@aastar/sdk 0.24.1 → 0.24.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dist/UserClient-4MRK2D7W.cjs +15 -0
  2. package/dist/{UserClient-S6LS3CB6.cjs.map → UserClient-4MRK2D7W.cjs.map} +1 -1
  3. package/dist/UserClient-DPJ6E2XL.js +6 -0
  4. package/dist/{UserClient-KYDCMAIU.js.map → UserClient-DPJ6E2XL.js.map} +1 -1
  5. package/dist/account.cjs +7 -7
  6. package/dist/account.js +2 -2
  7. package/dist/admin.cjs +3 -3
  8. package/dist/admin.js +2 -2
  9. package/dist/airaccount.cjs +102 -102
  10. package/dist/airaccount.js +2 -2
  11. package/dist/channel.cjs +6 -6
  12. package/dist/channel.js +2 -2
  13. package/dist/{chunk-BOVDJSMK.cjs → chunk-3FRNYRWI.cjs} +26 -26
  14. package/dist/{chunk-BOVDJSMK.cjs.map → chunk-3FRNYRWI.cjs.map} +1 -1
  15. package/dist/{chunk-VEAYV52I.cjs → chunk-4Q6FADF6.cjs} +9 -9
  16. package/dist/{chunk-VEAYV52I.cjs.map → chunk-4Q6FADF6.cjs.map} +1 -1
  17. package/dist/{chunk-654GQ7G7.js → chunk-7FLPD3V4.js} +3 -3
  18. package/dist/{chunk-654GQ7G7.js.map → chunk-7FLPD3V4.js.map} +1 -1
  19. package/dist/{chunk-2UC7UPHV.js → chunk-BPAAWQQA.js} +3 -3
  20. package/dist/{chunk-2UC7UPHV.js.map → chunk-BPAAWQQA.js.map} +1 -1
  21. package/dist/{chunk-BYVG7MO7.js → chunk-EEWLL7GE.js} +2 -2
  22. package/dist/{chunk-BYVG7MO7.js.map → chunk-EEWLL7GE.js.map} +1 -1
  23. package/dist/{chunk-D667CUUS.cjs → chunk-FUY4MHPM.cjs} +9 -9
  24. package/dist/{chunk-D667CUUS.cjs.map → chunk-FUY4MHPM.cjs.map} +1 -1
  25. package/dist/{chunk-HNJBQR5U.cjs → chunk-HP44S5U5.cjs} +5 -5
  26. package/dist/{chunk-HNJBQR5U.cjs.map → chunk-HP44S5U5.cjs.map} +1 -1
  27. package/dist/{chunk-MOJJ7QF6.cjs → chunk-IB3KOSHW.cjs} +2 -2
  28. package/dist/{chunk-MOJJ7QF6.cjs.map → chunk-IB3KOSHW.cjs.map} +1 -1
  29. package/dist/{chunk-VHY6R2PI.cjs → chunk-KYXXIKEI.cjs} +32 -32
  30. package/dist/{chunk-VHY6R2PI.cjs.map → chunk-KYXXIKEI.cjs.map} +1 -1
  31. package/dist/{chunk-A4ICWCHR.cjs → chunk-MANVOQY7.cjs} +5 -5
  32. package/dist/{chunk-A4ICWCHR.cjs.map → chunk-MANVOQY7.cjs.map} +1 -1
  33. package/dist/{chunk-NVYVTCHJ.cjs → chunk-MCDFQ5JH.cjs} +11 -11
  34. package/dist/{chunk-NVYVTCHJ.cjs.map → chunk-MCDFQ5JH.cjs.map} +1 -1
  35. package/dist/{chunk-7RVONA2R.js → chunk-O2CN77MV.js} +8 -8
  36. package/dist/{chunk-7RVONA2R.js.map → chunk-O2CN77MV.js.map} +1 -1
  37. package/dist/{chunk-DAMWXGKD.js → chunk-P3B6UTED.js} +3 -3
  38. package/dist/{chunk-DAMWXGKD.js.map → chunk-P3B6UTED.js.map} +1 -1
  39. package/dist/{chunk-WVJ4LQVB.js → chunk-PTVXBXZX.js} +3 -3
  40. package/dist/{chunk-WVJ4LQVB.js.map → chunk-PTVXBXZX.js.map} +1 -1
  41. package/dist/{chunk-RZ2M2RVP.js → chunk-PUE5GEKK.js} +3 -3
  42. package/dist/{chunk-RZ2M2RVP.js.map → chunk-PUE5GEKK.js.map} +1 -1
  43. package/dist/{chunk-72JZKARR.cjs → chunk-S7IUUQ5E.cjs} +6 -6
  44. package/dist/{chunk-72JZKARR.cjs.map → chunk-S7IUUQ5E.cjs.map} +1 -1
  45. package/dist/{chunk-JMW5AHLC.js → chunk-SX5GUCTF.js} +9 -9
  46. package/dist/{chunk-JMW5AHLC.js.map → chunk-SX5GUCTF.js.map} +1 -1
  47. package/dist/{chunk-5PH5CSM7.cjs → chunk-TGEVD7OR.cjs} +16 -16
  48. package/dist/{chunk-5PH5CSM7.cjs.map → chunk-TGEVD7OR.cjs.map} +1 -1
  49. package/dist/{chunk-WVOJV4Q5.cjs → chunk-TQIRRSGL.cjs} +4 -4
  50. package/dist/{chunk-WVOJV4Q5.cjs.map → chunk-TQIRRSGL.cjs.map} +1 -1
  51. package/dist/{chunk-PNBK2CLK.js → chunk-UJPW54CK.js} +3 -3
  52. package/dist/{chunk-PNBK2CLK.js.map → chunk-UJPW54CK.js.map} +1 -1
  53. package/dist/{chunk-GDH4DSVM.cjs → chunk-V23XPVHO.cjs} +12 -12
  54. package/dist/{chunk-GDH4DSVM.cjs.map → chunk-V23XPVHO.cjs.map} +1 -1
  55. package/dist/{chunk-PXQDAFXD.js → chunk-W73Y6JWZ.js} +6 -6
  56. package/dist/{chunk-PXQDAFXD.js.map → chunk-W73Y6JWZ.js.map} +1 -1
  57. package/dist/{chunk-LDARLWS3.js → chunk-XBZGVJ5K.js} +3 -3
  58. package/dist/{chunk-LDARLWS3.js.map → chunk-XBZGVJ5K.js.map} +1 -1
  59. package/dist/{chunk-WC25H5VG.js → chunk-Y5QM4LI4.js} +4 -4
  60. package/dist/{chunk-WC25H5VG.js.map → chunk-Y5QM4LI4.js.map} +1 -1
  61. package/dist/core.cjs +208 -208
  62. package/dist/core.js +1 -1
  63. package/dist/dapp.cjs +5 -5
  64. package/dist/dapp.js +2 -2
  65. package/dist/email.cjs +91 -0
  66. package/dist/email.cjs.map +1 -0
  67. package/dist/email.d.cts +115 -0
  68. package/dist/email.d.ts +115 -0
  69. package/dist/email.js +88 -0
  70. package/dist/email.js.map +1 -0
  71. package/dist/enduser.cjs +6 -6
  72. package/dist/enduser.js +3 -3
  73. package/dist/identity.cjs +5 -5
  74. package/dist/identity.js +2 -2
  75. package/dist/index.cjs +309 -309
  76. package/dist/index.js +15 -15
  77. package/dist/kms.cjs +102 -102
  78. package/dist/kms.js +2 -2
  79. package/dist/operator.cjs +6 -6
  80. package/dist/operator.js +2 -2
  81. package/dist/paymaster.cjs +15 -15
  82. package/dist/paymaster.js +2 -2
  83. package/dist/{src-UNS5B7FX.js → src-HKOFZ4V3.js} +4 -4
  84. package/dist/src-HKOFZ4V3.js.map +1 -0
  85. package/dist/{src-5URXSFKD.js → src-L2BLX34S.js} +3 -3
  86. package/dist/src-L2BLX34S.js.map +1 -0
  87. package/dist/{src-72GWEAPA.cjs → src-RM6DDR7K.cjs} +17 -17
  88. package/dist/src-RM6DDR7K.cjs.map +1 -0
  89. package/dist/{src-N72HAQXS.cjs → src-VO7TXJPG.cjs} +210 -210
  90. package/dist/src-VO7TXJPG.cjs.map +1 -0
  91. package/dist/tokens.cjs +3 -3
  92. package/dist/tokens.js +2 -2
  93. package/dist/x402.cjs +25 -25
  94. package/dist/x402.js +2 -2
  95. package/package.json +17 -2
  96. package/dist/UserClient-KYDCMAIU.js +0 -6
  97. package/dist/UserClient-S6LS3CB6.cjs +0 -15
  98. package/dist/src-5URXSFKD.js.map +0 -1
  99. package/dist/src-72GWEAPA.cjs.map +0 -1
  100. package/dist/src-N72HAQXS.cjs.map +0 -1
  101. package/dist/src-UNS5B7FX.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../airaccount/src/server/constants/entrypoint.ts","../../airaccount/src/server/config.ts","../../airaccount/src/server/interfaces/logger.ts","../../airaccount/src/server/providers/ethereum-provider.ts","../../airaccount/src/server/providers/typed-reads.ts","../../airaccount/src/server/services/account-init-config.ts","../../airaccount/src/server/services/account-manager.ts","../../airaccount/src/server/utils/execute-user-op.ts","../../airaccount/src/server/services/paymaster-manager.ts","../../airaccount/src/server/services/transfer-manager.ts","../../airaccount/src/server/services/bls-signature-service.ts","../../airaccount/src/server/services/token-service.ts","../../airaccount/src/server/services/wallet-manager.ts","../../airaccount/src/server/server-client.ts","../../airaccount/src/migration/viem/signatures.ts","../../airaccount/src/server/services/module-manager.ts","../../airaccount/src/server/services/session-key-service.ts","../../airaccount/src/server/services/guard-state-reader.ts","../../airaccount/src/server/utils/oapd.ts","../../airaccount/src/server/services/guard-checker.ts","../../airaccount/src/server/services/force-exit-service.ts","../../airaccount/src/server/services/recovery-service.ts","../../airaccount/src/server/services/eip7702-delegate-service.ts","../../airaccount/src/server/services/weighted-signature-service.ts","../../airaccount/src/server/services/agent-registry-service.ts","../../airaccount/src/server/services/erc8004-service.ts","../../airaccount/src/server/services/kms-http-client.ts","../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/nist.ts","../../airaccount/src/server/services/webauthn-ceremony.ts","../../airaccount/src/server/services/kms-signer.ts","../../airaccount/src/server/services/kms-agent-service.ts","../../airaccount/src/server/services/kms-session-service.ts","../../airaccount/src/server/services/kms-payment-signer.ts","../../airaccount/src/server/services/kms-monitor-service.ts","../../airaccount/src/server/adapters/memory-storage.ts","../../airaccount/src/server/adapters/local-wallet-signer.ts"],"names":["EntryPointVersion","parseAbi","getContract","concat","zeroAddress","ZERO32","EMPTY_P256","encodeFunctionData","numberToHex","parseEther","hexToBytes","parseUnits","viemHashMessage","viemRecoverAddress","keccak256","AIRACCOUNT_ABI_PARSED","FACTORY_ABI","ACCOUNT_ABI","axios","http"],"mappings":";;;;;;;;;AAMA,IAAM,YAAA,GAAe,oBAAoB,QAAQ,CAAA;AAE1C,IAAK,iBAAA,qBAAAA,kBAAAA,KAAL;AACL,EAAAA,mBAAA,MAAA,CAAA,GAAO,KAAA;AACP,EAAAA,mBAAA,MAAA,CAAA,GAAO,KAAA;AACP,EAAAA,mBAAA,MAAA,CAAA,GAAO,KAAA;AAHG,EAAA,OAAAA,kBAAAA;AAAA,CAAA,EAAA,iBAAA,IAAA,EAAA;AAcL,IAAM,oBAAA,GAAuB;AAAA,EAClC,CAAC,mBAAyB;AAAA,IACxB,OAAA,EAAS,4CAAA;AAAA,IACT,OAAA,EAAS,4CAAA;AAAA,I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AAI,QAAA,CAAS,MAAA,GAAS,IAAA,CAAK,MAAA,EAAQ;AACjC,MAAA,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,MAAA,EAAQ,QAAQ,CAAA;AACpC,MAAA,OAAO,IAAA;AAAA,IACT;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AAAA;AAAA,EAIA,MAAM,YAAA,GAAgD;AACpD,IAAA,OAAO,IAAA,CAAK,SAAA;AAAA,EACd;AAAA,EAEA,MAAM,uBAAuB,KAAA,EAAiC;AAC5D,IAAA,IAAA,CAAK,SAAA,GAAY;AAAA,MACf,GAAG,IAAA,CAAK,SAAA;AAAA,MACR,WAAA,EAAa;AAAA,QACX;AAAA;AACF,KACF;AAAA,EACF;AACF;AC3FO,IAAM,oBAAN,MAAkD;AAAA,EACtC,OAAA;AAAA,EAEjB,YAAY,UAAA,EAAoB;AAC9B,IAAA,IAAA,CAAK,OAAA,GAAU,oBAAoB,UAA2B,CAAA;AAAA,EAChE;AAAA,EAEA,MAAM,WAAW,OAAA,EAAyC;AACxD,IAAA,OAAO,KAAK,OAAA,CAAQ,OAAA;AAAA,EACtB;AAAA,EAEA,MAAM,WAAA,CACJ,OAAA,EACA,OAAA,EACA,IAAA,EACwB;AAIxB,IAAA,OAAO,IAAA,CAAK,QAAQ,WAAA,CAAY,EAAE,SAAS,EAAE,GAAA,EAAK,OAAA,EAAQ,EAAG,CAAA;AAAA,EAC/D;AAAA,EAEA,MAAM,aAAa,OAAA,EAAsD;AACvE,IAAA,OAAO,EAAE,OAAA,EAAS,IAAA,CAAK,OAAA,CAAQ,OAAA,EAAQ;AAAA,EACzC;AACF","file":"chunk-2UC7UPHV.js","sourcesContent":["import { CANONICAL_ADDRESSES } from \"@aastar/core\";\n\n// Single source of truth: derive AirAccount's CURRENT (non-deprecated) Sepolia\n// contract addresses from @aastar/core's CANONICAL_ADDRESSES. core is the\n// foundation package and never imports airaccount, so there is no circular dep.\n// See AIRACCOUNT_ADDRESSES below for the per-field key mapping.\nconst CORE_SEPOLIA = CANONICAL_ADDRESSES[11155111];\n\nexport enum EntryPointVersion {\n V0_6 = \"0.6\",\n V0_7 = \"0.7\",\n V0_8 = \"0.8\",\n}\n\nexport interface EntryPointConfig {\n version: EntryPointVersion;\n address: string;\n factoryAddress: string;\n validatorAddress: string;\n}\n\n/** Default EntryPoint addresses (same on Sepolia, Mainnet, and OP Mainnet). */\nexport const ENTRYPOINT_ADDRESSES = {\n [EntryPointVersion.V0_6]: {\n sepolia: \"0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789\",\n mainnet: \"0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789\",\n optimism: \"0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789\",\n },\n [EntryPointVersion.V0_7]: {\n sepolia: \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\",\n mainnet: \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\",\n optimism: \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\",\n },\n [EntryPointVersion.V0_8]: {\n sepolia: \"0x0576a174D229E3cFA37253523E645A78A0C91B57\",\n mainnet: \"0x0576a174D229E3cFA37253523E645A78A0C91B57\",\n optimism: \"0x0576a174D229E3cFA37253523E645A78A0C91B57\",\n },\n};\n\nexport const ENTRYPOINT_ABI_V6 = [\n \"function simulateValidation((address,uint256,bytes,bytes,uint256,uint256,uint256,uint256,uint256,bytes,bytes) userOp) external\",\n \"function getNonce(address sender, uint192 key) external view returns (uint256 nonce)\",\n \"function getUserOpHash((address,uint256,bytes,bytes,uint256,uint256,uint256,uint256,uint256,bytes,bytes) userOp) external view returns (bytes32)\",\n \"function handleOps((address,uint256,bytes,bytes,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[] ops, address payable beneficiary) external\",\n];\n\nexport const ENTRYPOINT_ABI_V7_V8 = [\n \"function simulateValidation((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes) packedUserOp) external\",\n \"function getNonce(address sender, uint192 key) external view returns (uint256 nonce)\",\n \"function getUserOpHash((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes) packedUserOp) external view returns (bytes32)\",\n \"function handleOps((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes)[] ops, address payable beneficiary) external\",\n];\n\nexport const FACTORY_ABI_V6 = [\n \"function getAddress(address creator, address signer, address validator, bool useAAStarValidator, uint256 salt) view returns (address)\",\n \"function createAccountWithAAStarValidator(address creator, address signer, address aaStarValidator, bool useAAStarValidator, uint256 salt) returns (address)\",\n];\n\nexport const FACTORY_ABI_V7_V8 = [\n \"function getAddress(address creator, address signer, address validator, bool useAAStarValidator, uint256 salt) view returns (address)\",\n \"function createAccount(address creator, address signer, address aaStarValidator, bool useAAStarValidator, uint256 salt) returns (address)\",\n];\n\nexport const ACCOUNT_ABI = [\n \"function execute(address dest, uint256 value, bytes calldata func) external\",\n];\n\nexport const VALIDATOR_ABI = [\n \"function getGasEstimate(uint256 nodeCount) external pure returns (uint256 gasEstimate)\",\n];\n\n// ── AirAccount Contract Addresses (Sepolia) ──────────────────────\n\nexport const AIRACCOUNT_ADDRESSES = {\n sepolia: {\n // M4 factory (legacy — 3-field InitConfig)\n factoryM4: \"0x914db0a849f55e68a726c72fd02b7114b1176d88\",\n // M5 factory r5 — 6-field InitConfig, guardian acceptance sigs required\n factoryM5: \"0xd72a236d84be6c388a8bc7deb64afd54704ae385\",\n /** @deprecated defaultCommunityGuardian was address(0); superseded by r6 and r4. Do not use for new accounts. */\n factoryM7r5Prev: \"0xa0007c5dB27548D8c1582773856dB1D123107383\",\n\n // ── Deprecated: r6 addresses (2026-03-29 deployment, superseded by r4 audit-final) ──────────\n // Retain for legacy account lookups and historical event indexing ONLY.\n // DO NOT use for new account creation — CREATE2 address will differ from r4.\n /** @deprecated Use {@link factory} (r4 audit-final) for new accounts. */\n factoryM7r6: \"0x42f82d77f9cf940686b6a64a369245cb563e0e85\",\n /** @deprecated Use {@link accountImpl} (r4 audit-final). */\n accountImplM7r6: \"0x2F1B4EB63143D338bE78d0AF878B806f075080c1\",\n /** @deprecated Use {@link compositeValidator} (r4 audit-final). */\n compositeValidatorM7r6: \"0x4135c539fec5e200fe9762b721f6829b2315cbe1\",\n /** @deprecated Use {@link tierGuardHook} (r4 audit-final). */\n tierGuardHookM7r6: \"0x73572e9e6138fd53465ee243e2fb4842cf86a787\",\n /** @deprecated Use {@link agentSessionKeyValidator} (r4 audit-final). */\n agentSessionKeyValidatorM7r6: \"0xa3e52db4b6e0a9d7cd5dd1414a90eedcf950e029\",\n\n // ── Deprecated: r4 audit-final (v0.16.0 era — pre-beta). Retained for existing account recovery. ─\n /** @deprecated Use factory (beta.4) for new accounts. */\n factoryM7r4: \"0x61bBAf9E1b8Fd78fF874776cFa50497dB9d43C3F\",\n /** @deprecated */\n accountImplM7r4: \"0xA674D308ce22230B70412b20Ee5a66fC6B24F49c\",\n /** @deprecated Use validatorRouter. */\n validatorRouterM7r4: \"0x730a162Ce3202b94cC5B74181B75b11eBB3045B1\",\n /** @deprecated */\n compositeValidatorM7r4: \"0xB65569950C48AA56dbe876915ca3605fD6FF2980\",\n /** @deprecated */\n tierGuardHookM7r4: \"0x67f878295cFF7451CBD2A775C4490607AF1b07d7\",\n /** @deprecated */\n agentSessionKeyValidatorM7r4: \"0x1F06961e133217801F92e1CF552187F594a32873\",\n\n // ── Current: derived from @aastar/core CANONICAL_ADDRESSES[11155111] ───────────\n // SINGLE SOURCE OF TRUTH. Do NOT hand-copy hex here. core is synced on every\n // protocol redeploy (currently AirAccount v0.20.0, Sepolia 2026-06-20),\n // and these fields re-derive automatically. The key mapping (airaccount field ←\n // core key) is asserted by entrypoint.addresses.test.ts so it can't silently drift.\n factory: CORE_SEPOLIA.airAccountFactoryV7,\n factoryM7: CORE_SEPOLIA.airAccountFactoryV7,\n accountImpl: CORE_SEPOLIA.airAccountV7Impl,\n validatorRouter: CORE_SEPOLIA.aaStarValidator,\n blsAlgorithm: CORE_SEPOLIA.aaStarBLSAlgorithm,\n blsAggregator: CORE_SEPOLIA.aaStarBLSAggregator,\n // SuperPaymaster proxy — same concept as core's `superPaymaster` proxy.\n superPaymaster: CORE_SEPOLIA.superPaymaster,\n sessionKeyValidator: CORE_SEPOLIA.sessionKeyValidator,\n forceExitModule: CORE_SEPOLIA.forceExitModule,\n airAccountDelegate: CORE_SEPOLIA.airAccountDelegate,\n airAccountExtension: CORE_SEPOLIA.airAccountExtension,\n agentRegistry: CORE_SEPOLIA.agentRegistry,\n calldataParserRegistry: CORE_SEPOLIA.calldataParserRegistry,\n // uniswapV3Parser is airaccount-specific (not in core) — keep hardcoded.\n uniswapV3Parser: \"0x5671810ac8aa1857397870e60232579cfc519515\",\n },\n};\n\n// ── AirAccount ABIs ──────────────────────────────────────────────\n\nexport const AIRACCOUNT_ABI = [\n // ── Core execution ──\n \"function execute(address dest, uint256 value, bytes calldata func) external\",\n \"function executeBatch(address[] calldata dest, uint256[] calldata value, bytes[] calldata func) external\",\n // ── ERC-7579 Module Management (M7.2) ──\n \"function installModule(uint256 moduleTypeId, address module, bytes calldata initData) external\",\n \"function uninstallModule(uint256 moduleTypeId, address module, bytes calldata deInitData) external\",\n \"function executeFromExecutor(bytes32 mode, bytes calldata executionCalldata) external returns (bytes[] memory returnData)\",\n // ── ERC-7579 Introspection ──\n \"function accountId() external pure returns (string memory)\",\n \"function supportsModule(uint256 moduleTypeId) external pure returns (bool)\",\n \"function isModuleInstalled(uint256 moduleTypeId, address module, bytes calldata additionalContext) external view returns (bool)\",\n // ── ERC-1271 / ERC-165 ──\n \"function isValidSignature(bytes32 hash, bytes calldata sig) external view returns (bytes4)\",\n \"function validateCompositeSignature(bytes32 hash, bytes calldata sig) external returns (uint256)\",\n \"function supportsInterface(bytes4 interfaceId) external pure returns (bool)\",\n // ── State readers ──\n \"function owner() external view returns (address)\",\n \"function entryPoint() external view returns (address)\",\n \"function validator() external view returns (address)\",\n \"function guard() external view returns (address)\",\n \"function guardianCount() external view returns (uint8)\",\n \"function guardians(uint256 index) external view returns (address)\",\n \"function p256KeyX() external view returns (bytes32)\",\n \"function p256KeyY() external view returns (bytes32)\",\n // abitype/viem human-readable ABIs use a bare parenthesised tuple `(...)`, not the\n // ethers-style `tuple(...)` keyword (which parseAbi rejects with \"Invalid ABI parameter\").\n \"function getConfigDescription() external view returns ((address accountOwner, address guardAddress, uint256 dailyLimit, uint256 dailyRemaining, uint256 tier1Limit, uint256 tier2Limit, address[3] guardianAddresses, uint8 guardianCount, bool hasP256Key, bool hasValidator, bool hasAggregator, bool hasActiveRecovery))\",\n // ── Owner / key management ──\n \"function setValidator(address _validator) external\",\n \"function setP256Key(bytes32 _x, bytes32 _y) external\",\n \"function setTierLimits(uint256 _tier1, uint256 _tier2) external\",\n \"function modifyTierLimitsWithGuardians(uint256 _tier1, uint256 _tier2, uint256 deadline, bytes[] calldata guardianSigs) external\",\n // ── Algorithm whitelist (v0.17.2-beta.4: single source of truth on the ACCOUNT, not the guard) ──\n \"function approvedAlgorithms(uint8 algId) external view returns (bool)\",\n \"function guardApproveAlgorithm(uint8 algId) external\",\n // ── Social / guardian recovery (F28) ──\n // Guardian set: owner adds guardians (max 3); removal needs RECOVERY_THRESHOLD guardian sigs.\n // Recovery lifecycle: a guardian proposes a new owner (starts the timelock), guardians\n // approve to reach 2-of-3 threshold, then anyone executes after the timelock; guardians\n // (not the owner) can vote to cancel. See RecoveryService for the full flow.\n \"function addGuardian(address _guardian) external\",\n \"function removeGuardian(uint8 index, bytes[] calldata guardianSigs) external\",\n \"function proposeRecovery(address _newOwner) external\",\n \"function approveRecovery() external\",\n \"function cancelRecovery() external\",\n \"function executeRecovery() external\",\n \"function activeRecovery() external view returns (address newOwner, uint256 proposedAt, uint256 approvalBitmap, uint256 cancellationBitmap)\",\n // ── Weighted-signature governance (algId 0x07) ──\n // WeightConfig tuple = (passkeyWeight, ecdsaWeight, blsWeight, guardian0Weight,\n // guardian1Weight, guardian2Weight, _padding, tier1Threshold, tier2Threshold, tier3Threshold)\n \"function setWeightConfig((uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold) config) external\",\n \"function proposeWeightChange((uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold) proposed) external\",\n \"function approveWeightChange() external\",\n \"function cancelWeightChange() external\",\n \"function executeWeightChange() external\",\n \"function weightConfig() external view returns (uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold)\",\n \"function pendingWeightChange() external view returns ((uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold) proposed, uint256 proposedAt, uint256 approvalBitmap)\",\n // ── ERC-4337 v0.7 bundler entrypoint (v0.17.2-beta.4) ──\n // Routes a UserOp whose callData starts with the executeUserOp selector to the account,\n // re-deriving the signature algId in-frame (fixes guard-account bundler gas estimation).\n // Only an inner execute()/executeBatch() may be wrapped (else reverts UnsupportedInnerSelector).\n \"function executeUserOp((address sender, uint256 nonce, bytes initCode, bytes callData, bytes32 accountGasLimits, uint256 preVerificationGas, bytes32 gasFees, bytes paymasterAndData, bytes signature) userOp, bytes32 userOpHash) external\",\n // ── Events ──\n \"event ModuleInstalled(uint256 indexed moduleTypeId, address indexed module)\",\n \"event ModuleUninstalled(uint256 indexed moduleTypeId, address indexed module)\",\n \"event OwnerChanged(address indexed oldOwner, address indexed newOwner)\",\n // v0.20.0 (#120): recovery events gained a trailing `uint8 guardianIdx` naming the\n // authorizing guardian slot (on P-256 relayer-submitted paths msg.sender is the relayer,\n // not the guardian). topic0 of these three events changed — decoders must use the new shape.\n \"event RecoveryProposed(address indexed newOwner, address indexed proposedBy, uint8 guardianIdx)\",\n \"event RecoveryApproved(address indexed newOwner, address indexed approvedBy, uint256 approvalCount, uint8 guardianIdx)\",\n \"event RecoveryCancelVoted(address indexed votedBy, uint256 cancelCount, uint8 guardianIdx)\",\n \"event RecoveryExecuted(address indexed oldOwner, address indexed newOwner)\",\n];\n\n// M7 factory ABI — ERC-7579 modules pre-installed, ERC-7828 chain-qualified addresses\n// v0.20.0 (#120): InitConfig inserted bytes32[3] guardianP256X, bytes32[3] guardianP256Y\n// (P-256 guardian keys) immediately after `address[3] guardians`. ECDSA-only accounts pass\n// [0x0,0x0,0x0] for both. Field ORDER is consensus-critical (CREATE2 address prediction).\n// InitConfig: (address[3] guardians, bytes32[3] guardianP256X, bytes32[3] guardianP256Y, uint256 dailyLimit, uint8[] approvedAlgIds, uint256 minDailyLimit, address[] initialTokens, (uint128 tier1Limit, uint128 tier2Limit, uint256 dailyLimit)[] initialTokenConfigs)\n// #118: TokenConfig packs tier1Limit/tier2Limit as uint128 (airaccount-contract #82) while dailyLimit\n// stays uint256. The selector is part of the type string, so even an EMPTY initialTokenConfigs must\n// declare (uint128,uint128,uint256) — declaring (uint256,uint256,uint256) yields the WRONG getAddress/\n// createAccount selector and reverts on the live v0.20.0 factory. Verified vs the canonical JSON ABI.\nexport const AIRACCOUNT_FACTORY_ABI = [\n // Full config creation\n \"function createAccount(address owner, uint256 salt, (address[3] guardians, bytes32[3] guardianP256X, bytes32[3] guardianP256Y, uint256 dailyLimit, uint8[] approvedAlgIds, uint256 minDailyLimit, address[] initialTokens, (uint128 tier1Limit, uint128 tier2Limit, uint256 dailyLimit)[] initialTokenConfigs) config) external returns (address)\",\n \"function getAddress(address owner, uint256 salt, (address[3] guardians, bytes32[3] guardianP256X, bytes32[3] guardianP256Y, uint256 dailyLimit, uint8[] approvedAlgIds, uint256 minDailyLimit, address[] initialTokens, (uint128 tier1Limit, uint128 tier2Limit, uint256 dailyLimit)[] initialTokenConfigs) config) external view returns (address)\",\n // Default guardian setup (requires guardian acceptance sigs — M5.3+)\n \"function createAccountWithDefaults(address owner, uint256 salt, address guardian1, bytes guardian1Sig, address guardian2, bytes guardian2Sig, uint256 dailyLimit) external returns (address)\",\n \"function getAddressWithDefaults(address owner, uint256 salt, address guardian1, address guardian2, uint256 dailyLimit) external view returns (address)\",\n // Agent-account creation (V7: agentKey + human-guardian2 co-owned account, registered in AgentRegistry)\n \"function createAgentAccount(address agentKey, bytes32 agentId, address guardian2, bytes guardian2Sig, bytes agentKeySig, uint48 deadline, uint256 dailyLimit) external returns (address account)\",\n \"function getAgentAddress(address humanOwner, address agentKey, bytes32 agentId) external view returns (address)\",\n \"function setAgentRegistry(address _agentRegistry) external\",\n \"function agentRegistry() external view returns (address)\",\n // M7 immutable state\n \"function implementation() external view returns (address)\",\n \"function entryPoint() external view returns (address)\",\n \"function defaultCommunityGuardian() external view returns (address)\",\n \"function defaultValidatorModule() external view returns (address)\",\n \"function defaultHookModule() external view returns (address)\",\n // M7.4 ERC-7828 chain-qualified address helpers\n \"function getChainQualifiedAddress(address account) external view returns (bytes32)\",\n \"function getAddressWithChainId(address owner, uint256 salt, (address[3] guardians, bytes32[3] guardianP256X, bytes32[3] guardianP256Y, uint256 dailyLimit, uint8[] approvedAlgIds, uint256 minDailyLimit, address[] initialTokens, (uint128 tier1Limit, uint128 tier2Limit, uint256 dailyLimit)[] initialTokenConfigs) config) external view returns (address account, bytes32 chainQualified)\",\n // Events\n \"event AccountCreated(address indexed account, address indexed owner, uint256 salt)\",\n];\n\n// v0.17.2-beta.4: the guard is now pure spend accounting. The algorithm whitelist\n// moved to the ACCOUNT (see AIRACCOUNT_ABI.approvedAlgorithms). checkTransaction/\n// checkTokenTransaction were renamed to recordSpend/recordTokenSpend, and\n// approveAlgorithm/approvedAlgorithms/AlgorithmNotApproved were removed from the guard.\nexport const GLOBAL_GUARD_ABI = [\n \"function remainingDailyAllowance() external view returns (uint256)\",\n \"function dailyLimit() external view returns (uint256)\",\n \"function account() external view returns (address)\",\n // Spend accounting (record* — algId dropped from the ETH path; kept for per-token tier math)\n \"function recordSpend(uint256 value) external returns (bool)\",\n \"function recordTokenSpend(address token, uint256 amount, uint8 algId) external returns (bool)\",\n];\n\nexport const ERC20_ABI = [\n \"function name() view returns (string)\",\n \"function symbol() view returns (string)\",\n \"function decimals() view returns (uint8)\",\n \"function totalSupply() view returns (uint256)\",\n \"function balanceOf(address owner) view returns (uint256)\",\n \"function transfer(address to, uint256 amount) returns (bool)\",\n \"function allowance(address owner, address spender) view returns (uint256)\",\n \"function approve(address spender, uint256 amount) returns (bool)\",\n];\n\n// ── M7 Module ABIs ───────────────────────────────────────────────\n\n// AgentSessionKeyValidator — ERC-7579 Validator module for AI agent capability delegation.\n// Supports velocity limits, selector allowlists, spend caps, and hierarchical delegation chains.\nexport const AGENT_SESSION_KEY_VALIDATOR_ABI = [\n // ERC-7579 lifecycle\n \"function onInstall(bytes calldata data) external\",\n \"function onUninstall(bytes calldata data) external\",\n \"function isInitialized(address smartAccount) external view returns (bool)\",\n // Session management\n \"function grantAgentSession(address sessionKey, (uint48 expiry, uint16 velocityLimit, uint32 velocityWindow, bool revoked, address[] callTargets, bytes4[] selectorAllowlist) cfg) external\",\n \"function delegateSession(address account, address subKey, (uint48 expiry, uint16 velocityLimit, uint32 velocityWindow, bool revoked, address[] callTargets, bytes4[] selectorAllowlist) subCfg) external\",\n \"function revokeAgentSession(address sessionKey) external\",\n // Validation\n \"function validateUserOp((address sender, uint256 nonce, bytes initCode, bytes callData, bytes32 accountGasLimits, uint256 preVerificationGas, bytes32 gasFees, bytes paymasterAndData, bytes signature) userOp, bytes32 userOpHash) external returns (uint256 validationData)\",\n \"function isValidSignatureWithSender(address sender, bytes32 hash, bytes calldata data) external pure returns (bytes4)\",\n // Enforcement\n \"function enforceSessionScope(address account, address sessionKey, address callTarget, bytes4 selector) external view\",\n // State readers\n \"function agentSessions(address account, address sessionKey) external view returns (uint48 expiry, uint16 velocityLimit, uint32 velocityWindow, bool revoked, address[] memory callTargets, bytes4[] memory selectorAllowlist)\",\n \"function sessionStates(address account, address sessionKey) external view returns (uint256 callCount, uint256 windowStart)\",\n \"function sessionKeyOwner(address sessionKey) external view returns (address)\",\n \"function delegatedBy(address account, address subKey) external view returns (address parentKey)\",\n // Events\n \"event AgentSessionGranted(address indexed account, address indexed sessionKey, uint48 expiry)\",\n \"event AgentSessionRevoked(address indexed account, address indexed sessionKey)\",\n \"event AgentSessionDelegated(address indexed parentAccount, address indexed parentKey, address indexed subKey, uint48 expiry)\",\n];\n\n// TierGuardHook — ERC-7579 Hook module wrapping tier-based spending enforcement.\n// Enforces per-execution ETH/token tier limits via preCheck/postCheck hooks.\nexport const TIER_GUARD_HOOK_ABI = [\n // ERC-7579 lifecycle\n \"function onInstall(bytes calldata data) external\",\n \"function onUninstall(bytes calldata data) external\",\n \"function isInitialized(address smartAccount) external view returns (bool)\",\n // ERC-7579 Hook interface\n \"function preCheck(address msgSender, uint256 msgValue, bytes calldata msgData) external returns (bytes memory hookData)\",\n \"function postCheck(bytes calldata hookData) external\",\n // State readers\n \"function accountGuard(address account) external view returns (address)\",\n \"function accountTier1(address account) external view returns (uint256)\",\n \"function accountTier2(address account) external view returns (uint256)\",\n];\n\n// AirAccountCompositeValidator — ERC-7579 Validator merging weighted + cumulative T2/T3 signature schemes.\n// Routes validation to the account's built-in algId dispatch via nonce-key routing.\nexport const AIR_ACCOUNT_COMPOSITE_VALIDATOR_ABI = [\n // ERC-7579 lifecycle\n \"function onInstall(bytes calldata data) external\",\n \"function onUninstall(bytes calldata data) external\",\n \"function isInitialized(address smartAccount) external view returns (bool)\",\n // ERC-7579 Validator interface\n \"function validateUserOp((address sender, uint256 nonce, bytes initCode, bytes callData, bytes32 accountGasLimits, uint256 preVerificationGas, bytes32 gasFees, bytes paymasterAndData, bytes signature) userOp, bytes32 userOpHash) external returns (uint256 validationData)\",\n \"function isValidSignatureWithSender(address sender, bytes32 hash, bytes calldata data) external view returns (bytes4 magicValue)\",\n];\n\n// ForceExitModule — ERC-7579 Executor module for guardian-gated L2→L1 emergency withdrawals.\n// Requires 2-of-3 guardian approvals before executing the force exit.\nexport const FORCE_EXIT_MODULE_ABI = [\n // ERC-7579 lifecycle\n \"function onInstall(bytes calldata data) external\",\n \"function onUninstall(bytes calldata data) external\",\n \"function isInitialized(address smartAccount) external view returns (bool)\",\n // Force exit flow\n \"function proposeForceExit(address target, uint256 value, bytes calldata data) external\",\n \"function approveForceExit(address account, bytes calldata guardianSig) external\",\n \"function executeForceExit(address account) external\",\n \"function cancelForceExit(address account) external\",\n // State readers\n \"function accountL2Type(address account) external view returns (uint8)\",\n \"function getPendingExit(address account) external view returns (address target, uint256 value, bytes memory data, uint256 proposedAt, uint256 approvalBitmap, address[3] memory guardians)\",\n // Events\n \"event ExitProposed(address indexed account, address indexed target, uint256 value)\",\n \"event ExitApproved(address indexed account, address indexed guardian, uint256 bitmap)\",\n \"event ExitExecuted(address indexed account, address indexed target, uint256 value)\",\n \"event ExitCancelled(address indexed account)\",\n];\n\n// ERC-7579 Module type IDs (spec: 1=validator, 2=executor, 3=fallback, 4=hook)\nexport const MODULE_TYPE = {\n VALIDATOR: 1,\n EXECUTOR: 2,\n FALLBACK: 3,\n HOOK: 4,\n} as const;\n\n// AirAccount algorithm IDs (algId values for signature dispatch)\nexport const ALG_ID = {\n BLS: 0x01,\n ECDSA: 0x02,\n P256: 0x03,\n CUMULATIVE_T2: 0x04, // P256 + BLS\n CUMULATIVE_T3: 0x05, // P256 + BLS + Guardian ECDSA\n COMBINED_T1: 0x06, // P256 AND ECDSA simultaneously\n WEIGHTED: 0x07, // Weighted multi-signature\n SESSION_KEY: 0x08, // Time-limited session key (SessionKeyValidator)\n AGENT_SESSION_KEY: 0x09, // AI agent session key (AgentSessionKeyValidator)\n} as const;\n\n// ── M6 继承合约 ABIs ─────────────────────────────────────────────\n\n// SessionKeyValidator — M6 基础 session key(algId=0x08)\n// 支持 ECDSA + P256 两种 session key,带合约/selector 作用域限制\nexport const SESSION_KEY_VALIDATOR_ABI = [\n // Session struct (8 fields) — authoritative tuple shape from\n // airaccount-contract/src/validators/SessionKeyValidator.sol and\n // packages/core/src/abis/SessionKeyValidator.json. The grant/build/read\n // functions take/return this tuple as a single arg — NOT flat params.\n // Canonical tuple type: (uint48,address,bytes4,bool,uint16,uint32,address[],bytes4[])\n // ECDSA session key\n \"function grantSession(address account, address sessionKey, (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist) cfg, bytes calldata ownerSig) external\",\n \"function grantSessionDirect(address account, address sessionKey, (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist) cfg) external\",\n \"function revokeSession(address account, address sessionKey) external\",\n \"function isSessionActive(address account, address sessionKey) external view returns (bool)\",\n \"function getSession(address account, address sessionKey) external view returns ((uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist))\",\n \"function buildGrantHash(address account, address sessionKey, (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist) cfg) external view returns (bytes32)\",\n // P256 session key\n \"function grantP256Session(address account, bytes32 p256KeyX, bytes32 p256KeyY, (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist) cfg, bytes calldata ownerSig) external\",\n \"function grantP256SessionDirect(address account, bytes32 p256KeyX, bytes32 p256KeyY, (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist) cfg) external\",\n \"function revokeP256Session(address account, bytes32 p256KeyX, bytes32 p256KeyY) external\",\n \"function isP256SessionActive(address account, bytes32 p256KeyX, bytes32 p256KeyY) external view returns (bool)\",\n \"function getP256Session(address account, bytes32 p256KeyHash) external view returns ((uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist))\",\n \"function buildP256GrantHash(address account, bytes32 p256KeyX, bytes32 p256KeyY, (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist) cfg) external view returns (bytes32)\",\n // Events\n \"event SessionGranted(address indexed account, address indexed sessionKey, uint48 expiry, address contractScope, bytes4 selectorScope)\",\n \"event SessionRevoked(address indexed account, address indexed sessionKey)\",\n \"event P256SessionGranted(address indexed account, bytes32 indexed p256KeyHash, uint48 expiry)\",\n \"event P256SessionRevoked(address indexed account, bytes32 indexed p256KeyHash)\",\n];\n\n// CalldataParserRegistry — DeFi 协议解析器注册表\n// 让 guard 能识别 Uniswap/Railgun 等协议的 calldata,精确核算 token 消费\nexport const CALLDATA_PARSER_REGISTRY_ABI = [\n \"function registerParser(address dest, address parser) external\",\n \"function getParser(address dest) external view returns (address)\",\n \"function transferOwnership(address newOwner) external\",\n \"function parserFor(address dest) external view returns (address)\",\n \"event ParserRegistered(address indexed dest, address indexed parser)\",\n \"event OwnershipTransferred(address indexed previousOwner, address indexed newOwner)\",\n];\n\n// AirAccountDelegate — EIP-7702 EOA 委托为 AirAccount(M7 新增)\n// EOA 通过 EIP-7702 授权后,调用 initialize() 即获得 AirAccount 能力\nexport const AIR_ACCOUNT_DELEGATE_ABI = [\n // EIP-7702 初始化(仅限 EOA 自身调用)\n \"function initialize(address guardian1, bytes calldata g1Sig, address guardian2, bytes calldata g2Sig, uint256 dailyLimit) external\",\n // ERC-4337 执行\n \"function validateUserOp((address sender, uint256 nonce, bytes initCode, bytes callData, bytes32 accountGasLimits, uint256 preVerificationGas, bytes32 gasFees, bytes paymasterAndData, bytes signature) userOp, bytes32 userOpHash, uint256 missingAccountFunds) external returns (uint256)\",\n \"function execute(address dest, uint256 value, bytes calldata data) external\",\n \"function executeBatch(address[] calldata dest, uint256[] calldata value, bytes[] calldata data) external\",\n // 社会恢复(Rescue,EIP-7702 术语避免与 AirAccount Recovery 混淆)\n \"function initiateRescue(address rescueTo) external\",\n \"function approveRescue() external\",\n \"function executeRescue() external\",\n // Events\n \"event DelegateInitialized(address indexed eoa, address guard, address g1, address g2)\",\n \"event RescueInitiated(address indexed eoa, address rescueTo, address indexed initiator)\",\n \"event RescueApproved(address indexed eoa, address indexed guardian, uint8 approvals)\",\n \"event RescueExecuted(address indexed eoa, address rescueTo, uint256 ethAmount)\",\n \"event RescueCancelled(address indexed eoa)\",\n];\n","import { IStorageAdapter } from \"./interfaces/storage-adapter\";\nimport { ISignerAdapter } from \"./interfaces/signer-adapter\";\nimport { ILogger } from \"./interfaces/logger\";\nimport { AIRACCOUNT_ADDRESSES, ENTRYPOINT_ADDRESSES, EntryPointVersion } from \"./constants/entrypoint\";\n\n/**\n * Per-version EntryPoint configuration.\n */\nexport interface EntryPointVersionConfig {\n entryPointAddress: string;\n factoryAddress: string;\n validatorAddress: string;\n}\n\n/**\n * Server SDK configuration — replaces NestJS ConfigService.\n */\nexport interface ServerConfig {\n /** Main network RPC URL. */\n rpcUrl: string;\n /** Bundler RPC URL (e.g. Pimlico, StackUp). */\n bundlerRpcUrl: string;\n /** Chain ID of the target network. */\n chainId: number;\n\n /** EntryPoint configurations — at least one version must be provided. */\n entryPoints: {\n v06?: EntryPointVersionConfig;\n v07?: EntryPointVersionConfig;\n v08?: EntryPointVersionConfig;\n };\n\n /** Default EntryPoint version to use when not specified. */\n defaultVersion?: \"0.6\" | \"0.7\" | \"0.8\";\n\n /** BLS signer seed nodes for gossip discovery. */\n blsSeedNodes?: string[];\n /** Timeout for BLS node discovery in ms. */\n blsDiscoveryTimeout?: number;\n\n /** KMS endpoint URL (optional, for KMS-based signing). */\n kmsEndpoint?: string;\n /** Whether KMS signing is enabled. */\n kmsEnabled?: boolean;\n /** KMS API key for authenticated requests. */\n kmsApiKey?: string;\n\n /** Storage adapter (required). */\n storage: IStorageAdapter;\n /** Signer adapter (required). */\n signer: ISignerAdapter;\n /** Logger (optional, defaults to ConsoleLogger). */\n logger?: ILogger;\n}\n\n/** AirAccount contract version selection.\n * - \"M7\" — r4 audit-final (default). Use for all new account creation.\n * - \"M7r6\" — r6 deployment (2026-03-29, superseded). Use ONLY to recover existing r6-deployed accounts.\n * - \"M5\" — legacy 6-field InitConfig deployment.\n */\nexport type AirAccountVersion = \"M5\" | \"M7\" | \"M7r6\";\n\n/**\n * Build a pre-configured EntryPointVersionConfig for Sepolia using a known AirAccount deployment.\n * Eliminates the need to look up contract addresses manually.\n *\n * @example\n * // Use M7 r4 audit-final (default)\n * const config = { entryPoints: { v07: sepoliaV07Config() }, ... };\n *\n * // Recover an existing r6-deployed account (do NOT use for new accounts)\n * const config = { entryPoints: { v07: sepoliaV07Config(\"M7r6\") }, ... };\n *\n * // Use M5 legacy\n * const config = { entryPoints: { v07: sepoliaV07Config(\"M5\") }, ... };\n */\nexport function sepoliaV07Config(version: AirAccountVersion = \"M7\"): EntryPointVersionConfig {\n const factoryAddress =\n version === \"M5\"\n ? AIRACCOUNT_ADDRESSES.sepolia.factoryM5\n : version === \"M7r6\"\n ? AIRACCOUNT_ADDRESSES.sepolia.factoryM7r6\n : AIRACCOUNT_ADDRESSES.sepolia.factory; // \"M7\" = r4 audit-final (default)\n\n return {\n entryPointAddress: ENTRYPOINT_ADDRESSES[EntryPointVersion.V0_7].sepolia,\n factoryAddress,\n validatorAddress: AIRACCOUNT_ADDRESSES.sepolia.validatorRouter,\n };\n}\n\n/**\n * Validate a ServerConfig and throw descriptive errors for missing fields.\n */\nexport function validateConfig(config: ServerConfig): void {\n if (!config.rpcUrl) {\n throw new Error(\"ServerConfig: rpcUrl is required\");\n }\n if (!config.bundlerRpcUrl) {\n throw new Error(\"ServerConfig: bundlerRpcUrl is required\");\n }\n if (!config.chainId) {\n throw new Error(\"ServerConfig: chainId is required\");\n }\n\n const { entryPoints } = config;\n if (!entryPoints || (!entryPoints.v06 && !entryPoints.v07 && !entryPoints.v08)) {\n throw new Error(\"ServerConfig: at least one entryPoint version must be configured\");\n }\n\n for (const [key, ep] of Object.entries(entryPoints)) {\n if (ep) {\n if (!ep.entryPointAddress) {\n throw new Error(`ServerConfig: entryPoints.${key}.entryPointAddress is required`);\n }\n if (!ep.factoryAddress) {\n throw new Error(`ServerConfig: entryPoints.${key}.factoryAddress is required`);\n }\n if (!ep.validatorAddress) {\n throw new Error(`ServerConfig: entryPoints.${key}.validatorAddress is required`);\n }\n }\n }\n\n if (!config.storage) {\n throw new Error(\"ServerConfig: storage adapter is required\");\n }\n if (!config.signer) {\n throw new Error(\"ServerConfig: signer adapter is required\");\n }\n}\n","/**\n * Optional logger interface for server SDK.\n * Implement this to integrate with your application's logging framework.\n */\nexport interface ILogger {\n debug(message: string, ...args: unknown[]): void;\n log(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n}\n\n/**\n * Default console logger used when no custom logger is provided.\n */\nexport class ConsoleLogger implements ILogger {\n constructor(private readonly prefix: string = \"[YAAA]\") {}\n\n debug(message: string, ...args: unknown[]): void {\n console.debug(`${this.prefix} ${message}`, ...args);\n }\n\n log(message: string, ...args: unknown[]): void {\n console.log(`${this.prefix} ${message}`, ...args);\n }\n\n warn(message: string, ...args: unknown[]): void {\n console.warn(`${this.prefix} ${message}`, ...args);\n }\n\n error(message: string, ...args: unknown[]): void {\n console.error(`${this.prefix} ${message}`, ...args);\n }\n}\n\n/**\n * Silent logger that suppresses all output.\n */\nexport class SilentLogger implements ILogger {\n debug(): void {}\n log(): void {}\n warn(): void {}\n error(): void {}\n}\n","import {\n createPublicClient,\n http,\n getContract,\n formatEther,\n parseUnits,\n type PublicClient,\n type Address,\n type Abi,\n} from \"viem\";\n// EntryPoint/AirAccount ABIs are local human-readable signatures (not in @aastar/core);\n// parseAbi is required to feed them to viem's getContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { ServerConfig, EntryPointVersionConfig } from \"../config\";\nimport {\n EntryPointVersion,\n ENTRYPOINT_ABI_V6,\n ENTRYPOINT_ABI_V7_V8,\n FACTORY_ABI_V6,\n AIRACCOUNT_FACTORY_ABI,\n ACCOUNT_ABI,\n AIRACCOUNT_ABI,\n VALIDATOR_ABI,\n AGENT_SESSION_KEY_VALIDATOR_ABI,\n TIER_GUARD_HOOK_ABI,\n AIR_ACCOUNT_COMPOSITE_VALIDATOR_ABI,\n FORCE_EXIT_MODULE_ABI,\n AIRACCOUNT_ADDRESSES,\n} from \"../constants/entrypoint\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\nimport { UserOperation, PackedUserOperation } from \"../../core/types\";\n\n/**\n * A viem contract instance bound to a read-only PublicClient.\n *\n * The EntryPoint/AirAccount ABIs are loaded from human-readable signatures via\n * `parseAbi`, which yields the loosely-typed `Abi` shape. As a result `read`/`write`\n * method access is not statically typed per-function; callers index by name and the\n * returned value is `unknown` (cast at the call site). This mirrors the dynamic\n * surface that `ethers.Contract` previously exposed.\n */\nexport type ViemContractMethods = Record<string, (...args: unknown[]) => Promise<unknown>>;\nexport interface ViemContract {\n address: Address;\n abi: Abi;\n /** Read (view/pure) calls: `contract.read.fnName([...args])`. */\n read: ViemContractMethods;\n /** State-changing calls (requires a wallet client — not provided by this read-only hub). */\n write: ViemContractMethods;\n estimateGas: ViemContractMethods;\n simulate: ViemContractMethods;\n getEvents: ViemContractMethods;\n}\n\n/**\n * Unified Ethereum provider — replaces NestJS EthereumService.\n * Manages RPC + Bundler clients (viem) and contract interactions.\n */\nexport class EthereumProvider {\n /** Main-network read client. Pass to viem getContract / readContract calls. */\n private readonly provider: PublicClient;\n /** Bundler client — used only for raw eth_ / pimlico_ userOp JSON-RPC. */\n private readonly bundlerProvider: PublicClient;\n private readonly config: ServerConfig;\n private readonly logger: ILogger;\n\n constructor(config: ServerConfig) {\n this.config = config;\n this.logger = config.logger ?? new ConsoleLogger(\"[EthereumProvider]\");\n this.provider = createPublicClient({ transport: http(config.rpcUrl) });\n this.bundlerProvider = createPublicClient({ transport: http(config.bundlerRpcUrl) });\n }\n\n /** Returns the viem PublicClient for the main network RPC. */\n getProvider(): PublicClient {\n return this.provider;\n }\n\n /** Returns the viem PublicClient bound to the bundler RPC (raw .request only). */\n getBundlerProvider(): PublicClient {\n return this.bundlerProvider;\n }\n\n /** EVM chain id from the validated ServerConfig (deterministic — no RPC round-trip). */\n getChainId(): number {\n return this.config.chainId;\n }\n\n /**\n * Raw bundler JSON-RPC call. The bundler exposes non-standard methods\n * (eth_sendUserOperation, pimlico_getUserOperationGasPrice, ...) that are not in\n * viem's typed RPC schema, so we go through the transport's request fn untyped.\n */\n private async bundlerRequest<T = unknown>(method: string, params: unknown[]): Promise<T> {\n return (await this.bundlerProvider.request({\n method: method as never,\n params: params as never,\n })) as T;\n }\n\n // ── Config helpers ──────────────────────────────────────────────\n\n private getVersionConfig(version: EntryPointVersion): EntryPointVersionConfig {\n const map: Record<EntryPointVersion, EntryPointVersionConfig | undefined> = {\n [EntryPointVersion.V0_6]: this.config.entryPoints.v06,\n [EntryPointVersion.V0_7]: this.config.entryPoints.v07,\n [EntryPointVersion.V0_8]: this.config.entryPoints.v08,\n };\n const versionConfig = map[version];\n if (!versionConfig) {\n throw new Error(`EntryPoint version ${version} is not configured`);\n }\n return versionConfig;\n }\n\n getEntryPointAddress(version: EntryPointVersion): string {\n return this.getVersionConfig(version).entryPointAddress;\n }\n\n getFactoryAddress(version: EntryPointVersion): string {\n return this.getVersionConfig(version).factoryAddress;\n }\n\n getValidatorAddress(version: EntryPointVersion): string {\n return this.getVersionConfig(version).validatorAddress;\n }\n\n getDefaultVersion(): EntryPointVersion {\n const v = this.config.defaultVersion;\n if (v === \"0.7\") return EntryPointVersion.V0_7;\n if (v === \"0.8\") return EntryPointVersion.V0_8;\n return EntryPointVersion.V0_6;\n }\n\n // ── Contract factories ──────────────────────────────────────────\n\n /** Build a read-only viem contract bound to the main-network PublicClient. */\n private contractAt(address: string, abi: readonly string[]): ViemContract {\n return getContract({\n address: address as Address,\n abi: parseAbi(abi as readonly string[]),\n client: this.provider,\n }) as unknown as ViemContract;\n }\n\n getFactoryContract(version: EntryPointVersion = EntryPointVersion.V0_6): ViemContract {\n const address = this.getFactoryAddress(version);\n const abi = version === EntryPointVersion.V0_6 ? FACTORY_ABI_V6 : AIRACCOUNT_FACTORY_ABI;\n return this.contractAt(address, abi);\n }\n\n getEntryPointContract(version: EntryPointVersion = EntryPointVersion.V0_6): ViemContract {\n const address = this.getEntryPointAddress(version);\n const abi = version === EntryPointVersion.V0_6 ? ENTRYPOINT_ABI_V6 : ENTRYPOINT_ABI_V7_V8;\n return this.contractAt(address, abi);\n }\n\n getValidatorContract(version: EntryPointVersion = EntryPointVersion.V0_6): ViemContract {\n const address = this.getValidatorAddress(version);\n return this.contractAt(address, VALIDATOR_ABI);\n }\n\n getAccountContract(address: string): ViemContract {\n return this.contractAt(address, AIRACCOUNT_ABI);\n }\n\n // ── M7 Module contracts ─────────────────────────────────────────\n\n // M7 r4 module helpers — addresses renamed to *M7r4 suffix in beta.3 to avoid ambiguity.\n // These methods are retained for backwards compatibility; callers should pass an explicit address.\n getAgentSessionKeyValidatorContract(address: string = AIRACCOUNT_ADDRESSES.sepolia.agentSessionKeyValidatorM7r4): ViemContract {\n return this.contractAt(address, AGENT_SESSION_KEY_VALIDATOR_ABI);\n }\n\n getTierGuardHookContract(address: string = AIRACCOUNT_ADDRESSES.sepolia.tierGuardHookM7r4): ViemContract {\n return this.contractAt(address, TIER_GUARD_HOOK_ABI);\n }\n\n getCompositeValidatorContract(address: string = AIRACCOUNT_ADDRESSES.sepolia.compositeValidatorM7r4): ViemContract {\n return this.contractAt(address, AIR_ACCOUNT_COMPOSITE_VALIDATOR_ABI);\n }\n\n getForceExitModuleContract(address: string): ViemContract {\n return this.contractAt(address, FORCE_EXIT_MODULE_ABI);\n }\n\n // ── On-chain queries ────────────────────────────────────────────\n\n async getBalance(address: string): Promise<string> {\n const balance = await this.provider.getBalance({ address: address as Address });\n return formatEther(balance);\n }\n\n async getNonce(\n accountAddress: string,\n key: number = 0,\n version: EntryPointVersion = EntryPointVersion.V0_6\n ): Promise<bigint> {\n const entryPoint = this.getEntryPointContract(version);\n return (await (entryPoint.read as Record<string, (args: unknown[]) => Promise<unknown>>).getNonce([\n accountAddress as Address,\n BigInt(key),\n ])) as bigint;\n }\n\n async getUserOpHash(\n userOp: UserOperation | PackedUserOperation,\n version: EntryPointVersion = EntryPointVersion.V0_6\n ): Promise<string> {\n const entryPoint = this.getEntryPointContract(version);\n const read = entryPoint.read as Record<string, (args: unknown[]) => Promise<unknown>>;\n\n if (version === EntryPointVersion.V0_6) {\n const op = userOp as UserOperation;\n // uint256 fields coerced to bigint for viem (byte-identical to ethers' BigNumberish handling).\n const userOpArray = [\n op.sender,\n BigInt(op.nonce),\n op.initCode || \"0x\",\n op.callData,\n BigInt(op.callGasLimit),\n BigInt(op.verificationGasLimit),\n BigInt(op.preVerificationGas),\n BigInt(op.maxFeePerGas),\n BigInt(op.maxPriorityFeePerGas),\n op.paymasterAndData || \"0x\",\n \"0x\", // Always use empty signature for hash calculation\n ];\n return (await read.getUserOpHash([userOpArray])) as string;\n } else {\n const packedOp = userOp as PackedUserOperation;\n const packedOpArray = [\n packedOp.sender,\n BigInt(packedOp.nonce),\n packedOp.initCode || \"0x\",\n packedOp.callData,\n packedOp.accountGasLimits,\n BigInt(packedOp.preVerificationGas),\n packedOp.gasFees,\n packedOp.paymasterAndData || \"0x\",\n \"0x\",\n ];\n return (await read.getUserOpHash([packedOpArray])) as string;\n }\n }\n\n // ── Bundler RPC ─────────────────────────────────────────────────\n\n async estimateUserOperationGas(\n userOp: unknown,\n version: EntryPointVersion = EntryPointVersion.V0_6\n ): Promise<{ callGasLimit: string; verificationGasLimit: string; preVerificationGas: string }> {\n try {\n return await this.bundlerRequest(\"eth_estimateUserOperationGas\", [\n userOp,\n this.getEntryPointAddress(version),\n ]);\n } catch {\n return {\n callGasLimit: \"0x249f0\",\n verificationGasLimit: \"0x3d0900\", // 4M — enough for M4 factory deployment + BLS verification\n preVerificationGas: \"0x11170\",\n };\n }\n }\n\n async sendUserOperation(\n userOp: unknown,\n version: EntryPointVersion = EntryPointVersion.V0_6\n ): Promise<string> {\n return await this.bundlerRequest(\"eth_sendUserOperation\", [\n userOp,\n this.getEntryPointAddress(version),\n ]);\n }\n\n async getUserOperationReceipt(userOpHash: string): Promise<unknown> {\n return await this.bundlerRequest(\"eth_getUserOperationReceipt\", [userOpHash]);\n }\n\n async waitForUserOp(userOpHash: string, maxAttempts: number = 60): Promise<string> {\n const pollInterval = 2000;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n try {\n const receipt = (await this.getUserOperationReceipt(userOpHash)) as Record<\n string,\n unknown\n > | null;\n if (receipt) {\n const txHash =\n (receipt.transactionHash as string) ||\n ((receipt.receipt as Record<string, unknown>)?.transactionHash as string);\n if (txHash) return txHash;\n }\n } catch {\n // Continue polling\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error(`UserOp timeout: ${userOpHash}`);\n }\n\n async getUserOperationGasPrice(): Promise<{\n maxFeePerGas: string;\n maxPriorityFeePerGas: string;\n }> {\n try {\n const gasPrice = await this.bundlerRequest<{\n fast: { maxFeePerGas: string; maxPriorityFeePerGas: string };\n }>(\"pimlico_getUserOperationGasPrice\", []);\n return {\n maxFeePerGas: gasPrice.fast.maxFeePerGas,\n maxPriorityFeePerGas: gasPrice.fast.maxPriorityFeePerGas,\n };\n } catch {\n try {\n const feeData = await this.provider.estimateFeesPerGas();\n const baseFee = feeData.maxFeePerGas || parseUnits(\"20\", 9); // gwei\n const priorityFee = feeData.maxPriorityFeePerGas || parseUnits(\"2\", 9); // gwei\n const maxFeePerGas = (baseFee * 3n) / 2n;\n const maxPriorityFeePerGas = (priorityFee * 3n) / 2n;\n return {\n maxFeePerGas: \"0x\" + maxFeePerGas.toString(16),\n maxPriorityFeePerGas: \"0x\" + maxPriorityFeePerGas.toString(16),\n };\n } catch {\n return {\n maxFeePerGas: \"0x\" + parseUnits(\"3\", 9).toString(16), // gwei\n maxPriorityFeePerGas: \"0x\" + parseUnits(\"1\", 9).toString(16), // gwei\n };\n }\n }\n }\n}\n","import type { Address, Hex } from \"viem\";\nimport type { ViemContract } from \"./ethereum-provider\";\n\n/**\n * Audited boundary for HIGH-risk contract reads.\n *\n * Background: the ethers->viem migration loads the EntryPoint / AirAccount /\n * validator / guard ABIs from human-readable signatures via `parseAbi`, then\n * widens them to the loose `Abi` shape (`ViemContract.read` is a bare\n * `Record<string, (...args) => Promise<unknown>>`). On that surface a wrong\n * function name, a wrong argument type (e.g. a JS `number` where a `uint256`\n * `bigint` is required, which can silently truncate outside the 53-bit safe\n * range), or a wrong decode shape is NOT caught at compile time.\n *\n * This module confines every such cast to one reviewable place. It only wraps\n * reads whose result flows into a money-movement / signing / authorization\n * decision (per the risk framework): gas math that gets signed, the\n * counterfactual account address that holds funds, the guard / tier / algorithm\n * gates that allow or deny a transfer, and the grant hashes the account owner\n * signs to authorize a session key. Pure display / logging reads are\n * deliberately left on the loose surface to keep this boundary small.\n *\n * Each wrapper declares explicit parameter types (bigint for every uint256) and\n * an explicit return type next to the on-chain function name it targets, so the\n * single `as` cast is documented against the real ABI signature.\n */\n\n/** Resolve a loosely-typed read method by name. The only cast escape hatch. */\nfunction readFn(contract: ViemContract, name: string): (args: readonly unknown[]) => Promise<unknown> {\n return contract.read[name] as (args: readonly unknown[]) => Promise<unknown>;\n}\n\n// ── Validator: gas estimate folded into the signed UserOp gas budget ──────────\n\n/**\n * `getGasEstimate(uint256 nodeCount) view returns (uint256)`.\n * `nodeCount` MUST be a bigint — the loose surface would accept a JS number and\n * risk silent truncation for a uint256 arg.\n */\nexport function readValidatorGasEstimate(\n validator: ViemContract,\n nodeCount: bigint\n): Promise<bigint> {\n return readFn(validator, \"getGasEstimate\")([nodeCount]) as Promise<bigint>;\n}\n\n// ── Factory: counterfactual account address (= fund-custody address) ──────────\n\n/**\n * `getAddress(address owner, uint256 salt, InitConfig config) view returns (address)`.\n * The predicted address is where user funds are sent before deployment, so a\n * mistyped `salt` (uint256) would yield a different, unrecoverable address.\n */\nexport function readPredictedAddress(\n factory: ViemContract,\n owner: string,\n salt: bigint,\n config: readonly unknown[]\n): Promise<Address> {\n return readFn(factory, \"getAddress\")([owner, salt, config]) as Promise<Address>;\n}\n\n/**\n * `getAddressWithDefaults(address owner, uint256 salt, address guardian1,\n * address guardian2, uint256 dailyLimit) view returns (address)`.\n * Both `salt` and `dailyLimit` are uint256 and MUST be bigint.\n */\nexport function readPredictedAddressWithDefaults(\n factory: ViemContract,\n owner: string,\n salt: bigint,\n guardian1: string,\n guardian2: string,\n dailyLimit: bigint\n): Promise<Address> {\n return readFn(factory, \"getAddressWithDefaults\")([\n owner,\n salt,\n guardian1,\n guardian2,\n dailyLimit,\n ]) as Promise<Address>;\n}\n\n// ── Account: authorization gates consumed by GuardChecker.preCheck ────────────\n\n/**\n * `tier1Limit()` / `tier2Limit()` (both uint256). These resolve the transfer\n * tier -> signing algId, gating which algorithm may authorize the transfer.\n */\nexport async function readAccountTierLimits(\n account: ViemContract\n): Promise<{ tier1Limit: bigint; tier2Limit: bigint }> {\n const [tier1Limit, tier2Limit] = await Promise.all([\n readFn(account, \"tier1Limit\")([]) as Promise<bigint>,\n readFn(account, \"tier2Limit\")([]) as Promise<bigint>,\n ]);\n return { tier1Limit, tier2Limit };\n}\n\n/**\n * `approvedAlgorithms(uint8 algId) view returns (bool)`. Gates whether the\n * signing algorithm for the resolved tier is allowed to authorize the tx.\n * `algId` is a uint8 (small enum), so a JS number is the correct ABI type.\n */\nexport function readAlgorithmApproved(account: ViemContract, algId: number): Promise<boolean> {\n return readFn(account, \"approvedAlgorithms\")([algId]) as Promise<boolean>;\n}\n\n/**\n * `getConfigDescription()` -> named struct; we read only `guardAddress`, which\n * decides whether the per-account spending guard is enforced at all.\n */\nexport async function readAccountGuardAddress(account: ViemContract): Promise<Address> {\n const config = (await readFn(account, \"getConfigDescription\")([])) as { guardAddress: Address };\n return config.guardAddress;\n}\n\n// ── Guard: daily spend allowance gate ─────────────────────────────────────────\n\n/**\n * `dailyLimit()` / `remainingDailyAllowance()` (both uint256). These cap the\n * value that may move per day; comparing the wrong (mistyped) value would let an\n * over-limit transfer through the pre-check.\n */\nexport async function readGuardDailyAllowance(\n guard: ViemContract\n): Promise<{ dailyLimit: bigint; dailyRemaining: bigint }> {\n const [dailyLimit, dailyRemaining] = await Promise.all([\n readFn(guard, \"dailyLimit\")([]) as Promise<bigint>,\n readFn(guard, \"remainingDailyAllowance\")([]) as Promise<bigint>,\n ]);\n return { dailyLimit, dailyRemaining };\n}\n\n// ── SessionKeyValidator: grant hashes the account owner SIGNS ─────────────────\n\n/** The on-chain `Session` struct passed to the grant-hash builders. */\nexport interface SessionGrantConfig {\n expiry: number;\n contractScope: string;\n selectorScope: string;\n revoked: boolean;\n velocityLimit: number;\n velocityWindow: number;\n callTargets: string[];\n selectorAllowlist: string[];\n}\n\n/**\n * `buildGrantHash(address account, address sessionKey, Session cfg) view returns (bytes32)`.\n * The returned digest is signed by the account owner to authorize the grant — a\n * wrong function name or decode shape would have the owner sign the wrong hash.\n */\nexport function readBuildGrantHash(\n validator: ViemContract,\n account: string,\n sessionKey: string,\n cfg: SessionGrantConfig\n): Promise<Hex> {\n return readFn(validator, \"buildGrantHash\")([account, sessionKey, cfg]) as Promise<Hex>;\n}\n\n/**\n * `buildP256GrantHash(address account, bytes32 keyX, bytes32 keyY, Session cfg)\n * view returns (bytes32)`. Owner-signed authorization digest for a P256 grant.\n */\nexport function readBuildP256GrantHash(\n validator: ViemContract,\n account: string,\n keyX: string,\n keyY: string,\n cfg: SessionGrantConfig\n): Promise<Hex> {\n return readFn(validator, \"buildP256GrantHash\")([account, keyX, keyY, cfg]) as Promise<Hex>;\n}\n","import { type Address, type Hex } from \"viem\";\nimport { buildInitConfig, type GuardianSpec, type InitConfig } from \"@aastar/core\";\nimport type { AccountRecord } from \"../interfaces/storage-adapter\";\n\n/**\n * Shared helpers for the FULL-config (8-field `InitConfig`) account-creation path —\n * the only factory path that can install P-256 (passkey) guardian keys at deploy time\n * (airaccount-contract v0.20.0 / #120, #118).\n *\n * ## Why a dedicated path (not `createAccountWithDefaults`)\n * The factory exposes two account-creation entrypoints with DIFFERENT salt + acceptance\n * semantics (verified against `AAStarAirAccountFactoryV7.sol`):\n *\n * - `createAccountWithDefaults(owner, salt, g1, g1Sig, g2, g2Sig, dailyLimit)` — ECDSA-only.\n * CREATE2 salt = `keccak256(owner, salt)` (does NOT bind the config), so the contract\n * REQUIRES each ECDSA guardian's `ACCEPT_GUARDIAN` acceptance signature to stop a\n * front-runner from seizing the counterfactual address with different guardians. This is\n * the existing `AccountManager.createAccountWithGuardians` path; it has no InitConfig and\n * thus no way to set `guardianP256X/Y`.\n *\n * - `createAccount(owner, salt, config)` — full 8-field `InitConfig`. CREATE2 salt =\n * `keccak256(owner, salt, keccak256(InitConfig))` (`_getSalt` over `_getConfigHash`),\n * so the address is BOUND to the exact config. Because any config change yields a\n * different address, the contract performs NO guardian-acceptance check on this path —\n * for either ECDSA or P-256 guardians (`_initAccount` installs every slot directly).\n * P-256 guardian bootstrap is owner-only and acceptance-sig-free by design (#110④):\n * a single guardian cannot form a recovery quorum, so no consent ceremony is needed.\n *\n * Consequence: the deploy-time initCode MUST embed the BYTE-IDENTICAL `InitConfig` used to\n * predict the address, or the deployed account lands at a different CREATE2 address. These\n * helpers build the config once (via the core `buildInitConfig`) and reconstruct it\n * deterministically from the persisted record at first-UserOp deploy time so the two match.\n */\n\n/** A P-256 (passkey) guardian public key — SEC1 affine coordinates, each a 32-byte hex word. */\nexport interface P256GuardianKey {\n x: Hex;\n y: Hex;\n}\n\n/** Inputs for the full-config (8-field `InitConfig`) account-creation path. */\nexport interface FullConfigGuardianParams {\n /** P-256 (passkey) guardians installed at deploy time. Owner-bootstrap — NO acceptance sig. */\n p256Guardians: P256GuardianKey[];\n /**\n * Optional ECDSA guardians, installed via the SAME full-config path. NOTE: on this path the\n * contract does not verify ECDSA acceptance signatures (the config-hash-in-salt binding stands\n * in for them), so none are required or accepted here.\n */\n ecdsaGuardians?: Address[];\n /** Daily spend limit (wei). MUST be > 0 — a guardian set enables the on-chain GUARD. */\n dailyLimit: bigint;\n /** Validator algorithm ids approved at init. Defaults (in buildInitConfig) to ECDSA (+P-256). */\n approvedAlgIds?: number[];\n /** Floor the daily limit may be lowered to via the guard. Defaults to 0. */\n minDailyLimit?: bigint;\n}\n\n/** A guardian slot serialized for JSON persistence on the {@link AccountRecord}. */\nexport type SerializedGuardianSpec = { ecdsa: string } | { p256: { x: string; y: string } };\n\n/**\n * Map the public params to core {@link GuardianSpec}s in a DETERMINISTIC order\n * (ECDSA slots first, then P-256). Order is consensus-critical: it determines both the\n * predicted CREATE2 address and the guardian slot index each key occupies on-chain.\n */\nexport function toGuardianSpecs(p: FullConfigGuardianParams): GuardianSpec[] {\n const specs: GuardianSpec[] = [];\n for (const e of p.ecdsaGuardians ?? []) specs.push({ ecdsa: e });\n for (const k of p.p256Guardians) specs.push({ p256: { x: k.x, y: k.y } });\n return specs;\n}\n\n/**\n * Build the full 8-field `InitConfig` for the create path. Delegates to the core\n * `buildInitConfig` (the 0.22.0 builder) so the P-256 slots, sentinel handling, and\n * approvedAlgId defaulting are produced by ONE audited implementation — never hand-rolled.\n */\nexport function buildFullInitConfig(p: FullConfigGuardianParams): InitConfig {\n return buildInitConfig({\n guardians: toGuardianSpecs(p),\n dailyLimit: p.dailyLimit,\n ...(p.approvedAlgIds ? { approvedAlgIds: p.approvedAlgIds } : {}),\n ...(p.minDailyLimit !== undefined ? { minDailyLimit: p.minDailyLimit } : {}),\n });\n}\n\n/**\n * Flatten a typed {@link InitConfig} into the POSITIONAL tuple the local human-readable\n * factory ABI (`AIRACCOUNT_FACTORY_ABI`, fed through viem `parseAbi`) expects as the\n * `config` argument of `getAddress` / `createAccount`. Field order is consensus-critical\n * and matches `AAStarAirAccountBase.InitConfig` exactly.\n */\nexport function initConfigToTuple(c: InitConfig): readonly unknown[] {\n return [\n c.guardians,\n c.guardianP256X,\n c.guardianP256Y,\n c.dailyLimit,\n c.approvedAlgIds,\n c.minDailyLimit,\n c.initialTokens,\n c.initialTokenConfigs.map((t) => [t.tier1Limit, t.tier2Limit, t.dailyLimit]),\n ];\n}\n\n/** Serialize core {@link GuardianSpec}s for JSON storage on the account record. */\nexport function serializeGuardianSpecs(specs: readonly GuardianSpec[]): SerializedGuardianSpec[] {\n return specs.map((s) =>\n s.p256 ? { p256: { x: s.p256.x, y: s.p256.y } } : { ecdsa: s.ecdsa as string }\n );\n}\n\n/**\n * Reconstruct the BYTE-IDENTICAL `InitConfig` from a persisted record at deploy time.\n *\n * Re-derivation is exact because the record persists the RESOLVED `approvedAlgIds`,\n * `minDailyLimit`, and `dailyLimit` (not just the create-time inputs), and `buildInitConfig`\n * is a pure function of its arguments. The resulting config therefore hashes to the same\n * `_getConfigHash`, yielding the same CREATE2 address that was predicted at create time.\n *\n * @throws if the record carries no `guardianSpecs` (i.e. it is not a full-config account).\n */\nexport function initConfigFromRecord(record: AccountRecord): InitConfig {\n if (!record.guardianSpecs || record.guardianSpecs.length === 0) {\n throw new Error(\n \"initConfigFromRecord: record has no guardianSpecs (not a full-config / P-256 account)\"\n );\n }\n const guardians: GuardianSpec[] = record.guardianSpecs.map((s) =>\n \"p256\" in s\n ? { p256: { x: s.p256.x as Hex, y: s.p256.y as Hex } }\n : { ecdsa: s.ecdsa as Address }\n );\n return buildInitConfig({\n guardians,\n dailyLimit: record.dailyLimit ? BigInt(record.dailyLimit) : 0n,\n ...(record.approvedAlgIds ? { approvedAlgIds: record.approvedAlgIds } : {}),\n ...(record.minDailyLimit !== undefined ? { minDailyLimit: BigInt(record.minDailyLimit) } : {}),\n });\n}\n","import { zeroAddress, parseEther, type Address, type Hash, type WalletClient } from \"viem\";\n// AIRACCOUNT_ABI is a local human-readable signature array (not in @aastar/core);\n// parseAbi is required to feed it to viem's encodeFunctionData during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi, encodeFunctionData } from \"viem\";\nimport {\n needsValidatorRouter,\n getCanonicalAddresses,\n airAccountActions,\n airAccountFactoryActions,\n} from \"@aastar/core\";\nimport { keccak256 } from \"../../migration/viem/hashing\";\nimport { solidityPacked } from \"../../migration/viem/abi-encoding\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport {\n readPredictedAddress,\n readPredictedAddressWithDefaults,\n} from \"../providers/typed-reads\";\nimport { IStorageAdapter, AccountRecord } from \"../interfaces/storage-adapter\";\nimport { ISignerAdapter } from \"../interfaces/signer-adapter\";\nimport { EntryPointVersion, AIRACCOUNT_FACTORY_ABI, AIRACCOUNT_ABI } from \"../constants/entrypoint\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\nimport {\n buildFullInitConfig,\n toGuardianSpecs,\n serializeGuardianSpecs,\n initConfigToTuple,\n initConfigFromRecord,\n type FullConfigGuardianParams,\n type P256GuardianKey,\n} from \"./account-init-config\";\n\n// v0.20.0 (#120): InitConfig gained bytes32[3] guardianP256X / guardianP256Y (P-256 guardian\n// keys) right after `guardians`. ECDSA-only accounts pass three zero words for each.\nconst ZERO32 = (\"0x\" + \"0\".repeat(64)) as `0x${string}`;\nconst EMPTY_P256: readonly [`0x${string}`, `0x${string}`, `0x${string}`] = [ZERO32, ZERO32, ZERO32];\n\n/**\n * Result of {@link AccountManager.ensureValidatorRouter}.\n * `set: true` only when an on-chain `setValidator(router)` tx was actually sent (`tx`\n * carries the hash). `set: false` is a no-op with a `reason` explaining the decision.\n */\nexport interface EnsureValidatorRouterResult {\n set: boolean;\n reason?: string;\n tx?: Hash;\n router?: Address;\n}\n\n/**\n * Account manager — extracted from NestJS AccountService.\n * Creates and retrieves smart accounts without framework dependencies.\n */\nexport class AccountManager {\n private readonly logger: ILogger;\n\n constructor(\n private readonly ethereum: EthereumProvider,\n private readonly storage: IStorageAdapter,\n private readonly signer: ISignerAdapter,\n logger?: ILogger\n ) {\n this.logger = logger ?? new ConsoleLogger(\"[AccountManager]\");\n }\n\n async createAccount(\n userId: string,\n options?: {\n entryPointVersion?: EntryPointVersion;\n salt?: number | bigint;\n /** Daily transfer limit in wei. When > 0 the account is created with on-chain guard enforcement. */\n dailyLimit?: bigint;\n /**\n * P-256 (passkey) guardians to install at deploy time. When present, the account is created\n * via the full-config createAccount(owner, salt, config) path (delegates to\n * {@link createAccountWithP256Guardians}); `dailyLimit` MUST be > 0 (guardians enable the guard).\n */\n p256Guardians?: P256GuardianKey[];\n /** Optional ECDSA guardians installed via the same full-config path (no acceptance sig required). */\n ecdsaGuardians?: Address[];\n /** Validator algorithm ids approved at init (full-config path). Defaults to ECDSA (+P-256). */\n approvedAlgIds?: number[];\n /** Floor the daily limit may be lowered to via the guard (full-config path). Defaults to 0. */\n minDailyLimit?: bigint;\n }\n ): Promise<AccountRecord> {\n // Full-config path: any passkey (P-256) guardian routes through the 8-field InitConfig builder\n // so the deploy-time initCode can inject guardianP256X/Y (the ECDSA-only createAccountWithDefaults\n // path cannot). See createAccountWithP256Guardians for the contract-level rationale.\n if (options?.p256Guardians && options.p256Guardians.length > 0) {\n return this.createAccountWithP256Guardians(userId, {\n p256Guardians: options.p256Guardians,\n ecdsaGuardians: options.ecdsaGuardians,\n dailyLimit: options.dailyLimit ?? 0n,\n approvedAlgIds: options.approvedAlgIds,\n minDailyLimit: options.minDailyLimit,\n salt: options.salt,\n entryPointVersion: options.entryPointVersion,\n });\n }\n\n const version = options?.entryPointVersion ?? this.ethereum.getDefaultVersion();\n const versionStr = version as string;\n\n // Check for existing account with this version\n const existingAccounts = await this.storage.getAccounts();\n const existing = existingAccounts.find(\n a => a.userId === userId && a.entryPointVersion === versionStr\n );\n if (existing) return existing;\n\n const factory = this.ethereum.getFactoryContract(version);\n const validatorAddress =\n (this.ethereum.getValidatorContract(version).address as string) ||\n this.ethereum.getValidatorAddress(version);\n\n // Ensure signer wallet exists\n const { address: signerAddress } = await this.signer.ensureSigner(userId);\n const salt = options?.salt ?? Math.floor(Math.random() * 1000000);\n\n // Predict account address using M5 factory (createAccount with minimal config).\n // When dailyLimit > 0, write it into the config so the account is guard-enabled at deployment.\n const dailyLimitValue = options?.dailyLimit ?? 0n;\n const minimalConfig = [\n [zeroAddress, zeroAddress, zeroAddress], // guardians (address[3])\n EMPTY_P256, // guardianP256X (bytes32[3]) — v0.20.0\n EMPTY_P256, // guardianP256Y (bytes32[3]) — v0.20.0\n dailyLimitValue, // dailyLimit (0 = no guard)\n [], // approvedAlgIds\n 0n, // minDailyLimit\n [], // initialTokens\n [], // initialTokenConfigs\n ];\n // uint256 `salt` coerced to bigint via the typed wrapper. The predicted\n // address is the fund-custody address; the bigint encoding is byte-identical\n // to the JS-number `salt` reused in the deploy-time initCode, so the\n // counterfactual address is unchanged.\n const accountAddress = await readPredictedAddress(\n factory,\n signerAddress,\n BigInt(salt),\n minimalConfig\n );\n\n // Check deployment status\n let deployed = false;\n try {\n const code = await this.ethereum.getProvider().getCode({ address: accountAddress as Address });\n deployed = !!code && code !== \"0x\";\n } catch {\n // Assume not deployed\n }\n\n const account: AccountRecord = {\n userId,\n address: accountAddress,\n signerAddress,\n salt,\n deployed,\n deploymentTxHash: null,\n validatorAddress,\n entryPointVersion: versionStr,\n factoryAddress: (factory.address as string) || this.ethereum.getFactoryAddress(version),\n createdAt: new Date().toISOString(),\n // Persist dailyLimit so buildUserOperation can reconstruct identical initCode at deploy time.\n ...(dailyLimitValue > 0n ? { dailyLimit: dailyLimitValue.toString() } : {}),\n };\n\n await this.storage.saveAccount(account);\n return account;\n }\n\n async getAccount(\n userId: string\n ): Promise<(AccountRecord & { balance: string; nonce: string }) | null> {\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) return null;\n\n let balance = \"0\";\n try {\n balance = await this.ethereum.getBalance(account.address);\n } catch {\n // Use default\n }\n\n const version = (account.entryPointVersion || \"0.6\") as unknown as EntryPointVersion;\n const nonce = await this.ethereum.getNonce(account.address, 0, version);\n\n return { ...account, balance, nonce: nonce.toString() };\n }\n\n async getAccountAddress(userId: string): Promise<string> {\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) throw new Error(\"Account not found\");\n return account.address;\n }\n\n async getAccountBalance(\n userId: string\n ): Promise<{ address: string; balance: string; balanceInWei: string }> {\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) throw new Error(\"Account not found\");\n const balance = await this.ethereum.getBalance(account.address);\n return {\n address: account.address,\n balance,\n balanceInWei: parseEther(balance).toString(),\n };\n }\n\n async getAccountNonce(userId: string): Promise<{ address: string; nonce: string }> {\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) throw new Error(\"Account not found\");\n const nonce = await this.ethereum.getNonce(account.address);\n return { address: account.address, nonce: nonce.toString() };\n }\n\n async getAccountByUserId(userId: string): Promise<AccountRecord | null> {\n return this.storage.findAccountByUserId(userId);\n }\n\n /**\n * Build the acceptance hash that guardian devices must sign before account creation.\n *\n * Encoding: keccak256(solidityPacked(\n * [\"string\",\"uint256\",\"address\",\"address\",\"uint256\",\"uint256\"],\n * [\"ACCEPT_GUARDIAN\", chainId, factoryAddress, owner, salt, dailyLimit]\n * ))\n *\n * dailyLimit is bound in the hash (PR #47 / C-3) to prevent a front-runner from\n * replaying guardian sigs with a weaker limit on the same counterfactual address.\n *\n * Returns the RAW keccak256 hash (no EIP-191 prefix).\n * Guardians MUST sign via personal_sign / ethers.signMessage(ethers.getBytes(hash)).\n * Do NOT use eth_sign — the EIP-191 \"\\x19Ethereum Signed Message:\\n32\" prefix\n * is applied inside the contract (toEthSignedMessageHash) before ecrecover, not here.\n *\n * @returns raw hex keccak256 hash — encode this into the QR code shown to guardian devices\n */\n buildGuardianAcceptanceHash(\n owner: string,\n salt: number | bigint,\n factoryAddress: string,\n chainId: number,\n dailyLimit: bigint\n ): string {\n if (typeof salt === \"number\" && !Number.isSafeInteger(salt)) {\n throw new Error(\n `salt value ${salt} exceeds Number.MAX_SAFE_INTEGER; pass as bigint to avoid precision loss`\n );\n }\n // viem's encodePacked rejects plain `number` for uint256 — coerce to bigint.\n return keccak256(\n solidityPacked(\n [\"string\", \"uint256\", \"address\", \"address\", \"uint256\", \"uint256\"],\n [\"ACCEPT_GUARDIAN\", BigInt(chainId), factoryAddress, owner, BigInt(salt), dailyLimit]\n )\n );\n }\n\n /**\n * Encode calldata for modifyTierLimitsWithGuardians() — guardian-gated tier-limit change (PR #43).\n *\n * Both tier1 and tier2 can be raised or lowered, subject to guardian approval.\n * Caller is responsible for building and submitting the resulting UserOp.\n *\n * @param tier1 New Tier-1 ceiling in wei (ECDSA-only spending; 0 = no limit)\n * @param tier2 New Tier-2 ceiling in wei (dual-factor; 0 = no limit)\n * @param deadline Unix timestamp — guardian sigs rejected after this\n * @param guardianSigs 65-byte EIP-191 hex signatures from required guardians\n */\n encodeModifyTierLimits(\n tier1: bigint,\n tier2: bigint,\n deadline: bigint,\n guardianSigs: string[]\n ): string {\n return encodeFunctionData({\n abi: parseAbi(AIRACCOUNT_ABI),\n functionName: \"modifyTierLimitsWithGuardians\",\n args: [tier1, tier2, deadline, guardianSigs as `0x${string}`[]],\n });\n }\n\n /**\n * Create an AirAccount with 3 on-chain guardians:\n * - guardian1 and guardian2: user's own devices (passkeys on phone 1 and phone 2)\n * - guardian3: team Safe multisig (defaultCommunityGuardian, set in factory at deploy time)\n *\n * Both guardian1 and guardian2 must sign the acceptance hash produced by\n * buildGuardianAcceptanceHash() before this method is called.\n *\n * Recovery: any 2-of-3 guardians can initiate social recovery after a 48h timelock.\n */\n async createAccountWithGuardians(\n userId: string,\n params: {\n guardian1: string;\n guardian1Sig: string;\n guardian2: string;\n guardian2Sig: string;\n dailyLimit: bigint;\n salt?: number | bigint;\n entryPointVersion?: EntryPointVersion;\n }\n ): Promise<AccountRecord> {\n if (params.guardian1.toLowerCase() === params.guardian2.toLowerCase()) {\n throw new Error(\"guardian1 and guardian2 must be different addresses\");\n }\n if (params.dailyLimit <= 0n) {\n throw new Error(\"Guardian accounts require dailyLimit > 0 (on-chain enforcement)\");\n }\n\n const version = params.entryPointVersion ?? this.ethereum.getDefaultVersion();\n if (version === EntryPointVersion.V0_6) {\n throw new Error(\n \"createAccountWithGuardians requires EntryPoint v0.7 or v0.8; \" +\n \"v0.6 factory does not support getAddressWithDefaults\"\n );\n }\n const versionStr = version as string;\n\n const existingAccounts = await this.storage.getAccounts();\n const existing = existingAccounts.find(\n a => a.userId === userId && a.entryPointVersion === versionStr && a.guardian1\n );\n if (existing) return existing;\n\n const { address: signerAddress } = await this.signer.ensureSigner(userId);\n const salt = params.salt ?? Math.floor(Math.random() * 1000000);\n\n const factory = this.ethereum.getFactoryContract(version);\n const factoryAddress = (factory.address as string) ?? this.ethereum.getFactoryAddress(version);\n\n // uint256 `salt` and `dailyLimit` are enforced as bigint by the typed wrapper.\n const accountAddress = await readPredictedAddressWithDefaults(\n factory,\n signerAddress,\n BigInt(salt),\n params.guardian1,\n params.guardian2,\n params.dailyLimit\n );\n\n let deployed = false;\n try {\n const code = await this.ethereum.getProvider().getCode({ address: accountAddress as Address });\n deployed = !!code && code !== \"0x\";\n } catch {\n // Assume not deployed\n }\n\n const validatorAddress = this.ethereum.getValidatorAddress(version);\n const account: AccountRecord = {\n userId,\n address: accountAddress,\n signerAddress,\n salt,\n deployed,\n deploymentTxHash: null,\n validatorAddress,\n entryPointVersion: versionStr,\n factoryAddress,\n createdAt: new Date().toISOString(),\n // Persist dailyLimit so transfer-manager can reconstruct identical initCode at deploy time.\n ...(params.dailyLimit > 0n ? { dailyLimit: params.dailyLimit.toString() } : {}),\n // Persist guardian addresses and sigs so transfer-manager can use createAccountWithDefaults\n // to reconstruct the correct initCode on first UserOp deployment.\n guardian1: params.guardian1,\n guardian1Sig: params.guardian1Sig,\n guardian2: params.guardian2,\n guardian2Sig: params.guardian2Sig,\n };\n\n await this.storage.saveAccount(account);\n this.logger.log(`[AccountManager] account created with guardians: ${accountAddress}`);\n return account;\n }\n\n /**\n * Create an AirAccount with one or more P-256 (WebAuthn passkey) guardians installed at\n * DEPLOY time — the server-client path #118 adds for KMS-custodied / counterfactual accounts\n * (e.g. YAA) that cannot drive the viem extension layer for account creation.\n *\n * Uses the factory's full-config `createAccount(owner, salt, config)` path because it is the\n * ONLY entrypoint that accepts an 8-field `InitConfig` (and therefore `guardianP256X/Y`). The\n * 8-field config is built by the core `buildInitConfig` (0.22.0) — never hand-rolled — and the\n * address is predicted via the factory's full-config `getAddress(owner, salt, config)` (NOT\n * `getAddressWithDefaults`), binding the address to `keccak256(config)`.\n *\n * ### Acceptance-signature semantics (verified against AAStarAirAccountFactoryV7.sol)\n * On this path the contract performs NO guardian-acceptance signature check — for P-256 OR ECDSA\n * guardians. Front-run protection comes from `_getSalt(owner, salt, _getConfigHash(config))`:\n * any change to the guardian set (or any other config field) yields a different CREATE2 address,\n * so an attacker cannot collide on the victim's counterfactual address with a weaker config.\n * P-256 guardians are an owner-bootstrap (single guardian can't form a recovery quorum), so no\n * acceptance ceremony exists for them by design (#110④). This is why optional ECDSA guardians may\n * also be passed here WITHOUT signatures — distinct from createAccountWithGuardians(), which uses\n * the owner-only-salt `createAccountWithDefaults` path and DOES require ECDSA acceptance sigs.\n *\n * The deploy UserOp is still signed by the existing KMS owner-key path (unchanged): this method\n * only predicts the address and persists the full config; transfer-manager rebuilds the\n * byte-identical initCode (via {@link initConfigFromRecord}) at first-UserOp deploy time.\n *\n * @throws if no P-256 guardian is supplied, dailyLimit <= 0, or EntryPoint is v0.6.\n */\n async createAccountWithP256Guardians(\n userId: string,\n params: {\n /** P-256 (passkey) guardian public keys to install at deploy time (at least one required). */\n p256Guardians: P256GuardianKey[];\n /** Optional ECDSA guardians installed via the same full-config path (no acceptance sig). */\n ecdsaGuardians?: Address[];\n /** Daily spend limit in wei. MUST be > 0 — a guardian set enables the on-chain guard. */\n dailyLimit: bigint;\n /** Validator algorithm ids approved at init. Defaults to ECDSA (+P-256 when a passkey is present). */\n approvedAlgIds?: number[];\n /** Floor the daily limit may be lowered to via the guard. Defaults to 0. */\n minDailyLimit?: bigint;\n salt?: number | bigint;\n entryPointVersion?: EntryPointVersion;\n }\n ): Promise<AccountRecord> {\n if (!params.p256Guardians || params.p256Guardians.length === 0) {\n throw new Error(\"createAccountWithP256Guardians requires at least one P-256 guardian\");\n }\n if (params.dailyLimit <= 0n) {\n throw new Error(\n \"P-256 guardian accounts require dailyLimit > 0 (a guardian set enables the on-chain guard)\"\n );\n }\n\n const version = params.entryPointVersion ?? this.ethereum.getDefaultVersion();\n if (version === EntryPointVersion.V0_6) {\n throw new Error(\n \"createAccountWithP256Guardians requires EntryPoint v0.7 or v0.8; \" +\n \"the v0.6 factory does not support the full-config createAccount(InitConfig) path\"\n );\n }\n const versionStr = version as string;\n\n // Build the FULL 8-field InitConfig (incl. guardianP256X/Y) via the core builder. This also\n // validates: <= 3 guardians, P-256 coords all-or-nothing + non-zero, sentinel misuse, dailyLimit > 0.\n const fullParams: FullConfigGuardianParams = {\n p256Guardians: params.p256Guardians,\n ecdsaGuardians: params.ecdsaGuardians,\n dailyLimit: params.dailyLimit,\n approvedAlgIds: params.approvedAlgIds,\n minDailyLimit: params.minDailyLimit,\n };\n const specs = toGuardianSpecs(fullParams);\n const config = buildFullInitConfig(fullParams);\n\n // One full-config (P-256) account per (user, version) — idempotent like the other create paths.\n const existingAccounts = await this.storage.getAccounts();\n const existing = existingAccounts.find(\n a =>\n a.userId === userId &&\n a.entryPointVersion === versionStr &&\n !!a.guardianSpecs &&\n a.guardianSpecs.length > 0\n );\n if (existing) return existing;\n\n const { address: signerAddress } = await this.signer.ensureSigner(userId);\n // #118 M2: a JS-number salt outside the 53-bit safe range silently truncates, so the predicted\n // and deploy-time salts would diverge -> different CREATE2 address -> stranded funds. Reject it\n // (pass a bigint for large salts) and persist a lossless DECIMAL STRING below.\n if (typeof params.salt === \"number\" && !Number.isSafeInteger(params.salt)) {\n throw new Error(\n `salt value ${params.salt} exceeds Number.MAX_SAFE_INTEGER; pass it as a bigint to avoid precision loss`\n );\n }\n const saltBig = BigInt(params.salt ?? Math.floor(Math.random() * 1000000));\n\n const factory = this.ethereum.getFactoryContract(version);\n const factoryAddress = (factory.address as string) ?? this.ethereum.getFactoryAddress(version);\n\n // Predict via the FULL-config getAddress(owner, salt, config). The address is bound to\n // keccak256(config), so the deploy-time initCode MUST embed the byte-identical config AND the\n // identical salt (transfer-manager rebuilds both from the persisted record fields below).\n const accountAddress = await readPredictedAddress(\n factory,\n signerAddress,\n saltBig,\n initConfigToTuple(config)\n );\n\n let deployed = false;\n try {\n const code = await this.ethereum.getProvider().getCode({ address: accountAddress as Address });\n deployed = !!code && code !== \"0x\";\n } catch {\n // Assume not deployed\n }\n\n const validatorAddress = this.ethereum.getValidatorAddress(version);\n const account: AccountRecord = {\n userId,\n address: accountAddress,\n signerAddress,\n // Persist as a lossless decimal string (#118 M2); transfer-manager rebuilds via BigInt(account.salt).\n salt: saltBig.toString(),\n deployed,\n deploymentTxHash: null,\n validatorAddress,\n entryPointVersion: versionStr,\n factoryAddress,\n createdAt: new Date().toISOString(),\n dailyLimit: params.dailyLimit.toString(),\n // Persist the RESOLVED config so transfer-manager rebuilds byte-identical initCode at deploy.\n guardianSpecs: serializeGuardianSpecs(specs),\n approvedAlgIds: [...config.approvedAlgIds],\n minDailyLimit: config.minDailyLimit.toString(),\n };\n\n await this.storage.saveAccount(account);\n this.logger.log(\n `[AccountManager] account created with ${params.p256Guardians.length} P-256 guardian(s): ${accountAddress}`\n );\n // Gap B: a router-delegated algId (BLS/T2/T3/weighted/session/...) cannot validate until the\n // account's validator router is wired via setValidator(). The factory does NOT auto-wire it, and\n // setValidator is onlyOwner + needs deployed code — so it CANNOT run at predict-time here (the\n // account is still counterfactual). Flag the explicit post-deploy step rather than attempting it now.\n if (needsValidatorRouter(config.approvedAlgIds)) {\n this.logger.log(\n `[AccountManager] account ${accountAddress} approved a router-delegated algorithm ` +\n `(approvedAlgIds=[${config.approvedAlgIds.join(\", \")}]); use deployAndWireValidator(userId, ` +\n `{ walletClient }) to deploy + setValidator(router) in one call (or ensureValidatorRouter(userId) ` +\n `after a manual deploy) — required for those algIds to validate.`\n );\n }\n return account;\n }\n\n /**\n * Gap B — wire the validator router for an account that approved a ROUTER-DELEGATED signature\n * algorithm (BLS 0x01, cumulative T2 0x04, T3 0x05, weighted 0x07, session 0x08, ...). Such an\n * account's `_validateTripleSignature` / `_callBLSValidator` return `1` (FAIL) while\n * `validator() == address(0)`, so the algorithm is non-functional until the owner calls\n * `setValidator(router)` (onlyOwner, SET-ONCE). Inline algIds (ECDSA 0x02, P256 0x03, COMBINED_T1\n * 0x06) need no router and are a no-op here.\n *\n * MUST be called AFTER the account is deployed (setValidator is onlyOwner and needs code) — the\n * lazy/counterfactual deploy path cannot setValidator at predict-time. Idempotent: re-running after\n * the validator is set is a no-op (`reason: 'validator already set'`).\n *\n * On-chain access matches the rest of this package: reads via the EthereumProvider's PublicClient\n * (`getAccountContract(...).read.validator()` and `getProvider().getCode()`); the state-changing\n * `setValidator` is sent through a caller-supplied `WalletClient` whose account is the owner —\n * the same convention used by `PaymasterManager.updatePrice` / `ForceExitService` (this manager's\n * narrow `ISignerAdapter` only EIP-191 personal-signs and cannot send transactions).\n *\n * @param userId the account owner's user id (storage key)\n * @param opts.router override the router address (defaults to the chain's canonical\n * `aaStarValidator`); pass to target a non-canonical router\n * @param opts.walletClient viem WalletClient signing as the account OWNER — REQUIRED to send the tx\n */\n async ensureValidatorRouter(\n userId: string,\n opts?: { router?: Address; walletClient?: WalletClient }\n ): Promise<EnsureValidatorRouterResult> {\n // (1) Load the record + resolve approvedAlgIds. Absent => ECDSA-only legacy record => no router.\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) throw new Error(\"Account not found\");\n const approvedAlgIds = account.approvedAlgIds;\n if (!approvedAlgIds || approvedAlgIds.length === 0) {\n return { set: false, reason: \"no approvedAlgIds / not router-delegated\" };\n }\n\n // (2) All approved algIds are inline => nothing to route.\n if (!needsValidatorRouter(approvedAlgIds)) {\n return { set: false, reason: \"no router-delegated algorithm\" };\n }\n\n // (3) Resolve the router: explicit override, else the chain's canonical aaStarValidator.\n const chainId = this.ethereum.getChainId();\n const canonicalRouter = getCanonicalAddresses(chainId)?.aaStarValidator as Address | undefined;\n const router = opts?.router ?? canonicalRouter;\n if (!router || router.toLowerCase() === zeroAddress) {\n return { set: false, reason: `no canonical validator router for chain ${chainId}` };\n }\n\n // (4) Check deployment FIRST. setValidator is onlyOwner and needs deployed code; and reading\n // validator() on a counterfactual (not-yet-deployed) account reverts (eth_call returns 0x),\n // so the deploy check MUST precede the validator() read — otherwise a pre-deploy call throws\n // instead of returning the clean \"not deployed yet\" reason.\n let deployed = false;\n try {\n const code = await this.ethereum.getProvider().getCode({ address: account.address as Address });\n deployed = !!code && code !== \"0x\";\n } catch {\n // Treat an RPC failure as \"not deployed\" — never attempt setValidator on an unknown-code account.\n }\n if (!deployed) {\n return { set: false, reason: \"account not deployed yet — call after deploy\" };\n }\n\n // (5) Read the account's current validator(). Non-zero => already wired (SET-ONCE) => no-op.\n const current = (await this.ethereum\n .getAccountContract(account.address)\n .read.validator([])) as Address;\n if (current && current.toLowerCase() !== zeroAddress) {\n return { set: false, reason: \"validator already set\" };\n }\n\n // (6) Send setValidator(router) signed by the owner. The write goes through a caller-supplied\n // WalletClient (this manager has no signer that can send transactions). Use the core setValidator\n // action so the encoding stays the single-source-of-truth ABI from @aastar/core.\n const walletClient = opts?.walletClient;\n if (!walletClient || !walletClient.account) {\n return {\n set: false,\n reason: \"walletClient (account owner) required to send setValidator\",\n router,\n };\n }\n const tx = (await airAccountActions(account.address as Address)(walletClient).setValidator({\n validator: router,\n account: walletClient.account,\n })) as Hash;\n this.logger.log(\n `[AccountManager] setValidator(${router}) sent for account ${account.address} (tx ${tx})`\n );\n return { set: true, tx, router };\n }\n\n /**\n * Gap B (complete auto-wiring): deploy a router-delegated account AND set its validator router in\n * ONE call, so a BLS / cumulative / session-key account is immediately functional — no separate\n * manual `ensureValidatorRouter` step. The factory's lazy first-UserOp deploy cannot bootstrap such\n * an account (its own algorithm can't validate until the router is wired), so this performs an\n * explicit `factory.createAccount(owner, salt, config)` deploy (if the account has no code yet),\n * waits for it, then wires `setValidator(router)`. Both txs go through the caller-supplied owner/\n * deployer `WalletClient` (this manager holds no transaction signer). For inline algIds (ECDSA/P256/\n * COMBINED_T1) the validator step is a documented no-op.\n *\n * @returns `{ deployTx?, validator }` — `deployTx` is undefined if the account was already deployed.\n */\n async deployAndWireValidator(\n userId: string,\n opts: { walletClient: WalletClient; router?: Address }\n ): Promise<{ deployTx?: Hash; validator: EnsureValidatorRouterResult }> {\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) throw new Error(\"Account not found\");\n const walletClient = opts.walletClient;\n if (!walletClient || !walletClient.account) {\n throw new Error(\"deployAndWireValidator: a walletClient (deployer/owner) is required\");\n }\n\n // (1) Deploy via the FULL-config createAccount(owner, salt, config) if the account has no code yet.\n let deployTx: Hash | undefined;\n let code = \"0x\";\n try {\n code = (await this.ethereum.getProvider().getCode({ address: account.address as Address })) ?? \"0x\";\n } catch {\n // Treat an RPC failure as \"not deployed\" — the createAccount below is idempotent (CREATE2).\n }\n if (!code || code === \"0x\") {\n // Rebuild the byte-identical InitConfig the account was predicted against (same owner/salt/config\n // ⇒ same CREATE2 address as the persisted record).\n const config = initConfigFromRecord(account);\n deployTx = (await airAccountFactoryActions(account.factoryAddress as Address)(walletClient).createAccount({\n owner: account.signerAddress as Address,\n salt: BigInt(account.salt),\n config,\n account: walletClient.account,\n })) as Hash;\n // setValidator (step 2) is onlyOwner + needs deployed code — wait for the deploy to land first.\n await this.ethereum.getProvider().waitForTransactionReceipt({ hash: deployTx });\n account.deployed = true;\n account.deploymentTxHash = deployTx;\n await this.storage.saveAccount(account);\n this.logger.log(`[AccountManager] deployed account ${account.address} (tx ${deployTx})`);\n }\n\n // (2) Wire the validator router. No-op when the account uses only inline algIds or it's already set.\n const validator = await this.ensureValidatorRouter(userId, {\n walletClient,\n router: opts.router,\n });\n // Wait for the setValidator tx to land so the account is on-chain-READY when this call returns\n // (ensureValidatorRouter itself fires-and-returns the hash without waiting).\n if (validator.set && validator.tx) {\n await this.ethereum.getProvider().waitForTransactionReceipt({ hash: validator.tx });\n }\n return { deployTx, validator };\n }\n}\n","import { concat, type Hex } from \"viem\";\n\nimport { selectorFromId } from \"../../migration/viem/hashing\";\n\n// AAStarAirAccountV7 v0.17.2-beta.4 bundler-compat entrypoint.\n//\n// The EntryPoint v0.7 routes a UserOp whose callData begins with the executeUserOp\n// selector to `account.executeUserOp(userOp, userOpHash)`, which re-derives the\n// signature algId in-frame. This eliminates the cross-`eth_call` transient dependency\n// that previously made guard-enabled accounts fail bundler gas estimation\n// (`AlgorithmNotApproved(0)`).\n\n/** 4-byte selector of `executeUserOp((PackedUserOperation),bytes32)`. */\nexport const EXECUTE_USER_OP_SELECTOR = selectorFromId(\n \"executeUserOp((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes),bytes32)\"\n);\n\n/** 4-byte selector of `execute(address,uint256,bytes)`. */\nexport const EXECUTE_SELECTOR = selectorFromId(\"execute(address,uint256,bytes)\");\n\n/** 4-byte selector of `executeBatch(address[],uint256[],bytes[])`. */\nexport const EXECUTE_BATCH_SELECTOR = selectorFromId(\n \"executeBatch(address[],uint256[],bytes[])\"\n);\n\n/**\n * Wrap inner `execute()` / `executeBatch()` callData with the `executeUserOp` selector so a\n * guard-enabled (v0.17.2-beta.4) account routes the bundler UserOp through `executeUserOp`.\n *\n * Only `execute` / `executeBatch` may be wrapped — the account reverts\n * `UnsupportedInnerSelector` for anything else (including a nested `executeUserOp`).\n *\n * Owner-direct (non-bundler) `execute()` does NOT need this; no-guard accounts can submit\n * bare callData. Use this only when building a bundler UserOp for a guard-enabled account.\n *\n * @param innerCallData ABI-encoded `execute`/`executeBatch` calldata (0x-prefixed)\n * @returns `executeUserOp.selector ++ innerCallData`\n * @throws if `innerCallData` is not an `execute`/`executeBatch` call\n */\nexport function wrapExecuteUserOp(innerCallData: string): string {\n if (!/^0x[0-9a-fA-F]*$/.test(innerCallData) || innerCallData.length < 10) {\n throw new Error(\"wrapExecuteUserOp: innerCallData must be 0x-prefixed calldata with a 4-byte selector\");\n }\n const sel = innerCallData.slice(0, 10).toLowerCase();\n if (sel !== EXECUTE_SELECTOR && sel !== EXECUTE_BATCH_SELECTOR) {\n throw new Error(\n `wrapExecuteUserOp: only execute()/executeBatch() may be wrapped (got selector ${sel}); ` +\n \"the account reverts UnsupportedInnerSelector otherwise\"\n );\n }\n return concat([EXECUTE_USER_OP_SELECTOR, innerCallData as Hex]);\n}\n\n/** True if callData is already wrapped with the executeUserOp selector. */\nexport function isExecuteUserOpWrapped(callData: string): boolean {\n return callData.slice(0, 10).toLowerCase() === EXECUTE_USER_OP_SELECTOR;\n}\n","import { concat, getContract, numberToHex, zeroAddress, type Address, type Hex, type WalletClient } from \"viem\";\n// PAYMASTER_PRICE_ABI / the SuperPaymaster-detection ABI are local human-readable\n// signature arrays (not in @aastar/core); parseAbi is required to feed them to\n// viem's getContract / writeContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport { IStorageAdapter, PaymasterRecord } from \"../interfaces/storage-adapter\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\n\n/**\n * Thrown when a paymaster's on-chain price cache is stale.\n * Caller should invoke `paymasterManager.updatePrice(paymasterAddress)` before retrying.\n */\nexport class PaymasterPriceStalenessError extends Error {\n constructor(\n public readonly paymasterAddress: string,\n public readonly ageSeconds: number,\n public readonly thresholdSeconds: number\n ) {\n super(\n `Paymaster ${paymasterAddress} price is stale ` +\n `(age: ${Math.floor(ageSeconds / 60)}min, threshold: ${Math.floor(thresholdSeconds / 60)}min). ` +\n `Call updatePrice() on the paymaster contract before retrying.`\n );\n this.name = \"PaymasterPriceStalenessError\";\n }\n}\n\nconst PAYMASTER_PRICE_ABI = parseAbi([\n \"function token() view returns (address)\",\n \"function cachedPriceTimestamp() view returns (uint256)\",\n \"function priceStalenessThreshold() view returns (uint256)\",\n \"function updatePrice() external\",\n]);\n\nconst SUPER_PAYMASTER_DETECT_ABI = parseAbi([\n \"function owner() view returns (address)\",\n \"function operators(address) view returns (bool,uint256,address,uint256)\",\n]);\n\n/**\n * Paymaster manager — extracted from NestJS PaymasterService.\n * Storage via IStorageAdapter instead of filesystem JSON files.\n */\nexport class PaymasterManager {\n private readonly logger: ILogger;\n\n constructor(\n private readonly ethereum: EthereumProvider,\n private readonly storage: IStorageAdapter,\n logger?: ILogger\n ) {\n this.logger = logger ?? new ConsoleLogger(\"[PaymasterManager]\");\n }\n\n async getAvailablePaymasters(\n userId: string\n ): Promise<{ name: string; address: string; configured: boolean }[]> {\n const paymasters = await this.storage.getPaymasters(userId);\n return paymasters.map(config => ({\n name: config.name,\n address: config.address,\n configured: !!config.address && config.address !== \"0x\",\n }));\n }\n\n async addCustomPaymaster(\n userId: string,\n name: string,\n address: string,\n type: \"pimlico\" | \"stackup\" | \"alchemy\" | \"custom\" = \"custom\",\n apiKey?: string,\n endpoint?: string\n ): Promise<void> {\n const paymaster: PaymasterRecord = {\n id: `${userId}-${name}-${Date.now()}`,\n name,\n address,\n type,\n apiKey,\n endpoint,\n createdAt: new Date().toISOString(),\n };\n await this.storage.savePaymaster(userId, paymaster);\n }\n\n async removeCustomPaymaster(userId: string, name: string): Promise<boolean> {\n return this.storage.removePaymaster(userId, name);\n }\n\n /**\n * Check whether a paymaster's on-chain price cache is still fresh.\n * Returns `{ fresh, ageSeconds, thresholdSeconds }`.\n * Throws if the contract does not implement `cachedPriceTimestamp()` / `priceStalenessThreshold()`.\n */\n async checkPriceFreshness(paymasterAddress: string): Promise<{\n fresh: boolean;\n ageSeconds: number;\n thresholdSeconds: number;\n }> {\n const provider = this.ethereum.getProvider();\n const contract = getContract({\n address: paymasterAddress as Address,\n abi: PAYMASTER_PRICE_ABI,\n client: provider,\n });\n const [timestamp, threshold] = await Promise.all([\n contract.read.cachedPriceTimestamp() as Promise<bigint>,\n contract.read.priceStalenessThreshold() as Promise<bigint>,\n ]);\n const nowSeconds = Math.floor(Date.now() / 1000);\n const ageSeconds = nowSeconds - Number(timestamp);\n const thresholdSeconds = Number(threshold);\n return {\n fresh: ageSeconds <= thresholdSeconds,\n ageSeconds,\n thresholdSeconds,\n };\n }\n\n /**\n * Call `updatePrice()` on a paymaster contract (permissionless).\n * Useful when `checkPriceFreshness()` reports stale price.\n *\n * @param walletClient - A viem WalletClient (with an account) that will send\n * the transaction (must have gas). Replaces the former ethers Signer param.\n */\n async updatePrice(paymasterAddress: string, walletClient: WalletClient): Promise<string> {\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"updatePrice requires a WalletClient with a configured account\");\n }\n const hash = await walletClient.writeContract({\n address: paymasterAddress as Address,\n abi: PAYMASTER_PRICE_ABI,\n functionName: \"updatePrice\",\n args: [],\n gas: BigInt(300_000),\n account,\n chain: walletClient.chain,\n });\n await this.ethereum.getProvider().waitForTransactionReceipt({ hash });\n this.logger.log(`Paymaster ${paymasterAddress} price updated, tx: ${hash}`);\n return hash;\n }\n\n async getPaymasterData(\n userId: string,\n paymasterName: string,\n userOp: unknown,\n entryPoint: string,\n customAddress?: string,\n options?: { tokenAddress?: string }\n ): Promise<string> {\n // Handle custom user-provided paymaster addresses\n if (paymasterName === \"custom-user-provided\" && customAddress) {\n const formattedAddress = customAddress.toLowerCase().startsWith(\"0x\")\n ? customAddress\n : `0x${customAddress}`;\n\n if (!/^0x[a-fA-F0-9]{40}$/.test(formattedAddress)) {\n throw new Error(`Invalid paymaster address format: ${customAddress}`);\n }\n\n const isV07OrV08 =\n entryPoint.toLowerCase() === \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\".toLowerCase() ||\n entryPoint.toLowerCase() === \"0x0576a174D229E3cFA37253523E645A78A0C91B57\".toLowerCase();\n\n if (isV07OrV08) {\n const provider = this.ethereum.getProvider();\n\n // Detect SuperPaymaster vs PaymasterV4\n let isSuperPaymaster = false;\n let operatorAddress = \"0x\";\n try {\n const spContract = getContract({\n address: formattedAddress as Address,\n abi: SUPER_PAYMASTER_DETECT_ABI,\n client: provider,\n });\n const owner = (await spContract.read.owner()) as Address;\n const opInfo = (await spContract.read.operators([owner])) as readonly [\n boolean,\n bigint,\n Address,\n bigint,\n ];\n if (opInfo && opInfo[0] === true) {\n isSuperPaymaster = true;\n operatorAddress = owner;\n this.logger.log(`SuperPaymaster detected, operator: ${operatorAddress}`);\n }\n } catch {\n /* not SuperPaymaster */\n }\n\n if (isSuperPaymaster) {\n const verGas = BigInt(80000);\n // recordXPNTsDebt + event emit in postOp observed ~117k gas on Sepolia; 300k gives safe headroom.\n const postGas = BigInt(300_000);\n const maxRate = (BigInt(1) << BigInt(256)) - BigInt(1);\n return concat([\n formattedAddress as Hex,\n numberToHex(verGas, { size: 16 }),\n numberToHex(postGas, { size: 16 }),\n operatorAddress as Hex,\n numberToHex(maxRate, { size: 32 }),\n ]);\n }\n\n // PaymasterV4 deposit model: paymasterData contains the ERC-20 token address\n // that the user pays gas with (20 bytes appended after the gas limits).\n // Auto-detect via token() on the contract; fall back to empty if not available.\n const paymasterVerificationGasLimit = BigInt(0x30000);\n const paymasterPostOpGasLimit = BigInt(0x30000);\n\n let tokenAddress: string | null = options?.tokenAddress ?? null;\n if (tokenAddress) {\n this.logger.log(`PaymasterV4 token from options: ${tokenAddress}`);\n } else {\n try {\n const pmContract = getContract({\n address: formattedAddress as Address,\n abi: PAYMASTER_PRICE_ABI,\n client: provider,\n });\n tokenAddress = (await pmContract.read.token()) as string;\n if (tokenAddress === zeroAddress) tokenAddress = null;\n if (tokenAddress) {\n this.logger.log(`PaymasterV4 token auto-detected: ${tokenAddress}`);\n }\n } catch {\n this.logger.log(`PaymasterV4 token() not available, paymasterData will have no token`);\n }\n }\n\n const parts: Hex[] = [\n formattedAddress as Hex,\n numberToHex(paymasterVerificationGasLimit, { size: 16 }),\n numberToHex(paymasterPostOpGasLimit, { size: 16 }),\n ];\n if (tokenAddress) {\n parts.push(tokenAddress as Hex);\n }\n return concat(parts);\n }\n\n return formattedAddress;\n }\n\n const paymasters = await this.storage.getPaymasters(userId);\n const config = paymasters.find(p => p.name === paymasterName);\n if (!config) {\n throw new Error(`Paymaster ${paymasterName} not found`);\n }\n\n switch (config.type) {\n case \"pimlico\":\n if (!config.apiKey) return \"0x\";\n return this.getPimlicoPaymasterData(config, userOp, entryPoint);\n case \"stackup\":\n if (!config.apiKey) return \"0x\";\n return this.getStackUpPaymasterData(config, userOp, entryPoint);\n case \"alchemy\":\n if (!config.apiKey) return \"0x\";\n return this.getAlchemyPaymasterData(config, userOp, entryPoint);\n case \"custom\":\n if (\n config.address.toLowerCase() ===\n \"0x0000000000325602a77416A16136FDafd04b299f\".toLowerCase() &&\n config.apiKey\n ) {\n return this.getPimlicoPaymasterData(\n { ...config, type: \"pimlico\", endpoint: \"https://api.pimlico.io/v2/11155111/rpc\" },\n userOp,\n entryPoint\n );\n }\n return config.address;\n default:\n return \"0x\";\n }\n }\n\n private async getPimlicoPaymasterData(\n config: PaymasterRecord,\n userOp: unknown,\n entryPoint: string\n ): Promise<string> {\n const url = `${config.endpoint}?apikey=${config.apiKey}`;\n const response = await globalThis.fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n method: \"pm_sponsorUserOperation\",\n params: [userOp, entryPoint, {}],\n id: 1,\n }),\n });\n\n const result = (await response.json()) as {\n error?: { message?: string };\n result?: {\n paymasterAndData?: string;\n paymaster?: string;\n paymasterVerificationGasLimit?: string;\n paymasterPostOpGasLimit?: string;\n paymasterData?: string;\n };\n };\n\n if (result.error) {\n throw new Error(\n `Pimlico sponsorship failed: ${result.error.message || JSON.stringify(result.error)}`\n );\n }\n\n if (result.result) {\n if (result.result.paymasterAndData) {\n return result.result.paymasterAndData;\n }\n if (result.result.paymaster) {\n return concat([\n result.result.paymaster as Hex,\n numberToHex(BigInt(result.result.paymasterVerificationGasLimit || \"0x30000\"), {\n size: 16,\n }),\n numberToHex(BigInt(result.result.paymasterPostOpGasLimit || \"0x30000\"), { size: 16 }),\n (result.result.paymasterData || \"0x\") as Hex,\n ]);\n }\n }\n\n throw new Error(\"Pimlico API did not return valid paymaster data\");\n }\n\n private async getStackUpPaymasterData(\n config: PaymasterRecord,\n userOp: unknown,\n entryPoint: string\n ): Promise<string> {\n try {\n const response = await globalThis.fetch(`${config.endpoint}/${config.apiKey}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n method: \"pm_sponsorUserOperation\",\n params: { userOperation: userOp, entryPoint, context: { type: \"payg\" } },\n id: 1,\n }),\n });\n const result = (await response.json()) as { error?: unknown; result?: string };\n if (result.error) return \"0x\";\n return result.result || \"0x\";\n } catch {\n return \"0x\";\n }\n }\n\n private async getAlchemyPaymasterData(\n config: PaymasterRecord,\n userOp: unknown,\n entryPoint: string\n ): Promise<string> {\n try {\n const response = await globalThis.fetch(`${config.endpoint}/${config.apiKey}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n method: \"alchemy_requestGasAndPaymasterAndData\",\n params: [{ policyId: \"default\", entryPoint, userOperation: userOp }],\n id: 1,\n }),\n });\n const result = (await response.json()) as {\n error?: unknown;\n result?: { paymasterAndData?: string };\n };\n if (result.error) return \"0x\";\n return result.result?.paymasterAndData || \"0x\";\n } catch {\n return \"0x\";\n }\n }\n}\n","import {\n hexToBytes,\n concat,\n numberToHex,\n parseEther,\n zeroAddress,\n type PublicClient,\n type Address,\n type Abi,\n} from \"viem\";\n// Local human-readable ABIs (not in @aastar/core); parseAbi is required to feed\n// them to viem's readContract / encodeFunctionData during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi, encodeFunctionData } from \"viem\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport { readValidatorGasEstimate } from \"../providers/typed-reads\";\nimport { AccountManager } from \"./account-manager\";\nimport { BLSSignatureService, GuardianSigner } from \"./bls-signature-service\";\nimport { GuardChecker } from \"./guard-checker\";\nimport { wrapExecuteUserOp } from \"../utils/execute-user-op\";\nimport { PaymasterManager } from \"./paymaster-manager\";\nimport { TokenService } from \"./token-service\";\nimport { IStorageAdapter } from \"../interfaces/storage-adapter\";\nimport { ISignerAdapter, PasskeyAssertionContext } from \"../interfaces/signer-adapter\";\nimport { LegacyPasskeyAssertion } from \"./kms-signer\";\nimport {\n EntryPointVersion,\n ALG_ID,\n AIRACCOUNT_ABI,\n AIRACCOUNT_FACTORY_ABI,\n FACTORY_ABI_V6,\n} from \"../constants/entrypoint\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\nimport { initConfigFromRecord, initConfigToTuple } from \"./account-init-config\";\n\n// v0.20.0 (#120): InitConfig gained bytes32[3] guardianP256X / guardianP256Y after `guardians`.\n// ECDSA-only deploy initCode passes three zero words for each.\nconst ZERO32 = (\"0x\" + \"0\".repeat(64)) as `0x${string}`;\nconst EMPTY_P256: readonly [`0x${string}`, `0x${string}`, `0x${string}`] = [ZERO32, ZERO32, ZERO32];\nimport { PaymasterPriceStalenessError } from \"./paymaster-manager\";\nimport { UserOperation, PackedUserOperation } from \"../../core/types\";\nimport { ERC4337Utils } from \"../../core/erc4337\";\nimport { TierLevel } from \"../../core/tier\";\n\n// ── Parsed local ABIs ─────────────────────────────────────────────\n// Widened to the loose `Abi` type so encodeFunctionData accepts dynamic\n// function names + loosely-typed args (mirrors the old ethers.Interface surface).\nconst AIRACCOUNT_ABI_PARSED: Abi = parseAbi(AIRACCOUNT_ABI);\nconst AIRACCOUNT_FACTORY_ABI_PARSED: Abi = parseAbi(AIRACCOUNT_FACTORY_ABI);\nconst FACTORY_ABI_V6_PARSED: Abi = parseAbi(FACTORY_ABI_V6);\nconst VALIDATOR_GETTER_ABI: Abi = parseAbi([\"function validator() view returns (address)\"]);\n\n/** encodeFunctionData over a loosely-typed Abi (was `iface.encodeFunctionData`). */\nfunction encodeFn(abi: Abi, functionName: string, args: readonly unknown[]): `0x${string}` {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return encodeFunctionData({ abi, functionName, args } as any);\n}\n\n// ── Signature strategy detection ─────────────────────────────────\n\n/**\n * Determines whether to use plain ECDSA and whether the account is a compositeValidator.\n * Exported for unit testing.\n */\nexport async function detectSignatureStrategy(\n provider: PublicClient,\n accountAddress: string\n): Promise<{ useECDSA: boolean; isCompositeValidator: boolean }> {\n try {\n const accountCode = await provider.getCode({ address: accountAddress as Address });\n if (!accountCode || accountCode === \"0x\") {\n // AirAccount factory invariant: all counterfactual addresses are compositeValidator deployments.\n return { useECDSA: true, isCompositeValidator: true };\n }\n const v = (await provider.readContract({\n address: accountAddress as Address,\n abi: VALIDATOR_GETTER_ABI,\n functionName: \"validator\",\n })) as string;\n // validator() exists → confirmed compositeValidator account.\n return { useECDSA: v === zeroAddress, isCompositeValidator: true };\n } catch {\n // Covers both getCode() and validator() failures (network error or non-compositeValidator account).\n // Use raw ECDSA (no algId prefix) to avoid AA24 on non-compositeValidator accounts.\n return { useECDSA: true, isCompositeValidator: false };\n }\n}\n\n// ── Public DTOs ───────────────────────────────────────────────────\n\nexport interface ExecuteTransferParams {\n to: string;\n amount: string;\n data?: string;\n tokenAddress?: string;\n usePaymaster?: boolean;\n paymasterAddress?: string;\n paymasterData?: string;\n /** ERC-20 token address for deposit-pull paymasters (e.g. PMv4) that require\n * the gas token address appended to paymasterData. Used when the paymaster\n * contract does not expose a public token() getter for auto-detection. */\n paymasterTokenAddress?: string;\n passkeyAssertion?: LegacyPasskeyAssertion;\n /** P256 passkey signature (64 bytes hex). Required for AirAccount Tier 2/3. */\n p256Signature?: string;\n /** Guardian signer instance. Required for AirAccount Tier 3. */\n guardianSigner?: GuardianSigner;\n /** Enable AirAccount tiered signature routing. Default: false (legacy BLS-only). */\n useAirAccountTiering?: boolean;\n /**\n * Wrap the execute()/executeBatch() callData with the `executeUserOp` selector\n * (v0.17.2-beta.4 bundler-compat). REQUIRED for guard-enabled accounts submitted\n * through a standard ERC-4337 bundler; the account re-derives the signature algId\n * in-frame. Default: false. No-guard accounts and owner-direct calls leave it off.\n */\n wrapExecuteUserOp?: boolean;\n}\n\nexport interface EstimateGasParams {\n to: string;\n amount: string;\n data?: string;\n tokenAddress?: string;\n /** Match the executeUserOp wrapping used at submission so gas estimation is accurate (v0.17.2-beta.4). */\n wrapExecuteUserOp?: boolean;\n}\n\nexport interface TransferResult {\n success: boolean;\n transferId: string;\n userOpHash: string;\n status: string;\n message: string;\n from: string;\n to: string;\n amount: string;\n}\n\n// ── Helper to generate UUID-like IDs without external dependency ──\n\nfunction generateId(): string {\n const hex = () => Math.random().toString(16).slice(2, 10);\n return `${hex()}${hex()}-${hex()}-${hex()}-${hex()}-${hex()}${hex()}${hex()}`;\n}\n\n/**\n * Transfer manager — extracted from NestJS TransferService.\n * No passkey verification: callers are responsible for their own auth.\n */\nexport class TransferManager {\n private readonly logger: ILogger;\n\n private readonly guardChecker: GuardChecker | null;\n\n constructor(\n private readonly ethereum: EthereumProvider,\n private readonly accountManager: AccountManager,\n private readonly blsService: BLSSignatureService,\n private readonly paymasterManager: PaymasterManager,\n private readonly tokenService: TokenService,\n private readonly storage: IStorageAdapter,\n private readonly signer: ISignerAdapter,\n logger?: ILogger,\n guardChecker?: GuardChecker\n ) {\n this.logger = logger ?? new ConsoleLogger(\"[TransferManager]\");\n this.guardChecker = guardChecker ?? null;\n }\n\n async executeTransfer(userId: string, params: ExecuteTransferParams): Promise<TransferResult> {\n // Get user's account\n const account = await this.accountManager.getAccountByUserId(userId);\n if (!account) throw new Error(\"User account not found\");\n\n // Check deployment\n const code = await this.ethereum.getProvider().getCode({ address: account.address as Address });\n const needsDeployment = !code || code === \"0x\";\n if (needsDeployment) {\n this.logger.log(\"Account needs deployment, will deploy with first transaction\");\n }\n\n // Balance validation\n const smartAccountBalance = parseFloat(await this.ethereum.getBalance(account.address));\n const isTokenTransfer = !!params.tokenAddress;\n const transferAmount = isTokenTransfer ? 0 : parseFloat(params.amount);\n\n if (!params.usePaymaster) {\n const minRequiredBalance = 0.0002;\n const totalNeeded = transferAmount + minRequiredBalance;\n if (smartAccountBalance < totalNeeded) {\n throw new Error(\n `Insufficient balance: Account has ${smartAccountBalance} ETH but needs ${totalNeeded} ETH`\n );\n }\n } else if (!isTokenTransfer && transferAmount > smartAccountBalance) {\n throw new Error(\n `Insufficient balance: Account has ${smartAccountBalance} ETH but trying to send ${transferAmount} ETH`\n );\n }\n\n const version = (account.entryPointVersion || \"0.6\") as unknown as EntryPointVersion;\n\n // Build UserOperation\n const userOp = await this.buildUserOperation(\n userId,\n account.address,\n params.to,\n params.amount,\n params.data || \"0x\",\n params.usePaymaster,\n params.paymasterAddress,\n params.paymasterData,\n params.tokenAddress,\n version,\n params.paymasterTokenAddress,\n params.wrapExecuteUserOp ?? false\n );\n\n // Get hash\n const userOpHash = await this.ethereum.getUserOpHash(userOp, version);\n\n // Ensure wallet exists\n await this.signer.ensureSigner(userId);\n\n // BLS signature (pass assertion context for KMS-backed signing)\n const assertionCtx: PasskeyAssertionContext | undefined = params.passkeyAssertion\n ? { assertion: params.passkeyAssertion }\n : undefined;\n\n // Detect whether this is a compositeValidator account (has validator() fn) or plain ECDSA.\n // Only compositeValidator accounts expect the algId prefix in the signature.\n let useECDSA = false;\n let isCompositeValidator = false;\n if (version === EntryPointVersion.V0_7 || version === EntryPointVersion.V0_8) {\n const provider = this.ethereum.getProvider();\n ({ useECDSA, isCompositeValidator } = await detectSignatureStrategy(\n provider,\n account.address\n ));\n }\n\n if (useECDSA) {\n const ecdsaSig = await this.signer.signMessage(\n userId,\n hexToBytes(userOpHash as `0x${string}`),\n assertionCtx\n );\n if (isCompositeValidator) {\n this.logger.log(\"ECDSA path for compositeValidator: prepending algId prefix\");\n userOp.signature = concat([\n numberToHex(ALG_ID.ECDSA, { size: 1 }),\n ecdsaSig as `0x${string}`,\n ]);\n } else {\n this.logger.log(\"ECDSA path for non-compositeValidator: raw signature\");\n userOp.signature = ecdsaSig;\n }\n } else if (params.useAirAccountTiering && this.guardChecker) {\n // AirAccount tiered signature routing\n const transferValue = params.tokenAddress ? 0n : parseEther(params.amount);\n const preCheck = await this.guardChecker.preCheck(account.address, transferValue);\n\n if (!preCheck.ok) {\n throw new Error(`Guard pre-check failed: ${preCheck.errors.join(\"; \")}`);\n }\n\n this.logger.log(\n `Tier ${preCheck.tier} selected (algId=0x${preCheck.algId.toString(16).padStart(2, \"0\")})`\n );\n\n userOp.signature = await this.blsService.generateTieredSignature({\n tier: preCheck.tier as TierLevel,\n userId,\n userOpHash,\n p256Signature: params.p256Signature,\n guardianSigner: params.guardianSigner,\n ctx: assertionCtx,\n });\n } else {\n // BLS accounts are always compositeValidator by design — algId prefix applied unconditionally.\n const blsData = await this.blsService.generateBLSSignature(userId, userOpHash, assertionCtx);\n const packedBls = await this.blsService.packSignature(blsData);\n userOp.signature = concat([\n numberToHex(ALG_ID.BLS, { size: 1 }),\n packedBls as `0x${string}`,\n ]);\n }\n\n // Create transfer record\n const transferId = generateId();\n let tokenSymbol = \"ETH\";\n if (params.tokenAddress) {\n try {\n const tokenInfo = await this.tokenService.getTokenInfo(params.tokenAddress);\n tokenSymbol = tokenInfo.symbol;\n } catch {\n tokenSymbol = `${params.tokenAddress.slice(0, 6)}...${params.tokenAddress.slice(-4)}`;\n }\n }\n\n await this.storage.saveTransfer({\n id: transferId,\n userId,\n from: account.address,\n to: params.to,\n amount: params.amount,\n data: params.data,\n userOpHash,\n status: \"pending\",\n nodeIndices: [],\n createdAt: new Date().toISOString(),\n tokenAddress: params.tokenAddress,\n tokenSymbol,\n });\n\n // Process asynchronously\n this.processTransferAsync(transferId, userOp, account.address, version);\n\n return {\n success: true,\n transferId,\n userOpHash,\n status: \"pending\",\n message: \"Transfer submitted successfully. Use transferId to check status.\",\n from: account.address,\n to: params.to,\n amount: params.amount,\n };\n }\n\n private async processTransferAsync(\n transferId: string,\n userOp: UserOperation | PackedUserOperation,\n from: string,\n version: EntryPointVersion\n ): Promise<void> {\n try {\n const formatted = this.formatUserOpForBundler(userOp, version);\n const bundlerUserOpHash = await this.ethereum.sendUserOperation(formatted, version);\n\n await this.storage.updateTransfer(transferId, {\n bundlerUserOpHash,\n status: \"submitted\",\n submittedAt: new Date().toISOString(),\n } as Partial<import(\"../interfaces/storage-adapter\").TransferRecord>);\n\n const txHash = await this.ethereum.waitForUserOp(bundlerUserOpHash);\n\n await this.storage.updateTransfer(transferId, {\n transactionHash: txHash,\n status: \"completed\",\n completedAt: new Date().toISOString(),\n } as Partial<import(\"../interfaces/storage-adapter\").TransferRecord>);\n\n // Update deployment status if first tx\n const code = await this.ethereum.getProvider().getCode({ address: from as Address });\n if (code && code !== \"0x\") {\n const account = (await this.storage.getAccounts()).find(a => a.address === from);\n if (account && !account.deployed) {\n await this.storage.updateAccount(account.userId, {\n deployed: true,\n deploymentTxHash: txHash,\n });\n }\n }\n } catch (error: unknown) {\n let message = error instanceof Error ? error.message : String(error);\n\n // Translate bundler \"expires too soon\" into a structured PaymasterPriceStalenessError\n // so callers can detect and handle stale paymaster price without string-matching.\n if (\n message.includes(\"expires too soon\") ||\n message.includes(\"AA32\") ||\n message.includes(\"paymaster deposit not locked\")\n ) {\n const validUntilMatch = message.match(/validUntil=(\\d+)/);\n const hint = validUntilMatch\n ? ` (validUntil=${validUntilMatch[1]}, expired ${Math.floor(Date.now() / 1000) - Number(validUntilMatch[1])}s ago)`\n : \"\";\n message =\n `Paymaster price is stale${hint}. ` +\n `Call paymasterManager.checkPriceFreshness(paymasterAddress) to diagnose, ` +\n `then paymasterManager.updatePrice(paymasterAddress, signer) to refresh. ` +\n `Original error: ${message}`;\n error = new PaymasterPriceStalenessError(\n \"unknown\" /* paymasterAddress not available here */,\n 0,\n 0\n );\n (error as PaymasterPriceStalenessError & { message: string }).message = message;\n }\n\n await this.storage.updateTransfer(transferId, {\n status: \"failed\",\n error: message,\n failedAt: new Date().toISOString(),\n } as Partial<import(\"../interfaces/storage-adapter\").TransferRecord>);\n this.logger.error(`Transfer ${transferId} failed: ${message}`);\n }\n }\n\n async estimateGas(userId: string, params: EstimateGasParams) {\n const account = await this.accountManager.getAccountByUserId(userId);\n if (!account) throw new Error(\"User account not found\");\n\n const version = (account.entryPointVersion || \"0.6\") as unknown as EntryPointVersion;\n\n const userOp = await this.buildUserOperation(\n userId,\n account.address,\n params.to,\n params.amount,\n params.data || \"0x\",\n false,\n undefined,\n undefined,\n params.tokenAddress,\n version,\n undefined,\n params.wrapExecuteUserOp ?? false\n );\n\n const formatted = this.formatUserOpForBundler(userOp, version);\n const gasEstimates = await this.ethereum.estimateUserOperationGas(formatted, version);\n const gasPrices = await this.ethereum.getUserOperationGasPrice();\n\n const validatorContract = this.ethereum.getValidatorContract(version);\n // Typed wrapper enforces the uint256 `nodeCount` as bigint (a JS number would\n // risk silent truncation outside the 53-bit safe range on the loose surface).\n const validatorGasEstimate = await readValidatorGasEstimate(validatorContract, 3n);\n\n return {\n callGasLimit: gasEstimates.callGasLimit,\n verificationGasLimit: gasEstimates.verificationGasLimit,\n preVerificationGas: gasEstimates.preVerificationGas,\n validatorGasEstimate: validatorGasEstimate.toString(),\n totalGasEstimate: (\n BigInt(gasEstimates.callGasLimit) +\n BigInt(gasEstimates.verificationGasLimit) +\n BigInt(gasEstimates.preVerificationGas)\n ).toString(),\n maxFeePerGas: gasPrices.maxFeePerGas,\n maxPriorityFeePerGas: gasPrices.maxPriorityFeePerGas,\n };\n }\n\n async getTransferStatus(userId: string, transferId: string) {\n const transfer = await this.storage.findTransferById(transferId);\n if (!transfer || transfer.userId !== userId) {\n throw new Error(\"Transfer not found\");\n }\n\n const response: Record<string, unknown> = { ...transfer };\n\n if (transfer.status === \"pending\" || transfer.status === \"submitted\") {\n const elapsed = Math.floor((Date.now() - new Date(transfer.createdAt).getTime()) / 1000);\n response.elapsedSeconds = elapsed;\n }\n\n if (transfer.transactionHash) {\n response.explorerUrl = `https://sepolia.etherscan.io/tx/${transfer.transactionHash}`;\n }\n\n const statusDescriptions: Record<string, string> = {\n pending: \"Preparing transaction and generating signatures\",\n submitted: \"Transaction submitted to bundler, waiting for confirmation\",\n completed: \"Transaction confirmed on chain\",\n failed: \"Transaction failed\",\n };\n response.statusDescription = statusDescriptions[transfer.status] || transfer.status;\n\n return response;\n }\n\n async getTransferHistory(userId: string, page = 1, limit = 10) {\n const transfers = await this.storage.findTransfersByUserId(userId);\n if (!transfers || transfers.length === 0) {\n return { transfers: [], total: 0, page, limit, totalPages: 0 };\n }\n\n transfers.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());\n\n const start = (page - 1) * limit;\n const paginated = transfers.slice(start, start + limit);\n\n return {\n transfers: paginated,\n total: transfers.length,\n page,\n limit,\n totalPages: Math.ceil(transfers.length / limit),\n };\n }\n\n // ── Private helpers ─────────────────────────────────────────────\n\n private async buildUserOperation(\n userId: string,\n sender: string,\n to: string,\n amount: string,\n data: string,\n usePaymaster?: boolean,\n paymasterAddress?: string,\n _paymasterData?: string,\n tokenAddress?: string,\n version: EntryPointVersion = EntryPointVersion.V0_6,\n paymasterTokenAddress?: string,\n wrapExecuteUserOpFlag: boolean = false\n ): Promise<UserOperation | PackedUserOperation> {\n const nonce = await this.ethereum.getNonce(sender, 0, version);\n\n // initCode for deployment\n const provider = this.ethereum.getProvider();\n const code = await provider.getCode({ address: sender as Address });\n const needsDeployment = !code || code === \"0x\";\n\n let initCode = \"0x\";\n if (needsDeployment) {\n const accounts = await this.storage.getAccounts();\n const account = accounts.find(a => a.address === sender);\n if (account) {\n const factory = this.ethereum.getFactoryContract(version);\n const factoryAddress = factory.address;\n\n let deployCalldata: string;\n if (version === EntryPointVersion.V0_7 || version === EntryPointVersion.V0_8) {\n const storedDailyLimit = account.dailyLimit ? BigInt(account.dailyLimit) : 0n;\n if (account.guardianSpecs && account.guardianSpecs.length > 0) {\n // Full-config (P-256 / mixed-guardian) account (#118): rebuild the BYTE-IDENTICAL\n // 8-field InitConfig from the persisted record so the deploy CREATE2 address matches\n // the create-time prediction (the factory binds the address to keccak256(config)).\n const rebuilt = initConfigFromRecord(account);\n deployCalldata = encodeFn(AIRACCOUNT_FACTORY_ABI_PARSED, \"createAccount\", [\n account.signerAddress,\n BigInt(account.salt),\n initConfigToTuple(rebuilt),\n ]);\n } else if (account.guardian1 && account.guardian2 && account.guardian1Sig && account.guardian2Sig) {\n // Guardian account: use createAccountWithDefaults so the factory-computed address\n // matches the stored sender (which was predicted via getAddressWithDefaults).\n // bytes params require 0x-prefixed hex — guard against missing prefix.\n const sig1 = account.guardian1Sig.startsWith(\"0x\")\n ? account.guardian1Sig\n : `0x${account.guardian1Sig}`;\n const sig2 = account.guardian2Sig.startsWith(\"0x\")\n ? account.guardian2Sig\n : `0x${account.guardian2Sig}`;\n deployCalldata = encodeFn(AIRACCOUNT_FACTORY_ABI_PARSED, \"createAccountWithDefaults\", [\n account.signerAddress,\n BigInt(account.salt),\n account.guardian1,\n sig1,\n account.guardian2,\n sig2,\n storedDailyLimit,\n ]);\n } else {\n // Standard account: createAccount with zero guardians and stored dailyLimit.\n const minimalConfig = [\n [zeroAddress, zeroAddress, zeroAddress], // guardians (address[3])\n EMPTY_P256, // guardianP256X (bytes32[3]) — v0.20.0\n EMPTY_P256, // guardianP256Y (bytes32[3]) — v0.20.0\n storedDailyLimit,\n [], // approvedAlgIds\n 0n, // minDailyLimit\n [], // initialTokens\n [], // initialTokenConfigs\n ];\n deployCalldata = encodeFn(AIRACCOUNT_FACTORY_ABI_PARSED, \"createAccount\", [\n account.signerAddress,\n BigInt(account.salt),\n minimalConfig,\n ]);\n }\n } else {\n deployCalldata = encodeFn(FACTORY_ABI_V6_PARSED, \"createAccountWithAAStarValidator\", [\n account.signerAddress,\n account.signerAddress,\n account.validatorAddress,\n true,\n BigInt(account.salt),\n ]);\n }\n\n initCode = concat([factoryAddress as `0x${string}`, deployCalldata as `0x${string}`]);\n }\n }\n\n // callData\n let callData: string;\n if (tokenAddress) {\n const tokenInfo = await this.tokenService.getTokenInfo(tokenAddress);\n const transferCalldata = this.tokenService.generateTransferCalldata(\n to,\n amount,\n tokenInfo.decimals\n );\n callData = encodeFn(AIRACCOUNT_ABI_PARSED, \"execute\", [tokenAddress, 0n, transferCalldata]);\n } else {\n callData = encodeFn(AIRACCOUNT_ABI_PARSED, \"execute\", [to, parseEther(amount), data]);\n }\n\n // v0.17.2-beta.4: guard-enabled accounts must route bundler UserOps through\n // executeUserOp so the account re-derives the signature algId in-frame.\n if (wrapExecuteUserOpFlag) {\n callData = wrapExecuteUserOp(callData);\n }\n\n const gasPrices = await this.ethereum.getUserOperationGasPrice();\n\n const isV07 = version === EntryPointVersion.V0_7 || version === EntryPointVersion.V0_8;\n\n let baseUserOp: Record<string, unknown>;\n if (isV07) {\n // v0.7/v0.8: use factory/factoryData and separate paymaster fields\n let factory: string | undefined;\n let factoryData: string | undefined;\n if (initCode && initCode !== \"0x\" && initCode.length > 2) {\n factory = initCode.slice(0, 42);\n factoryData = initCode.length > 42 ? \"0x\" + initCode.slice(42) : \"0x\";\n }\n baseUserOp = {\n sender,\n nonce: \"0x\" + nonce.toString(16),\n ...(factory ? { factory, factoryData } : {}),\n callData,\n callGasLimit: \"0x0\",\n verificationGasLimit: \"0x0\",\n preVerificationGas: \"0x0\",\n maxFeePerGas: gasPrices.maxFeePerGas,\n maxPriorityFeePerGas: gasPrices.maxPriorityFeePerGas,\n signature: \"0x\",\n };\n } else {\n // v0.6: use initCode and paymasterAndData\n baseUserOp = {\n sender,\n nonce: \"0x\" + nonce.toString(16),\n initCode,\n callData,\n callGasLimit: \"0x0\",\n verificationGasLimit: \"0x0\",\n preVerificationGas: \"0x0\",\n maxFeePerGas: gasPrices.maxFeePerGas,\n maxPriorityFeePerGas: gasPrices.maxPriorityFeePerGas,\n paymasterAndData: \"0x\",\n signature: \"0x\",\n };\n }\n\n // Paymaster\n let paymasterAndData = \"0x\";\n if (usePaymaster) {\n if (paymasterAddress) {\n const entryPoint = this.ethereum.getEntryPointAddress(version);\n paymasterAndData = await this.paymasterManager.getPaymasterData(\n userId,\n \"custom-user-provided\",\n baseUserOp,\n entryPoint,\n paymasterAddress,\n paymasterTokenAddress ? { tokenAddress: paymasterTokenAddress } : undefined\n );\n } else {\n const available = await this.paymasterManager.getAvailablePaymasters(userId);\n const configured = available.find(pm => pm.configured);\n if (configured) {\n const entryPoint = this.ethereum.getEntryPointAddress(version);\n paymasterAndData = await this.paymasterManager.getPaymasterData(\n userId,\n configured.name,\n baseUserOp,\n entryPoint\n );\n } else {\n throw new Error(\"No paymaster configured and no paymaster address provided\");\n }\n }\n\n if (!paymasterAndData || paymasterAndData === \"0x\") {\n throw new Error(\n `Paymaster failed to provide sponsorship data. The paymaster at ${paymasterAddress} may not be configured correctly.`\n );\n }\n\n if (isV07) {\n // For v0.7, split paymasterAndData into separate fields on the baseUserOp\n baseUserOp.paymaster = paymasterAndData.slice(0, 42);\n if (paymasterAndData.length >= 74) {\n baseUserOp.paymasterVerificationGasLimit =\n \"0x\" + BigInt(\"0x\" + paymasterAndData.slice(42, 74)).toString(16);\n }\n if (paymasterAndData.length >= 106) {\n baseUserOp.paymasterPostOpGasLimit =\n \"0x\" + BigInt(\"0x\" + paymasterAndData.slice(74, 106)).toString(16);\n }\n if (paymasterAndData.length > 106) {\n baseUserOp.paymasterData = \"0x\" + paymasterAndData.slice(106);\n }\n } else {\n baseUserOp.paymasterAndData = paymasterAndData;\n }\n }\n\n // Gas estimation\n const gasEstimates = await this.ethereum.estimateUserOperationGas(baseUserOp, version);\n\n const standardUserOp: UserOperation = {\n sender,\n nonce,\n initCode,\n callData,\n callGasLimit: BigInt(gasEstimates.callGasLimit),\n verificationGasLimit: BigInt(gasEstimates.verificationGasLimit),\n preVerificationGas: BigInt(gasEstimates.preVerificationGas),\n maxFeePerGas: BigInt(gasPrices.maxFeePerGas),\n maxPriorityFeePerGas: BigInt(gasPrices.maxPriorityFeePerGas),\n paymasterAndData,\n signature: \"0x\",\n };\n\n if (version === EntryPointVersion.V0_7 || version === EntryPointVersion.V0_8) {\n return ERC4337Utils.packUserOperation(standardUserOp);\n }\n\n return standardUserOp;\n }\n\n private formatUserOpForBundler(\n userOp: UserOperation | PackedUserOperation,\n version: EntryPointVersion = EntryPointVersion.V0_6\n ): Record<string, unknown> {\n if (version === EntryPointVersion.V0_7 || version === EntryPointVersion.V0_8) {\n const packedOp = userOp as PackedUserOperation;\n const gasLimits = ERC4337Utils.unpackAccountGasLimits(packedOp.accountGasLimits);\n const gasFees = ERC4337Utils.unpackGasFees(packedOp.gasFees);\n\n let factory: string | undefined;\n let factoryData: string | undefined;\n if (packedOp.initCode && packedOp.initCode !== \"0x\" && packedOp.initCode.length > 2) {\n factory = packedOp.initCode.slice(0, 42);\n if (packedOp.initCode.length > 42) {\n factoryData = \"0x\" + packedOp.initCode.slice(42);\n }\n }\n\n let paymaster: string | undefined;\n let paymasterVerificationGasLimit: string | undefined;\n let paymasterPostOpGasLimit: string | undefined;\n let paymasterData: string | undefined;\n\n if (\n packedOp.paymasterAndData &&\n packedOp.paymasterAndData !== \"0x\" &&\n packedOp.paymasterAndData.length > 2\n ) {\n paymaster = packedOp.paymasterAndData.slice(0, 42);\n if (packedOp.paymasterAndData.length >= 74) {\n paymasterVerificationGasLimit =\n \"0x\" + BigInt(\"0x\" + packedOp.paymasterAndData.slice(42, 74)).toString(16);\n }\n if (packedOp.paymasterAndData.length >= 106) {\n paymasterPostOpGasLimit =\n \"0x\" + BigInt(\"0x\" + packedOp.paymasterAndData.slice(74, 106)).toString(16);\n }\n if (packedOp.paymasterAndData.length > 106) {\n paymasterData = \"0x\" + packedOp.paymasterAndData.slice(106);\n }\n }\n\n const result: Record<string, unknown> = {\n sender: packedOp.sender,\n nonce:\n typeof packedOp.nonce === \"bigint\"\n ? \"0x\" + packedOp.nonce.toString(16)\n : packedOp.nonce.toString().startsWith(\"0x\")\n ? packedOp.nonce.toString()\n : \"0x\" + BigInt(packedOp.nonce).toString(16),\n callData: packedOp.callData,\n callGasLimit: \"0x\" + gasLimits.callGasLimit.toString(16),\n verificationGasLimit: \"0x\" + gasLimits.verificationGasLimit.toString(16),\n preVerificationGas:\n typeof packedOp.preVerificationGas === \"bigint\"\n ? \"0x\" + packedOp.preVerificationGas.toString(16)\n : packedOp.preVerificationGas.toString().startsWith(\"0x\")\n ? packedOp.preVerificationGas.toString()\n : \"0x\" + BigInt(packedOp.preVerificationGas).toString(16),\n maxFeePerGas: \"0x\" + gasFees.maxFeePerGas.toString(16),\n maxPriorityFeePerGas: \"0x\" + gasFees.maxPriorityFeePerGas.toString(16),\n signature: packedOp.signature || \"0x\",\n };\n\n if (factory) result.factory = factory;\n if (factoryData) result.factoryData = factoryData;\n\n if (paymaster) {\n result.paymaster = paymaster;\n result.paymasterVerificationGasLimit = paymasterVerificationGasLimit || \"0x30000\";\n result.paymasterPostOpGasLimit = paymasterPostOpGasLimit || \"0x30000\";\n if (paymasterData && paymasterData !== \"0x\") {\n result.paymasterData = paymasterData;\n }\n }\n\n return result;\n }\n\n // v0.6 format\n const op = userOp as UserOperation;\n return {\n sender: op.sender,\n nonce: \"0x\" + op.nonce.toString(16),\n initCode: op.initCode,\n callData: op.callData,\n callGasLimit: \"0x\" + op.callGasLimit.toString(16),\n verificationGasLimit: \"0x\" + op.verificationGasLimit.toString(16),\n preVerificationGas: \"0x\" + op.preVerificationGas.toString(16),\n maxFeePerGas: \"0x\" + op.maxFeePerGas.toString(16),\n maxPriorityFeePerGas: \"0x\" + op.maxPriorityFeePerGas.toString(16),\n paymasterAndData: op.paymasterAndData,\n signature: op.signature,\n };\n }\n}\n","import { hexToBytes } from \"viem\";\nimport { keccak256 } from \"../../migration/viem/hashing\";\nimport axios from \"axios\";\n\n/**\n * Minimal guardian signer surface (was `ethers.Signer`): an external signer that\n * performs an EIP-191 personal-sign over raw bytes and returns a 0x-prefixed\n * 65-byte hex signature. Structural — any ethers/viem signer with this method fits.\n */\nexport interface GuardianSigner {\n signMessage(message: Uint8Array): Promise<string>;\n}\nimport {\n BLSManager,\n BLSSignatureData,\n CumulativeT2SignatureData,\n CumulativeT3SignatureData,\n} from \"../../core/bls\";\nimport { TierLevel } from \"../../core/tier\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport { IStorageAdapter } from \"../interfaces/storage-adapter\";\nimport { ISignerAdapter, PasskeyAssertionContext } from \"../interfaces/signer-adapter\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\nimport { ServerConfig } from \"../config\";\n\n/**\n * Raised when a DVT node (aNode YetAnotherAA-Validator ≥ v1.3.0, running with\n * `CONFIRM_ENABLED=true`) withholds its co-signature on a high-value op pending\n * out-of-band approval. The node returns `{ status: \"pending_confirmation\",\n * userOpHash }` instead of a signature; the withheld co-sign is released by\n * `POST /signature/confirm { userOpHash, token }` once the user approves over an\n * independent channel (single-use token, TTL, fail-closed). The SDK surfaces this\n * as a typed error rather than silently dropping the node so callers can drive the\n * confirm flow. Default-off nodes never emit this (behaviour == v1.2.0).\n */\nexport class DvtPendingConfirmationError extends Error {\n constructor(\n public readonly userOpHash: string,\n public readonly nodeEndpoint: string\n ) {\n super(\n `DVT node ${nodeEndpoint} withheld its co-signature pending out-of-band ` +\n `confirmation for userOpHash ${userOpHash}; release it via POST /signature/confirm.`\n );\n this.name = \"DvtPendingConfirmationError\";\n }\n}\n\n/**\n * Type guard for a DVT v1.3.0 `/signature/sign` response that withheld its\n * co-signature pending out-of-band confirmation (`{ status: \"pending_confirmation\",\n * userOpHash }`). Used at every sign call site so a high-value-op withhold is\n * surfaced, not mistaken for a signature-less failure. Default-off nodes never\n * return this shape.\n */\nexport function isPendingConfirmation(\n data: unknown\n): data is { status: \"pending_confirmation\"; userOpHash?: string } {\n return (\n typeof data === \"object\" &&\n data !== null &&\n (data as { status?: unknown }).status === \"pending_confirmation\"\n );\n}\n\n/**\n * BLS signature service — extracted from NestJS BlsService.\n * Uses lazy initialization instead of onModuleInit.\n */\nexport class BLSSignatureService {\n private blsManager: BLSManager | null = null;\n private readonly logger: ILogger;\n\n constructor(\n private readonly config: ServerConfig,\n private readonly ethereum: EthereumProvider,\n private readonly storage: IStorageAdapter,\n private readonly signer: ISignerAdapter,\n logger?: ILogger\n ) {\n this.logger = logger ?? new ConsoleLogger(\"[BLSSignatureService]\");\n }\n\n /** Lazy-initialize BLSManager on first use. */\n private async ensureInitialized(): Promise<BLSManager> {\n if (this.blsManager) return this.blsManager;\n\n const blsConfig = await this.storage.getBlsConfig();\n const seedNodes =\n this.config.blsSeedNodes ?? blsConfig?.discovery?.seedNodes?.map(n => n.endpoint) ?? [];\n\n this.blsManager = new BLSManager({\n seedNodes,\n discoveryTimeout: this.config.blsDiscoveryTimeout ?? 10000,\n });\n\n return this.blsManager;\n }\n\n async getActiveSignerNodes(): Promise<unknown[]> {\n const manager = await this.ensureInitialized();\n const nodes = await manager.getAvailableNodes();\n\n if (nodes.length > 0) {\n try {\n await this.storage.updateSignerNodesCache(nodes);\n } catch {\n // Non-critical\n }\n }\n\n return nodes;\n }\n\n async generateBLSSignature(\n userId: string,\n userOpHash: string,\n ctx?: PasskeyAssertionContext\n ): Promise<BLSSignatureData> {\n const manager = await this.ensureInitialized();\n\n const activeNodes = await this.getActiveSignerNodes();\n if (activeNodes.length < 1) {\n throw new Error(\"No active BLS signer nodes available\");\n }\n\n const selectedNodes = activeNodes.slice(0, Math.min(3, activeNodes.length)) as Array<{\n apiEndpoint: string;\n }>;\n\n const signerNodeSignatures: string[] = [];\n const signerNodeIds: string[] = [];\n\n for (const node of selectedNodes) {\n try {\n const response = await axios.post(`${node.apiEndpoint}/signature/sign`, {\n message: userOpHash,\n });\n\n // DVT v1.3.0: a CONFIRM_ENABLED node withholds its co-sign on a high-value\n // op until out-of-band approval. Surface it instead of treating the\n // signature-less response as a node failure to be skipped.\n if (isPendingConfirmation(response.data)) {\n throw new DvtPendingConfirmationError(response.data.userOpHash ?? userOpHash, node.apiEndpoint);\n }\n\n const signatureForAggregation = response.data.signatureCompact || response.data.signature;\n const formatted = signatureForAggregation.startsWith(\"0x\")\n ? signatureForAggregation\n : `0x${signatureForAggregation}`;\n\n signerNodeSignatures.push(formatted);\n signerNodeIds.push(response.data.nodeId);\n } catch (err) {\n if (err instanceof DvtPendingConfirmationError) throw err;\n // Continue with other nodes\n }\n }\n\n if (signerNodeSignatures.length === 0) {\n throw new Error(\"Failed to get signatures from any BLS signer nodes\");\n }\n\n let aggregatedSignature: string;\n if (signerNodeSignatures.length > 1) {\n const aggregateResponse = await axios.post(\n `${selectedNodes[0].apiEndpoint}/signature/aggregate`,\n { signatures: signerNodeSignatures }\n );\n aggregatedSignature = aggregateResponse.data.signature.startsWith(\"0x\")\n ? aggregateResponse.data.signature\n : `0x${aggregateResponse.data.signature}`;\n } else {\n // Single signature — re-request in EIP format\n const singleSignResponse = await axios.post(\n `${selectedNodes[0].apiEndpoint}/signature/sign`,\n { message: userOpHash }\n );\n if (isPendingConfirmation(singleSignResponse.data)) {\n throw new DvtPendingConfirmationError(\n singleSignResponse.data.userOpHash ?? userOpHash,\n selectedNodes[0].apiEndpoint\n );\n }\n aggregatedSignature = singleSignResponse.data.signature.startsWith(\"0x\")\n ? singleSignResponse.data.signature\n : `0x${singleSignResponse.data.signature}`;\n }\n\n // Generate message point\n const messagePoint = await manager.generateMessagePoint(userOpHash);\n\n // Get user account and wallet for ECDSA signatures\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) {\n throw new Error(`User account not found for userId: ${userId}`);\n }\n\n const walletAddress = await this.signer.getAddress(userId);\n\n if (walletAddress.toLowerCase() !== account.signerAddress.toLowerCase()) {\n throw new Error(\n `Wallet address mismatch! Wallet: ${walletAddress}, Expected: ${account.signerAddress}`\n );\n }\n\n const aaSignature = await this.signer.signMessage(\n userId,\n hexToBytes(userOpHash as `0x${string}`),\n ctx\n );\n const messagePointHash = keccak256(messagePoint as `0x${string}`);\n const messagePointSignature = await this.signer.signMessage(\n userId,\n hexToBytes(messagePointHash as `0x${string}`),\n ctx\n );\n\n return {\n nodeIds: signerNodeIds,\n signature: aggregatedSignature,\n messagePoint,\n aaAddress: account.signerAddress,\n aaSignature,\n messagePointSignature,\n };\n }\n\n async packSignature(blsData: BLSSignatureData): Promise<string> {\n const manager = await this.ensureInitialized();\n return manager.packSignature(blsData);\n }\n\n // ── Tiered Signature Support (M4) ─────────────────────────────\n\n /**\n * Generate a tiered signature based on the required tier level.\n *\n * - Tier 1: raw 65-byte ECDSA (no algId prefix, backwards-compat)\n * - Tier 2: algId 0x04 — P256 + BLS aggregate + messagePoint ECDSA\n * - Tier 3: algId 0x05 — P256 + BLS + messagePoint ECDSA + Guardian ECDSA\n *\n * @param tier - Required tier level (1, 2, or 3)\n * @param userId - User ID for account lookup\n * @param userOpHash - The UserOp hash to sign\n * @param p256Signature - P256 passkey signature (64 bytes, required for tier 2/3)\n * @param guardianSigner - Guardian signer (required for tier 3)\n * @param ctx - Optional passkey assertion context for KMS signing\n */\n async generateTieredSignature(params: {\n tier: TierLevel;\n userId: string;\n userOpHash: string;\n p256Signature?: string;\n guardianSigner?: GuardianSigner;\n ctx?: PasskeyAssertionContext;\n }): Promise<string> {\n const { tier, userId, userOpHash, p256Signature, guardianSigner, ctx } = params;\n const manager = await this.ensureInitialized();\n\n if (tier === 1) {\n // Tier 1: raw ECDSA signature (65 bytes, no algId prefix)\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) throw new Error(`User account not found for userId: ${userId}`);\n\n return this.signer.signMessage(userId, hexToBytes(userOpHash as `0x${string}`), ctx);\n }\n\n // Tier 2 and 3 both need BLS + P256\n if (!p256Signature) {\n throw new Error(`P256 signature required for Tier ${tier}`);\n }\n\n // Get BLS components (reuse existing generateBLSSignature for node signing + aggregation)\n const blsData = await this.generateBLSSignature(userId, userOpHash, ctx);\n\n if (tier === 2) {\n const t2Data: CumulativeT2SignatureData = {\n p256Signature,\n nodeIds: blsData.nodeIds,\n blsSignature: blsData.signature,\n messagePoint: blsData.messagePoint,\n messagePointSignature: blsData.messagePointSignature,\n };\n return manager.packCumulativeT2Signature(t2Data);\n }\n\n // Tier 3: also needs guardian signature\n if (!guardianSigner) {\n throw new Error(\"Guardian signer required for Tier 3\");\n }\n\n const guardianSignature = await guardianSigner.signMessage(\n hexToBytes(userOpHash as `0x${string}`)\n );\n\n const t3Data: CumulativeT3SignatureData = {\n p256Signature,\n nodeIds: blsData.nodeIds,\n blsSignature: blsData.signature,\n messagePoint: blsData.messagePoint,\n messagePointSignature: blsData.messagePointSignature,\n guardianSignature,\n };\n return manager.packCumulativeT3Signature(t3Data);\n }\n}\n","// eslint-disable-next-line no-restricted-imports\nimport { parseAbi, formatUnits, parseUnits, encodeFunctionData } from \"viem\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport { ERC20_ABI } from \"../constants/entrypoint\";\n\n// ERC20_ABI is a local human-readable `string[]` of signatures (not available in\n// @aastar/core), so parseAbi is required to feed it to viem read/encode helpers.\nconst ERC20_ABI_PARSED = parseAbi(ERC20_ABI);\n\nexport interface TokenInfo {\n address: string;\n symbol: string;\n name: string;\n decimals: number;\n}\n\nexport interface TokenBalance {\n token: TokenInfo;\n balance: string;\n formattedBalance: string;\n}\n\n/**\n * Token service — extracted from NestJS TokenService.\n * Only on-chain queries and calldata generation (no preset token list).\n */\nexport class TokenService {\n constructor(private readonly ethereum: EthereumProvider) {}\n\n async getTokenInfo(tokenAddress: string): Promise<TokenInfo> {\n const client = this.ethereum.getProvider();\n const address = tokenAddress as `0x${string}`;\n\n const [name, symbol, decimals] = await Promise.all([\n client.readContract({ address, abi: ERC20_ABI_PARSED, functionName: \"name\" }),\n client.readContract({ address, abi: ERC20_ABI_PARSED, functionName: \"symbol\" }),\n client.readContract({ address, abi: ERC20_ABI_PARSED, functionName: \"decimals\" }),\n ]);\n\n return {\n address: tokenAddress.toLowerCase(),\n name: name as string,\n symbol: symbol as string,\n decimals: Number(decimals),\n };\n }\n\n async getTokenBalance(tokenAddress: string, walletAddress: string): Promise<string> {\n const client = this.ethereum.getProvider();\n\n try {\n const balance = await client.readContract({\n address: tokenAddress as `0x${string}`,\n abi: ERC20_ABI_PARSED,\n functionName: \"balanceOf\",\n args: [walletAddress as `0x${string}`],\n });\n return (balance as bigint).toString();\n } catch {\n return \"0\";\n }\n }\n\n async getFormattedTokenBalance(\n tokenAddress: string,\n walletAddress: string\n ): Promise<TokenBalance> {\n const tokenInfo = await this.getTokenInfo(tokenAddress);\n const rawBalance = await this.getTokenBalance(tokenAddress, walletAddress);\n const formattedBalance = formatUnits(BigInt(rawBalance), tokenInfo.decimals);\n return { token: tokenInfo, balance: rawBalance, formattedBalance };\n }\n\n generateTransferCalldata(to: string, amount: string, decimals: number): string {\n // Calldata encoding does not depend on a contract address (the old ethers\n // call site passed ethers.ZeroAddress only to instantiate ethers.Contract).\n const parsedAmount = parseUnits(amount, decimals);\n return encodeFunctionData({\n abi: ERC20_ABI_PARSED,\n functionName: \"transfer\",\n args: [to as `0x${string}`, parsedAmount],\n });\n }\n\n async validateToken(tokenAddress: string): Promise<{\n isValid: boolean;\n token?: TokenInfo;\n error?: string;\n }> {\n try {\n const client = this.ethereum.getProvider();\n const address = tokenAddress as `0x${string}`;\n\n const [name, symbol, decimals] = (await Promise.race([\n Promise.all([\n client.readContract({ address, abi: ERC20_ABI_PARSED, functionName: \"name\" }),\n client.readContract({ address, abi: ERC20_ABI_PARSED, functionName: \"symbol\" }),\n client.readContract({ address, abi: ERC20_ABI_PARSED, functionName: \"decimals\" }),\n ]),\n new Promise((_, reject) => setTimeout(() => reject(new Error(\"Timeout\")), 10000)),\n ])) as [string, string, number];\n\n return {\n isValid: true,\n token: {\n address: tokenAddress.toLowerCase(),\n name,\n symbol,\n decimals: Number(decimals),\n },\n };\n } catch (error: unknown) {\n return {\n isValid: false,\n error: error instanceof Error ? error.message : \"Invalid ERC20 token\",\n };\n }\n }\n}\n","import { ISignerAdapter, PasskeyAssertionContext } from \"../interfaces/signer-adapter\";\n\n/**\n * Thin wrapper around ISignerAdapter for consistent wallet access.\n */\nexport class WalletManager {\n constructor(private readonly signer: ISignerAdapter) {}\n\n async getAddress(userId: string): Promise<`0x${string}`> {\n return this.signer.getAddress(userId);\n }\n\n async signMessage(\n userId: string,\n message: `0x${string}` | Uint8Array,\n ctx?: PasskeyAssertionContext\n ): Promise<`0x${string}`> {\n return this.signer.signMessage(userId, message, ctx);\n }\n\n async ensureSigner(userId: string): Promise<{ address: `0x${string}` }> {\n return this.signer.ensureSigner(userId);\n }\n}\n","import { ServerConfig, validateConfig } from \"./config\";\nimport { ConsoleLogger } from \"./interfaces/logger\";\nimport { EthereumProvider } from \"./providers/ethereum-provider\";\nimport { AccountManager } from \"./services/account-manager\";\nimport { TransferManager } from \"./services/transfer-manager\";\nimport { BLSSignatureService } from \"./services/bls-signature-service\";\nimport { PaymasterManager } from \"./services/paymaster-manager\";\nimport { TokenService } from \"./services/token-service\";\nimport { WalletManager } from \"./services/wallet-manager\";\n\n/**\n * Main facade for the YAAA Server SDK.\n * Wires all services together from a single config object.\n *\n * @example\n * ```ts\n * import { AirAccountServerClient, MemoryStorage, LocalWalletSigner } from '@aastar/airaccount/server';\n *\n * const client = new AirAccountServerClient({\n * rpcUrl: 'https://sepolia.infura.io/v3/...',\n * bundlerRpcUrl: 'https://api.pimlico.io/v2/11155111/rpc?apikey=...',\n * chainId: 11155111,\n * entryPoints: {\n * v06: {\n * entryPointAddress: '0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789',\n * factoryAddress: '0x...',\n * validatorAddress: '0x...',\n * },\n * },\n * storage: new MemoryStorage(),\n * signer: new LocalWalletSigner('0xPRIVATE_KEY'),\n * });\n *\n * const account = await client.accounts.createAccount('user-123');\n * ```\n */\nexport class AirAccountServerClient {\n readonly ethereum: EthereumProvider;\n readonly accounts: AccountManager;\n readonly transfers: TransferManager;\n readonly bls: BLSSignatureService;\n readonly paymaster: PaymasterManager;\n readonly tokens: TokenService;\n readonly wallets: WalletManager;\n\n constructor(config: ServerConfig) {\n validateConfig(config);\n\n const logger = config.logger ?? new ConsoleLogger(\"[YAAA]\");\n\n // Core provider\n this.ethereum = new EthereumProvider(config);\n\n // Service wiring (order matters: dependencies first)\n this.wallets = new WalletManager(config.signer);\n this.tokens = new TokenService(this.ethereum);\n this.paymaster = new PaymasterManager(this.ethereum, config.storage, logger);\n this.accounts = new AccountManager(this.ethereum, config.storage, config.signer, logger);\n this.bls = new BLSSignatureService(\n config,\n this.ethereum,\n config.storage,\n config.signer,\n logger\n );\n this.transfers = new TransferManager(\n this.ethereum,\n this.accounts,\n this.bls,\n this.paymaster,\n this.tokens,\n config.storage,\n config.signer,\n logger\n );\n }\n}\n\n/**\n * @deprecated Renamed to {@link AirAccountServerClient}. This alias is kept for\n * backward compatibility and will be removed in a future major version.\n */\nexport const YAAAServerClient = AirAccountServerClient;\n","/**\n * Viem reimplementation of the signature-normalization helpers that the\n * AirAccount KMS signer and EIP-7702 delegate service currently implement with\n * ethers.\n *\n * This is a NEW, parallel module written for the ethers -> viem migration. The\n * original ethers code (kms-signer.ts / eip7702-delegate-service.ts) is left\n * untouched; the differential parity test next to this file proves that, for\n * the same inputs, these viem helpers produce byte-identical results.\n *\n * The load-bearing invariant being migrated:\n * - The KMS and EIP-7702 paths assemble / consume a 65-byte signature laid\n * out as r(32) || s(32) || v(1), where the final byte v is the Ethereum\n * recovery id 27/28 (NOT the EIP-2098 yParity 0/1). viem's\n * parseSignature/serializeSignature must preserve this exact layout, and\n * must NOT emit the compact (64-byte) yParityAndS form.\n */\nimport {\n type Address,\n type Hex,\n type ByteArray,\n concatHex,\n hashMessage as viemHashMessage,\n keccak256,\n numberToHex,\n parseSignature,\n recoverAddress as viemRecoverAddress,\n recoverMessageAddress,\n serializeSignature,\n toRlp,\n} from \"viem\";\n\n/** The Ethereum personal-message hashable input (mirrors ethers.hashMessage). */\nexport type SignableMessage = string | ByteArray;\n\n/**\n * Normalize a 65-byte ECDSA signature to the canonical r(32)||s(32)||v(1)\n * serialization with v = 27/28.\n *\n * Equivalent to `ethers.Signature.from(sig).serialized`. Accepts a 65-byte\n * signature whose final byte is either the legacy recovery id (27/28) or the\n * raw yParity (0/1); both normalize to 27/28 in the output. The output is\n * ALWAYS 65 bytes — viem's compact yParityAndS variant is never produced.\n */\nexport function normalizeSignature(sig: Hex): Hex {\n const parsed = parseSignature(sig);\n // serializeSignature with a default `to: \"hex\"` and a v/yParity present\n // writes the 65-byte r||s||v form, mapping yParity 0 -> 0x1b, 1 -> 0x1c.\n return serializeSignature(parsed);\n}\n\n/**\n * Hash a personal message exactly like `ethers.hashMessage`.\n *\n * keccak256(\"\\x19Ethereum Signed Message:\\n\" + len + message). A `string` is\n * treated as UTF-8 text (NOT hex); a byte array is hashed as raw bytes.\n */\nexport function hashMessage(message: SignableMessage): Hex {\n if (typeof message === \"string\") return viemHashMessage(message);\n return viemHashMessage({ raw: message });\n}\n\n/**\n * Recover the signer address from a digest + 65-byte signature.\n *\n * Async equivalent of `ethers.recoverAddress(hash, sig)`. Returns a\n * checksummed address.\n */\nexport async function recoverAddress(hash: Hex, signature: Hex): Promise<Address> {\n return viemRecoverAddress({ hash, signature });\n}\n\n/**\n * Recover the signer address of a personal message.\n *\n * Async equivalent of `ethers.verifyMessage(message, sig)` (which returns the\n * recovered address). Returns a checksummed address.\n */\nexport async function verifyMessage(\n message: SignableMessage,\n signature: Hex\n): Promise<Address> {\n if (typeof message === \"string\") return recoverMessageAddress({ message, signature });\n return recoverMessageAddress({ message: { raw: message }, signature });\n}\n\n/**\n * Compute the EIP-7702 SET_CODE authorization hash that an EOA must sign.\n *\n * Hash = keccak256(0x05 || RLP([chainId, address, nonce]))\n *\n * Mirrors `EIP7702DelegateService.buildAuthorizationHash`. chainId and nonce\n * are RLP-encoded as minimal big-endian integers (0 -> empty byte string).\n */\nexport function buildAuthorizationHash(\n chainId: number,\n nonce: bigint,\n delegateAddress: Address\n): Hex {\n const encoded = toRlp([\n chainId === 0 ? \"0x\" : numberToHex(chainId),\n delegateAddress,\n nonce === 0n ? \"0x\" : numberToHex(nonce),\n ]);\n return keccak256(concatHex([\"0x05\", encoded]));\n}\n\n/**\n * Verify a 65-byte signature is a valid EIP-7702 authorization for `eoa`.\n *\n * Async equivalent of `EIP7702DelegateService.verifyAuthorization`. Recovers\n * the signer from the authorization hash and compares (case-insensitively)\n * against the expected EOA.\n */\nexport async function verifyAuthorization(\n eoa: Address,\n chainId: number,\n nonce: bigint,\n signature: Hex,\n delegateAddress: Address\n): Promise<boolean> {\n const hash = buildAuthorizationHash(chainId, nonce, delegateAddress);\n const recovered = await recoverAddress(hash, signature);\n return recovered.toLowerCase() === eoa.toLowerCase();\n}\n","import {\n concat,\n encodeFunctionData,\n hexToBytes,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\n// AIRACCOUNT_ABI is a local human-readable signature array (not in @aastar/core);\n// parseAbi is required to feed it to viem's readContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { MODULE_TYPE, AIRACCOUNT_ABI, AIRACCOUNT_ADDRESSES } from \"../constants/entrypoint\";\n// Byte-exact viem parity helpers (proven in migration/viem/*.parity.test.ts).\nimport { keccak256 } from \"../../migration/viem/hashing\";\nimport { solidityPacked } from \"../../migration/viem/abi-encoding\";\nimport { hashMessage } from \"../../migration/viem/signatures\";\n\nexport type ModuleTypeId = 1 | 2 | 3 | 4; // VALIDATOR | EXECUTOR | FALLBACK | HOOK\n\nexport interface InstallModuleParams {\n /** The deployed AirAccount address */\n account: string;\n /** ERC-7579 module type: 1=Validator, 2=Executor, 3=Fallback, 4=Hook */\n moduleTypeId: ModuleTypeId;\n /** Module contract address to install */\n module: string;\n /**\n * Guardian signatures + module init data, packed as:\n * bytes[0..65*sigsRequired] = guardian ECDSA sigs\n * bytes[65*sigsRequired..] = module onInstall() init data\n *\n * Sig hash (per guardian, r5 format):\n * keccak256(\"INSTALL_MODULE\" ‖ chainId ‖ account ‖ moduleTypeId ‖ module ‖ keccak256(moduleInitData)).toEthSignedMessageHash()\n *\n * sigsRequired: 0 if threshold<=40, 1 if <=70, 2 if =100\n */\n guardianSigs?: string[]; // 65-byte hex sigs from guardians\n /** Raw bytes passed to module.onInstall() after guardian sigs */\n moduleInitData?: string;\n}\n\nexport interface UninstallModuleParams {\n account: string;\n moduleTypeId: ModuleTypeId;\n module: string;\n /** Always requires 2 guardian sigs for uninstall */\n guardianSig1: string;\n guardianSig2: string;\n /** Passed to module.onUninstall() */\n moduleDeInitData?: string;\n}\n\n/**\n * Build the EIP-191 install hash that guardians must sign.\n *\n * r5 format: includes keccak256(moduleInitData) to prevent config-swap attacks.\n *\n * @example\n * const hash = buildInstallModuleHash(chainId, account, 1, moduleAddress, moduleInitData);\n * const sig = await guardian.signMessage(hexToBytes(hash));\n */\nexport function buildInstallModuleHash(\n chainId: number,\n account: string,\n moduleTypeId: ModuleTypeId,\n module: string,\n moduleInitData: string = \"0x\",\n): string {\n const moduleInitDataHash = keccak256(moduleInitData as Hex);\n const raw = keccak256(\n solidityPacked(\n [\"string\", \"uint256\", \"address\", \"uint256\", \"address\", \"bytes32\"],\n [\"INSTALL_MODULE\", BigInt(chainId), account, BigInt(moduleTypeId), module, moduleInitDataHash],\n ),\n );\n return hashMessage(hexToBytes(raw));\n}\n\n/**\n * Build the EIP-191 uninstall hash that guardians must sign.\n */\nexport function buildUninstallModuleHash(\n chainId: number,\n account: string,\n moduleTypeId: ModuleTypeId,\n module: string,\n): string {\n const raw = keccak256(\n solidityPacked(\n [\"string\", \"uint256\", \"address\", \"uint256\", \"address\"],\n [\"UNINSTALL_MODULE\", BigInt(chainId), account, BigInt(moduleTypeId), module],\n ),\n );\n return hashMessage(hexToBytes(raw));\n}\n\n/**\n * ModuleManager — ERC-7579 module install/uninstall helpers.\n *\n * Handles the guardian-sig packing required by AAStarAirAccountV7:\n * installModule(moduleTypeId, module, guardianSigs ‖ moduleInitData)\n * uninstallModule(moduleTypeId, module, guardianSig1 ‖ guardianSig2 ‖ deInitData)\n */\nexport class ModuleManager {\n private readonly provider: PublicClient;\n private readonly chainId: number;\n\n constructor(provider: PublicClient, chainId: number) {\n this.provider = provider;\n this.chainId = chainId;\n }\n\n /**\n * Encode calldata for installModule().\n * Caller is responsible for submitting via UserOp (EntryPoint) or direct tx.\n */\n encodeInstall(params: InstallModuleParams): string {\n const sigs = params.guardianSigs ?? [];\n const initData = (params.moduleInitData ?? \"0x\") as Hex;\n\n // Pack: guardian sigs (65 bytes each) concatenated with module init data.\n // viem `concat` over hex strings produces the same byte layout as\n // ethers.concat over getBytes(...) — the 0x prefixes are stripped per item.\n const packed: Hex =\n sigs.length > 0 ? concat([...(sigs as Hex[]), initData]) : initData;\n\n return encodeFunctionData({\n abi: parseAbi(AIRACCOUNT_ABI as readonly string[]),\n functionName: \"installModule\",\n args: [BigInt(params.moduleTypeId), params.module as Address, packed],\n });\n }\n\n /**\n * Encode calldata for uninstallModule().\n * Always requires 2 guardian signatures.\n */\n encodeUninstall(params: UninstallModuleParams): string {\n const deInitData = (params.moduleDeInitData ?? \"0x\") as Hex;\n const packed: Hex = concat([\n params.guardianSig1 as Hex,\n params.guardianSig2 as Hex,\n deInitData,\n ]);\n\n return encodeFunctionData({\n abi: parseAbi(AIRACCOUNT_ABI as readonly string[]),\n functionName: \"uninstallModule\",\n args: [BigInt(params.moduleTypeId), params.module as Address, packed],\n });\n }\n\n /** Check if a module is currently installed on the account. */\n async isInstalled(\n account: string,\n moduleTypeId: ModuleTypeId,\n module: string,\n ): Promise<boolean> {\n return (await this.provider.readContract({\n address: account as Address,\n abi: parseAbi(AIRACCOUNT_ABI as readonly string[]),\n functionName: \"isModuleInstalled\",\n args: [BigInt(moduleTypeId), module as Address, \"0x\"],\n })) as boolean;\n }\n\n /** Return the install hash for a guardian to sign (r5 format, includes moduleInitData hash). */\n installHash(account: string, moduleTypeId: ModuleTypeId, module: string, moduleInitData: string = \"0x\"): string {\n return buildInstallModuleHash(this.chainId, account, moduleTypeId, module, moduleInitData);\n }\n\n /** Return the uninstall hash for guardians to sign. */\n uninstallHash(account: string, moduleTypeId: ModuleTypeId, module: string): string {\n return buildUninstallModuleHash(this.chainId, account, moduleTypeId, module);\n }\n\n /**\n * Convenience: build install calldata for the standard M7 module set.\n * Uses pre-deployed Sepolia addresses (r4 audit-final). No guardian sigs required when\n * account threshold <= 40 (default for newly created accounts).\n *\n * Note: beta.3 unifies these into SessionKeyValidator. This helper retains the r4\n * addresses for accounts already deployed on r4; new accounts use SessionKeyValidator.\n */\n encodeInstallDefaultModules(account: string): {\n compositeValidator: string;\n tierGuardHook: string;\n } {\n const addresses = AIRACCOUNT_ADDRESSES.sepolia;\n return {\n compositeValidator: this.encodeInstall({\n account,\n moduleTypeId: MODULE_TYPE.VALIDATOR,\n module: addresses.compositeValidatorM7r4,\n }),\n tierGuardHook: this.encodeInstall({\n account,\n moduleTypeId: MODULE_TYPE.HOOK,\n module: addresses.tierGuardHookM7r4,\n }),\n };\n }\n}\n","import {\n getContract,\n encodeFunctionData,\n zeroAddress,\n type Abi,\n type PublicClient,\n} from \"viem\";\n// parseAbi is required to feed the local human-readable string[] ABIs to viem's\n// getContract / encodeFunctionData during the ethers->viem migration. These\n// validator ABIs are not available in @aastar/core.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport {\n SESSION_KEY_VALIDATOR_ABI,\n AGENT_SESSION_KEY_VALIDATOR_ABI,\n} from \"../constants/entrypoint\";\nimport { type ViemContract } from \"../providers/ethereum-provider\";\nimport { readBuildGrantHash, readBuildP256GrantHash } from \"../providers/typed-reads\";\n\n// Parse the local human-readable ABIs once. Widened to `Abi` so viem treats the\n// call args loosely (plain address strings / numbers) — matching the previous\n// ethers.Interface ergonomics without per-call `0x${string}` casts.\nconst SESSION_KEY_VALIDATOR_VIEM_ABI = parseAbi(SESSION_KEY_VALIDATOR_ABI) as Abi;\nconst AGENT_SESSION_KEY_VALIDATOR_VIEM_ABI = parseAbi(AGENT_SESSION_KEY_VALIDATOR_ABI) as Abi;\n\n// ─── M6 SessionKeyValidator ──────────────────────────────────────\n\nexport interface GrantSessionParams {\n /** Account that owns the session */\n account: string;\n /** The session key address (ephemeral EOA) */\n sessionKey: string;\n /** Expiry unix timestamp (max 7 days from now) */\n expiry: number;\n /** address(0) = any destination allowed */\n contractScope?: string;\n /** bytes4(0) = any selector allowed */\n selectorScope?: string;\n /** Max calls per velocityWindow (0 = unlimited). Session struct field. */\n velocityLimit?: number;\n /** Velocity window in seconds (0 = no window). Session struct field. */\n velocityWindow?: number;\n /** Allowed destination addresses ([] = any). Session struct field. */\n callTargets?: string[];\n /** Allowed selectors ([] = any). Session struct field. */\n selectorAllowlist?: string[];\n /** Owner signature over buildGrantHash() — omit if calling directly from account */\n ownerSig?: string;\n}\n\nexport interface SessionInfo {\n expiry: number;\n contractScope: string;\n selectorScope: string;\n revoked: boolean;\n velocityLimit: number;\n velocityWindow: number;\n callTargets: string[];\n selectorAllowlist: string[];\n active: boolean;\n}\n\nexport interface GrantP256SessionParams {\n /** Account that owns the session */\n account: string;\n /** P256 public key X coordinate (0x-prefixed 32-byte hex) */\n keyX: string;\n /** P256 public key Y coordinate (0x-prefixed 32-byte hex) */\n keyY: string;\n /** Expiry unix timestamp (max 7 days from now) */\n expiry: number;\n /** address(0) = any destination allowed */\n contractScope?: string;\n /** bytes4(0) = any selector allowed */\n selectorScope?: string;\n /** Max calls per velocityWindow (0 = unlimited). Session struct field. */\n velocityLimit?: number;\n /** Velocity window in seconds (0 = no window). Session struct field. */\n velocityWindow?: number;\n /** Allowed destination addresses ([] = any). Session struct field. */\n callTargets?: string[];\n /** Allowed selectors ([] = any). Session struct field. */\n selectorAllowlist?: string[];\n /** Owner signature over buildP256GrantHash() — omit if calling directly from the owner EOA */\n ownerSig?: string;\n}\n\n/**\n * The on-chain `Session` struct (8 fields), passed as a single tuple arg to the\n * grant/build functions and returned by getSession/getP256Session. Field order\n * MUST match SessionKeyValidator.sol and packages/core/src/abis/SessionKeyValidator.json:\n * (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked,\n * uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist)\n */\ninterface SessionStruct {\n expiry: number;\n contractScope: string;\n selectorScope: string;\n revoked: boolean;\n velocityLimit: number;\n velocityWindow: number;\n callTargets: string[];\n selectorAllowlist: string[];\n}\n\n/** Build the Session tuple from grant params; `revoked` is always false on grant. */\nfunction buildSessionStruct(params: {\n expiry: number;\n contractScope?: string;\n selectorScope?: string;\n velocityLimit?: number;\n velocityWindow?: number;\n callTargets?: string[];\n selectorAllowlist?: string[];\n}): SessionStruct {\n return {\n expiry: params.expiry,\n contractScope: params.contractScope ?? zeroAddress,\n selectorScope: params.selectorScope ?? \"0x00000000\",\n revoked: false,\n velocityLimit: params.velocityLimit ?? 0,\n velocityWindow: params.velocityWindow ?? 0,\n callTargets: params.callTargets ?? [],\n selectorAllowlist: params.selectorAllowlist ?? [],\n };\n}\n\n/**\n * The raw 8-field Session tuple as decoded by viem. Because the on-chain return\n * type names every tuple component (uint48 expiry, address contractScope, ...),\n * viem returns a NAMED object (not an array), so we read by field name. uint\n * fields come back as `bigint`.\n */\ninterface RawSession {\n expiry: bigint | number;\n contractScope: string;\n selectorScope: string;\n revoked: boolean;\n velocityLimit: bigint | number;\n velocityWindow: bigint | number;\n callTargets: readonly string[];\n selectorAllowlist: readonly string[];\n}\n\n/**\n * Decode the 8-field Session tuple returned by getSession/getP256Session into\n * a SessionInfo, computing the derived `active` flag.\n */\nfunction decodeSessionInfo(session: unknown): SessionInfo {\n const s = session as RawSession;\n const expiry = Number(s.expiry);\n const now = Math.floor(Date.now() / 1000);\n return {\n expiry,\n contractScope: s.contractScope,\n selectorScope: s.selectorScope,\n revoked: s.revoked,\n velocityLimit: Number(s.velocityLimit),\n velocityWindow: Number(s.velocityWindow),\n callTargets: [...(s.callTargets ?? [])],\n selectorAllowlist: [...(s.selectorAllowlist ?? [])],\n active: expiry > now && !s.revoked,\n };\n}\n\n// ─── M7 AgentSessionKeyValidator ─────────────────────────────────\n\nexport interface AgentSessionConfig {\n expiry: number; // Unix timestamp\n velocityLimit: number; // Max calls per velocityWindow (0 = unlimited)\n velocityWindow: number; // Window in seconds\n callTargets: string[]; // Allowed dest addresses (empty = any)\n selectorAllowlist: string[]; // Allowed selectors (empty = any)\n}\n\nexport interface AgentSessionInfo extends AgentSessionConfig {\n revoked: boolean;\n callCount: bigint;\n windowStart: bigint;\n}\n\n/**\n * SessionKeyService — manage M6 (basic) and M7 (agent) session keys.\n *\n * M6 SessionKeyValidator (algId=0x08):\n * Simple time-limited ECDSA/P256 key with optional contract+selector scope.\n * Used for standard delegated actions (hot wallet, automated tasks).\n *\n * M7 AgentSessionKeyValidator (algId=0x09):\n * Rich session key for AI agents: velocity limits, spend caps, call allowlists,\n * hierarchical delegation (parent → sub-agent with scope narrowing).\n */\nexport class SessionKeyService {\n private readonly skValidator: ViemContract;\n private readonly askValidator: ViemContract;\n\n constructor(\n provider: PublicClient,\n sessionKeyValidatorAddress: string,\n agentSessionKeyValidatorAddress: string,\n ) {\n this.skValidator = getContract({\n address: sessionKeyValidatorAddress as `0x${string}`,\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n client: provider,\n }) as unknown as ViemContract;\n this.askValidator = getContract({\n address: agentSessionKeyValidatorAddress as `0x${string}`,\n abi: AGENT_SESSION_KEY_VALIDATOR_VIEM_ABI,\n client: provider,\n }) as unknown as ViemContract;\n }\n\n // ── M6: Basic Session Keys ────────────────────────────────────\n\n /**\n * Build the hash that the account owner must sign to grant a session key.\n * Use grantSession() with this sig, or grantSessionDirect() from the account itself.\n */\n async buildGrantHash(params: Omit<GrantSessionParams, \"ownerSig\">): Promise<string> {\n return readBuildGrantHash(\n this.skValidator,\n params.account,\n params.sessionKey,\n buildSessionStruct(params)\n );\n }\n\n /** Query an ECDSA session key state (decodes the 8-field Session tuple). */\n async getSession(account: string, sessionKey: string): Promise<SessionInfo> {\n const session = await this.skValidator.read.getSession([account, sessionKey]);\n return decodeSessionInfo(session);\n }\n\n /** Check if an ECDSA session is currently active. */\n async isSessionActive(account: string, sessionKey: string): Promise<boolean> {\n return this.skValidator.read.isSessionActive([account, sessionKey]) as Promise<boolean>;\n }\n\n /**\n * Encode calldata for session grant.\n *\n * - **With ownerSig** → `grantSession()` — for gasless/UserOp flows.\n * Owner signs the GRANT_SESSION_V2 typed hash via KMS `sign-grant-session`,\n * then the relayer calls `grantSession(account, key, cfg, ownerSig)` on-chain.\n * This is the ONLY path for ERC-4337 sponsored / gasless grant flows.\n *\n * - **Without ownerSig** → `grantSessionDirect()` — **owner EOA direct-send only**.\n * Since v0.17.2 round 3, `grantSessionDirect` requires `msg.sender == ownerOf(account)`.\n * It does NOT accept `msg.sender == account` (removed in round 3 — confused-deputy fix).\n * Do NOT encode this for a UserOp callData; the EntryPoint is not the owner EOA.\n */\n encodeGrantSession(params: GrantSessionParams): string {\n const cfg = buildSessionStruct(params);\n if (params.ownerSig) {\n return encodeFunctionData({\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"grantSession\",\n args: [params.account, params.sessionKey, cfg, params.ownerSig],\n });\n }\n // grantSessionDirect — owner EOA direct tx only (NOT for UserOp/gasless flows).\n return encodeFunctionData({\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"grantSessionDirect\",\n args: [params.account, params.sessionKey, cfg],\n });\n }\n\n /** Encode calldata for revokeSession(). */\n encodeRevokeSession(account: string, sessionKey: string): string {\n return encodeFunctionData({\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"revokeSession\",\n args: [account, sessionKey],\n });\n }\n\n // ── M6: P256 / Passkey Session Keys ───────────────────────────\n\n /**\n * Build the hash that the account owner must sign to grant a P256/passkey session key.\n * Use grantP256Session() with this sig, or grantP256SessionDirect() from the owner EOA itself.\n * The owner/KMS signs this hash to authorize a gasless grantP256Session().\n */\n async buildP256GrantHash(\n params: Omit<GrantP256SessionParams, \"ownerSig\">,\n ): Promise<string> {\n return readBuildP256GrantHash(\n this.skValidator,\n params.account,\n params.keyX,\n params.keyY,\n buildSessionStruct(params)\n );\n }\n\n /**\n * Query a P256 session key state (decodes the 8-field Session tuple).\n * @param keyHash The keccak256 hash of (keyX, keyY) used as the on-chain session id.\n */\n async getP256Session(account: string, keyHash: string): Promise<SessionInfo> {\n const session = await this.skValidator.read.getP256Session([account, keyHash]);\n return decodeSessionInfo(session);\n }\n\n /** Check if a P256 session is currently active. */\n async isP256SessionActive(account: string, keyX: string, keyY: string): Promise<boolean> {\n return this.skValidator.read.isP256SessionActive([account, keyX, keyY]) as Promise<boolean>;\n }\n\n /**\n * Encode calldata for a P256/passkey session grant.\n *\n * - **With ownerSig** → `grantP256Session()` — for gasless/UserOp flows.\n * Owner signs the buildP256GrantHash() digest via KMS `sign-p256-grant-session`,\n * then the relayer calls `grantP256Session(account, keyX, keyY, cfg, ownerSig)` on-chain.\n * This is the ONLY path for ERC-4337 sponsored / gasless P256 grant flows.\n *\n * - **Without ownerSig** → `grantP256SessionDirect()` — **owner EOA direct-send only**.\n * Since v0.17.2 round 3, `grantP256SessionDirect` requires `msg.sender == ownerOf(account)`.\n * It does NOT accept `msg.sender == account` (removed in round 3 — confused-deputy fix).\n * Do NOT encode this for a UserOp callData; the EntryPoint is not the owner EOA.\n */\n encodeGrantP256Session(params: GrantP256SessionParams): string {\n const cfg = buildSessionStruct(params);\n if (params.ownerSig) {\n return encodeFunctionData({\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"grantP256Session\",\n args: [params.account, params.keyX, params.keyY, cfg, params.ownerSig],\n });\n }\n // grantP256SessionDirect — owner EOA direct tx only (NOT for UserOp/gasless flows).\n return encodeFunctionData({\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"grantP256SessionDirect\",\n args: [params.account, params.keyX, params.keyY, cfg],\n });\n }\n\n /** Encode calldata for revokeP256Session(). */\n encodeRevokeP256Session(account: string, keyX: string, keyY: string): string {\n return encodeFunctionData({\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"revokeP256Session\",\n args: [account, keyX, keyY],\n });\n }\n\n // ── M7: Agent Session Keys ────────────────────────────────────\n\n /**\n * Encode calldata for grantAgentSession().\n * Must be called from the account (via UserOp or direct execute).\n * The contract uses msg.sender as the account — no account param needed.\n */\n encodeGrantAgentSession(sessionKey: string, cfg: AgentSessionConfig): string {\n return encodeFunctionData({\n abi: AGENT_SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"grantAgentSession\",\n args: [\n sessionKey,\n {\n expiry: cfg.expiry,\n velocityLimit: cfg.velocityLimit,\n velocityWindow: cfg.velocityWindow,\n revoked: false,\n callTargets: cfg.callTargets,\n selectorAllowlist: cfg.selectorAllowlist,\n },\n ],\n });\n }\n\n /**\n * Encode calldata for delegateSession() — sub-agent delegation.\n * The sub-agent config must be a strict subset of the parent session's scope.\n * Called by the parent session key (not the account owner).\n * @param account The smart account under which the parent session was granted.\n */\n encodeDelegateSession(account: string, subKey: string, subCfg: AgentSessionConfig): string {\n return encodeFunctionData({\n abi: AGENT_SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"delegateSession\",\n args: [\n account,\n subKey,\n {\n expiry: subCfg.expiry,\n velocityLimit: subCfg.velocityLimit,\n velocityWindow: subCfg.velocityWindow,\n revoked: false,\n callTargets: subCfg.callTargets,\n selectorAllowlist: subCfg.selectorAllowlist,\n },\n ],\n });\n }\n\n /** Encode calldata for revokeAgentSession(). */\n encodeRevokeAgentSession(sessionKey: string): string {\n return encodeFunctionData({\n abi: AGENT_SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"revokeAgentSession\",\n args: [sessionKey],\n });\n }\n\n /** Query agent session config + runtime state. */\n async getAgentSession(account: string, sessionKey: string): Promise<AgentSessionInfo> {\n // Multi-output view fns are returned by viem as a positional array.\n const [expiry, velocityLimit, velocityWindow, revoked, callTargets, selectorAllowlist] =\n (await this.askValidator.read.agentSessions([account, sessionKey])) as readonly unknown[];\n const [callCount, windowStart] =\n (await this.askValidator.read.sessionStates([account, sessionKey])) as readonly unknown[];\n return {\n expiry: Number(expiry),\n velocityLimit: Number(velocityLimit),\n velocityWindow: Number(velocityWindow),\n callTargets: callTargets as string[],\n selectorAllowlist: selectorAllowlist as string[],\n revoked: revoked as boolean,\n callCount: BigInt(callCount as bigint),\n windowStart: BigInt(windowStart as bigint),\n };\n }\n\n /** Check if an agent session is active (not expired, not revoked). */\n async isAgentSessionActive(account: string, sessionKey: string): Promise<boolean> {\n const session = await this.getAgentSession(account, sessionKey);\n return session.expiry > Math.floor(Date.now() / 1000) && !session.revoked;\n }\n\n /** Return the parent account of a delegated session key. */\n async getSessionKeyOwner(sessionKey: string): Promise<string> {\n return this.askValidator.read.sessionKeyOwner([sessionKey]) as Promise<string>;\n }\n\n /** Return the parent key that delegated to subKey, or ZeroAddress if not delegated. */\n async getDelegatedBy(account: string, subKey: string): Promise<string> {\n return this.askValidator.read.delegatedBy([account, subKey]) as Promise<string>;\n }\n}\n\n// ─── UserOp Signature Packing (v0.17.2+) ────────────────────────\n\n/**\n * Pack a secp256k1 session key signature into the 106-byte UserOp.signature format.\n *\n * Layout: [0x08][account(20)][sessionKey(20)][r(32)][s(32)][v(1)]\n *\n * @param account - The AirAccount address (20 bytes, with or without 0x)\n * @param sessionKey - The ephemeral EOA session key address (20 bytes)\n * @param signature - 65-byte hex signature from KMS sign-grant-session (R||S||V)\n * @returns 106-byte hex string (0x-prefixed) suitable as UserOp.signature\n */\nexport function packSecp256k1SessionSignature(\n account: string,\n sessionKey: string,\n signature: string\n): string {\n const acc = account.startsWith(\"0x\") ? account.slice(2) : account;\n const key = sessionKey.startsWith(\"0x\") ? sessionKey.slice(2) : sessionKey;\n const sig = signature.startsWith(\"0x\") ? signature.slice(2) : signature;\n\n if (acc.length !== 40) throw new Error(\"account must be 20 bytes (40 hex chars)\");\n if (key.length !== 40) throw new Error(\"sessionKey must be 20 bytes (40 hex chars)\");\n if (sig.length !== 130) throw new Error(\"signature must be 65 bytes (130 hex chars)\");\n\n // [0x08][account(20)][sessionKey(20)][r(32)][s(32)][v(1)] = 106 bytes\n return `0x08${acc}${key}${sig}`;\n}\n\n/**\n * Pack a P256 session key signature into the 149-byte UserOp.signature format.\n *\n * Layout: [0x08][account(20)][keyX(32)][keyY(32)][r(32)][s(32)]\n *\n * @param account - The AirAccount address (20 bytes)\n * @param keyX - P256 public key X coordinate (32 bytes hex, without 0x)\n * @param keyY - P256 public key Y coordinate (32 bytes hex, without 0x)\n * @param signature - 64-byte hex signature from KMS sign-p256-grant-session (R||S, no V)\n * @returns 149-byte hex string (0x-prefixed) suitable as UserOp.signature\n */\nexport function packP256SessionSignature(\n account: string,\n keyX: string,\n keyY: string,\n signature: string\n): string {\n const acc = account.startsWith(\"0x\") ? account.slice(2) : account;\n const x = keyX.startsWith(\"0x\") ? keyX.slice(2) : keyX;\n const y = keyY.startsWith(\"0x\") ? keyY.slice(2) : keyY;\n const sig = signature.startsWith(\"0x\") ? signature.slice(2) : signature;\n\n if (acc.length !== 40) throw new Error(\"account must be 20 bytes (40 hex chars)\");\n if (x.length !== 64) throw new Error(\"keyX must be 32 bytes (64 hex chars)\");\n if (y.length !== 64) throw new Error(\"keyY must be 32 bytes (64 hex chars)\");\n if (sig.length !== 128) throw new Error(\"P256 signature must be 64 bytes (128 hex chars, R||S)\");\n\n // [0x08][account(20)][keyX(32)][keyY(32)][r(32)][s(32)] = 149 bytes\n return `0x08${acc}${x}${y}${sig}`;\n}\n","import { getContract, zeroAddress, type Address, type PublicClient } from \"viem\";\n// EntryPoint/AirAccount/Guard ABIs are local human-readable signatures (not in @aastar/core);\n// parseAbi is required to feed them to viem's getContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { AIRACCOUNT_ABI, GLOBAL_GUARD_ABI } from \"../constants/entrypoint\";\n\nconst EXTENDED_GUARD_ABI = [\n ...GLOBAL_GUARD_ABI,\n \"function todaySpent() external view returns (uint256)\",\n \"function tokenTodaySpent(address token) external view returns (uint256)\",\n // approvedAlgorithms removed from the guard in v0.17.2-beta.4 — now read from the account.\n \"function tier1Limit() external view returns (uint256)\",\n \"function tier2Limit() external view returns (uint256)\",\n \"function minDailyLimit() external view returns (uint256)\",\n];\n\nexport type TierLevel = 1 | 2 | 3;\n\nexport interface GuardState {\n /** ETH daily limit in wei */\n dailyLimit: bigint;\n /** ETH already spent today in wei */\n todaySpent: bigint;\n /** ETH remaining for today in wei */\n remaining: bigint;\n /** Current tier based on spent amount */\n currentTier: TierLevel;\n /** Tier 1 max spend threshold in wei (single sig) */\n tier1Limit: bigint;\n /** Tier 2 max spend threshold in wei (dual sig) */\n tier2Limit: bigint;\n /** Minimum daily limit floor (cannot decrease below this) */\n minDailyLimit: bigint;\n /** Guard contract address */\n guardAddress: string;\n}\n\nexport interface TokenGuardState {\n token: string;\n todaySpent: bigint;\n dailyLimit: bigint;\n remaining: bigint;\n currentTier: TierLevel;\n tier1Limit: bigint;\n tier2Limit: bigint;\n}\n\n/** Loosely-typed read surface for viem contracts built from human-readable ABIs. */\ntype ReadMethods = Record<string, (args?: unknown[]) => Promise<unknown>>;\n\n/**\n * GuardStateReader — F6: read AAStarGlobalGuard spending state.\n *\n * Enables UI components to show:\n * - Daily spend progress bar\n * - Current required tier (T1/T2/T3) for next transaction\n * - Per-token limits and remaining allowances\n */\nexport class GuardStateReader {\n private readonly provider: PublicClient;\n\n constructor(provider: PublicClient) {\n this.provider = provider;\n }\n\n private accountContract(accountAddress: string) {\n return getContract({\n address: accountAddress as Address,\n abi: parseAbi(AIRACCOUNT_ABI as readonly string[]),\n client: this.provider,\n });\n }\n\n private guardContract(guardAddress: string) {\n return getContract({\n address: guardAddress as Address,\n abi: parseAbi(EXTENDED_GUARD_ABI as readonly string[]),\n client: this.provider,\n });\n }\n\n /**\n * Read the full ETH guard state for an account.\n * Returns null if the account has no guard (dailyLimit=0).\n */\n async getGuardState(accountAddress: string): Promise<GuardState | null> {\n const account = this.accountContract(accountAddress).read as ReadMethods;\n const guardAddress = (await account.guard([])) as string;\n if (guardAddress === zeroAddress) return null;\n\n const guard = this.guardContract(guardAddress).read as ReadMethods;\n const [dailyLimit, remaining, todaySpent, tier1Limit, tier2Limit, minDailyLimit] =\n await Promise.all([\n guard.dailyLimit([]),\n guard.remainingDailyAllowance([]),\n guard.todaySpent([]),\n guard.tier1Limit([]).catch(() => 0n),\n guard.tier2Limit([]).catch(() => 0n),\n guard.minDailyLimit([]).catch(() => 0n),\n ]);\n\n return {\n dailyLimit: BigInt(dailyLimit as bigint),\n todaySpent: BigInt(todaySpent as bigint),\n remaining: BigInt(remaining as bigint),\n currentTier: resolveTierFromSpend(\n BigInt(todaySpent as bigint),\n BigInt(tier1Limit as bigint),\n BigInt(tier2Limit as bigint),\n ),\n tier1Limit: BigInt(tier1Limit as bigint),\n tier2Limit: BigInt(tier2Limit as bigint),\n minDailyLimit: BigInt(minDailyLimit as bigint),\n guardAddress,\n };\n }\n\n /**\n * Read per-token guard state.\n * Returns null if the token is not configured on the guard.\n */\n async getTokenGuardState(\n accountAddress: string,\n token: string,\n ): Promise<TokenGuardState | null> {\n const account = this.accountContract(accountAddress).read as ReadMethods;\n const guardAddress = (await account.guard([])) as string;\n if (guardAddress === zeroAddress) return null;\n\n const guard = this.guardContract(guardAddress).read as ReadMethods;\n try {\n const todaySpent = await guard.tokenTodaySpent([token as Address]);\n // TokenConfig is not directly readable on-chain per token; limits are not fully implemented.\n return {\n token,\n todaySpent: BigInt(todaySpent as bigint),\n dailyLimit: 0n, // token daily limit not directly exposed\n remaining: 0n,\n currentTier: 1 as TierLevel,\n tier1Limit: 0n,\n tier2Limit: 0n,\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Determine the minimum tier required to send a given ETH amount.\n * Useful for showing \"this transfer needs 2 signatures\" before submission.\n */\n async requiredTierForAmount(\n accountAddress: string,\n amountWei: bigint,\n ): Promise<TierLevel> {\n const state = await this.getGuardState(accountAddress);\n if (!state) return 1; // No guard = no tier restriction\n\n const projectedSpend = state.todaySpent + amountWei;\n return resolveTierFromSpend(projectedSpend, state.tier1Limit, state.tier2Limit);\n }\n\n /**\n * Check if a given algorithm ID is approved on the guard.\n */\n async isAlgorithmApproved(accountAddress: string, algId: number): Promise<boolean> {\n // v0.17.2-beta.4: the algorithm whitelist lives on the ACCOUNT (single source of\n // truth, enforced in validateUserOp), not the guard.\n const account = this.accountContract(accountAddress).read as ReadMethods;\n // approvedAlgorithms(uint8 algId): viem requires uint args as bigint.\n return (await account.approvedAlgorithms([BigInt(algId)])) as boolean;\n }\n}\n\n/**\n * Resolve required tier from cumulative spend vs tier thresholds.\n *\n * tier1Limit=0 means no Tier-1 cap (everything is Tier 1).\n * tier2Limit=0 means no Tier-2 cap (anything above tier1 is Tier 2).\n */\nfunction resolveTierFromSpend(\n spent: bigint,\n tier1Limit: bigint,\n tier2Limit: bigint,\n): TierLevel {\n if (tier1Limit === 0n) return 1;\n if (spent < tier1Limit) return 1;\n if (tier2Limit === 0n || spent < tier2Limit) return 2;\n return 3;\n}\n","// eslint-disable-next-line no-restricted-imports -- AIRACCOUNT_FACTORY_ABI is a local human-readable string[] (not in @aastar/core); parseAbi is required to feed it to viem readContract.\nimport { parseAbi, type PublicClient } from \"viem\";\nimport { keccak256 } from \"../../migration/viem/hashing\";\nimport { solidityPacked } from \"../../migration/viem/abi-encoding\";\nimport { AIRACCOUNT_ADDRESSES, AIRACCOUNT_FACTORY_ABI } from \"../constants/entrypoint\";\n\n/**\n * OAPD — One Account Per DApp address derivation (F7).\n *\n * Each DApp gets a unique counterfactual AirAccount address derived from:\n * salt = keccak256(owner ‖ dappId)\n *\n * This prevents DApps from correlating user activity across sites while\n * sharing the same underlying owner key and guardians.\n *\n * The OAPD address is a standard AirAccount clone — it has its own guard,\n * its own daily limits, and can be funded independently.\n */\n\n// Parse the local human-readable factory ABI once so viem reads can consume it.\nconst FACTORY_ABI = parseAbi(AIRACCOUNT_FACTORY_ABI);\n\nexport interface OapdConfig {\n /** Account owner address */\n owner: string;\n /** DApp identifier — use the DApp's domain or contract address */\n dappId: string;\n /** Factory address (defaults to M7 Sepolia) */\n factoryAddress?: string;\n /**\n * InitConfig for the OAPD account.\n * Typically lower daily limits than the main account.\n */\n initConfig: {\n guardians: [string, string, string];\n // v0.20.0 (#120): P-256 guardian keys (bytes32[3] each), inserted after `guardians`.\n // ECDSA-only OAPD accounts pass three zero words for each.\n guardianP256X: [string, string, string];\n guardianP256Y: [string, string, string];\n dailyLimit: bigint;\n approvedAlgIds: number[];\n minDailyLimit: bigint;\n initialTokens: string[];\n initialTokenConfigs: Array<{\n tier1Limit: bigint;\n tier2Limit: bigint;\n dailyLimit: bigint;\n }>;\n };\n}\n\n/**\n * Compute the numeric salt for an OAPD address.\n * salt = uint256(keccak256(abi.encodePacked(owner, dappId)))\n */\nexport function computeOapdSalt(owner: string, dappId: string): bigint {\n const packed = solidityPacked([\"address\", \"string\"], [owner, dappId]);\n return BigInt(keccak256(packed));\n}\n\n/**\n * Predict the counterfactual OAPD address without deploying.\n * Uses the factory's getAddress() view function.\n */\nexport async function getOapdAddress(\n provider: PublicClient,\n config: OapdConfig,\n): Promise<string> {\n const factoryAddress = config.factoryAddress ?? AIRACCOUNT_ADDRESSES.sepolia.factory;\n const salt = computeOapdSalt(config.owner, config.dappId);\n\n return provider.readContract({\n address: factoryAddress as `0x${string}`,\n abi: FACTORY_ABI,\n functionName: \"getAddress\",\n args: [config.owner as `0x${string}`, salt, config.initConfig],\n }) as Promise<string>;\n}\n\n/**\n * Get the OAPD address and its ERC-7828 chain-qualified identifier.\n */\nexport async function getOapdAddressWithChainId(\n provider: PublicClient,\n config: OapdConfig,\n): Promise<{ address: string; chainQualified: string }> {\n const factoryAddress = config.factoryAddress ?? AIRACCOUNT_ADDRESSES.sepolia.factory;\n const salt = computeOapdSalt(config.owner, config.dappId);\n\n const result = (await provider.readContract({\n address: factoryAddress as `0x${string}`,\n abi: FACTORY_ABI,\n functionName: \"getAddressWithChainId\",\n args: [config.owner as `0x${string}`, salt, config.initConfig],\n })) as readonly [string, string];\n return { address: result[0], chainQualified: result[1] };\n}\n\n/**\n * Check if an OAPD account has been deployed yet.\n */\nexport async function isOapdDeployed(\n provider: PublicClient,\n config: OapdConfig,\n): Promise<boolean> {\n const address = await getOapdAddress(provider, config);\n // viem getCode returns the deployed bytecode, or `undefined` when the\n // address has no code (the ethers equivalent returned \"0x\").\n const code = await provider.getCode({ address: address as `0x${string}` });\n return code !== undefined && code !== \"0x\";\n}\n","import { getContract, zeroAddress } from \"viem\";\n// GLOBAL_GUARD_ABI is a local human-readable signature array (not in @aastar/core);\n// parseAbi is required to feed it to viem's getContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { EthereumProvider, type ViemContract } from \"../providers/ethereum-provider\";\nimport {\n readAccountTierLimits,\n readAccountGuardAddress,\n readGuardDailyAllowance,\n readAlgorithmApproved,\n} from \"../providers/typed-reads\";\nimport { GLOBAL_GUARD_ABI } from \"../constants/entrypoint\";\nimport {\n TierConfig,\n GuardStatus,\n PreCheckResult,\n ALG_ECDSA,\n ALG_P256,\n ALG_BLS,\n ALG_CUMULATIVE_T2,\n ALG_CUMULATIVE_T3,\n} from \"../../core/tier\";\nimport { resolveTier, algIdForTier } from \"../../core/tier\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\n\nconst ALG_NAMES: Record<number, string> = {\n [ALG_BLS]: \"BLS (0x01)\",\n [ALG_ECDSA]: \"ECDSA (0x02)\",\n [ALG_P256]: \"P256 (0x03)\",\n [ALG_CUMULATIVE_T2]: \"Cumulative T2 (0x04)\",\n [ALG_CUMULATIVE_T3]: \"Cumulative T3 (0x05)\",\n};\n\n/**\n * Pre-checks transactions against GlobalGuard before submitting on-chain.\n * Avoids wasted gas from predictable reverts.\n */\nexport class GuardChecker {\n private readonly logger: ILogger;\n\n constructor(\n private readonly ethereum: EthereumProvider,\n logger?: ILogger\n ) {\n this.logger = logger ?? new ConsoleLogger(\"[GuardChecker]\");\n }\n\n /**\n * Fetch tier limits from an AirAccount contract.\n */\n async fetchTierConfig(accountAddress: string): Promise<TierConfig> {\n const account = this.ethereum.getAccountContract(accountAddress);\n // Typed wrapper returns both uint256 tier limits as bigint.\n return readAccountTierLimits(account);\n }\n\n /**\n * Fetch guard status from the account's GlobalGuard.\n */\n async fetchGuardStatus(accountAddress: string): Promise<GuardStatus> {\n const account = this.ethereum.getAccountContract(accountAddress);\n\n // getConfigDescription returns a single tuple struct; the typed wrapper reads\n // the `guardAddress` field that decides whether the guard is enforced at all.\n const guardAddress = await readAccountGuardAddress(account);\n\n if (guardAddress === zeroAddress) {\n return {\n hasGuard: false,\n guardAddress: zeroAddress,\n dailyLimit: 0n,\n dailyRemaining: 0n,\n };\n }\n\n const guard = getContract({\n address: guardAddress,\n abi: parseAbi(GLOBAL_GUARD_ABI),\n client: this.ethereum.getProvider(),\n }) as unknown as ViemContract;\n // Typed wrapper returns both uint256 daily-allowance values as bigint.\n const { dailyLimit, dailyRemaining } = await readGuardDailyAllowance(guard);\n\n return {\n hasGuard: true,\n guardAddress,\n dailyLimit,\n dailyRemaining,\n };\n }\n\n /**\n * Pre-check a transaction: determine tier, check guard limits and algorithm approval.\n * Returns errors array (empty = OK to proceed).\n */\n async preCheck(accountAddress: string, value: bigint): Promise<PreCheckResult> {\n const errors: string[] = [];\n\n // Fetch tier config → resolve tier → get algId\n const tierConfig = await this.fetchTierConfig(accountAddress);\n const tier = resolveTier(value, tierConfig);\n const algId = algIdForTier(tier);\n\n // Fetch guard status\n const guard = await this.fetchGuardStatus(accountAddress);\n\n if (!guard.hasGuard) {\n return { ok: true, errors: [], tier, algId };\n }\n\n // Check daily allowance\n if (guard.dailyLimit > 0n && value > guard.dailyRemaining) {\n errors.push(\n `Daily limit exceeded: requesting ${value} wei but only ${guard.dailyRemaining} remaining (limit: ${guard.dailyLimit})`\n );\n }\n\n // Check algorithm approval. v0.17.2-beta.4: the algorithm whitelist is the single\n // source of truth on the ACCOUNT (enforced in validateUserOp), not the guard.\n const accountContract = this.ethereum.getAccountContract(accountAddress);\n const isApproved = await readAlgorithmApproved(accountContract, algId);\n\n if (!isApproved) {\n errors.push(\n `Algorithm ${ALG_NAMES[algId] ?? `0x${algId.toString(16)}`} is not approved by the account`\n );\n }\n\n if (errors.length > 0) {\n this.logger.warn(`Pre-check failed for ${accountAddress}: ${errors.join(\"; \")}`);\n }\n\n return { ok: errors.length === 0, errors, tier, algId };\n }\n}\n","import {\n getContract,\n encodeFunctionData,\n type Address,\n type Hex,\n type PublicClient,\n type WalletClient,\n} from \"viem\";\n// FORCE_EXIT_ABI is a local human-readable signature array (not in @aastar/core);\n// parseAbi is required to feed it to viem's getContract / encodeFunctionData during\n// the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { encodeAbiParams } from \"../../migration/viem/abi-encoding\";\nimport type { ViemContract } from \"../providers/ethereum-provider\";\n\n// ForceExitModule ABI — minimal subset for SDK use\nconst FORCE_EXIT_ABI = [\n // ERC-7579 module lifecycle\n \"function onInstall(bytes calldata data) external\",\n \"function onUninstall(bytes calldata data) external\",\n \"function isInitialized(address smartAccount) external view returns (bool)\",\n // Proposal lifecycle\n \"function proposeForceExit(address target, uint256 value, bytes calldata data) external\",\n \"function approveForceExit(address account, bytes calldata guardianSig) external\",\n \"function executeForceExit(address account) external\",\n \"function cancelForceExit(address account) external\",\n // State readers\n \"function getPendingExit(address account) external view returns (address target, uint256 value, bytes memory data, uint256 proposedAt, uint256 approvalBitmap, address[3] memory guardians)\",\n \"function accountL2Type(address account) external view returns (uint8)\",\n // Constants\n \"function APPROVAL_THRESHOLD() external view returns (uint8)\",\n \"function MODULE_VERSION() external view returns (string)\",\n // Errors (for decoding reverts)\n \"error AlreadyApproved()\",\n \"error AlreadyProposed()\",\n \"error ForceExitCallFailed()\",\n \"error IncompatibleAccount()\",\n \"error InvalidGuardianSig()\",\n \"error NoProposal()\",\n \"error NotEnoughApprovals()\",\n \"error NotInstalled()\",\n \"error NotOwner()\",\n \"error SignerNoLongerGuardian()\",\n \"error UnsupportedL2Type()\",\n];\n\n// Parsed once at module load — fed to getContract (reads/writes) and encodeFunctionData.\nconst FORCE_EXIT_PARSED_ABI = parseAbi(FORCE_EXIT_ABI as readonly string[]);\n\nexport const L2_TYPE = {\n OPTIMISM: 1,\n ARBITRUM: 2,\n} as const;\n\nexport type L2Type = (typeof L2_TYPE)[keyof typeof L2_TYPE];\n\nexport interface PendingExit {\n target: string;\n value: bigint;\n data: string;\n proposedAt: bigint;\n approvalBitmap: bigint;\n guardians: [string, string, string];\n}\n\n/**\n * A viem client capable of backing the ForceExit contract. A `PublicClient`\n * alone enables the on-chain reads; a `WalletClient` (or the `{ public, wallet }`\n * pair) is required for the state-changing `proposeForceExit`/`approveForceExit`/\n * etc. transactions. This replaces the old `ethers.Provider | ethers.Signer`\n * argument (provider = reads, signer = reads + writes).\n */\nexport type ForceExitClient =\n | PublicClient\n | WalletClient\n | { public: PublicClient; wallet: WalletClient };\n\n/**\n * ForceExitService — typed wrappers for ForceExitModule ERC-7579 emergency L2→L1 exit.\n *\n * Flow:\n * 1. Owner installs module via account.installModule(2, forceExitModuleAddr, encodeOnInstall(L2_TYPE.OPTIMISM))\n * 2. Any party calls proposeForceExit(target, value, data) to submit a bridge-out proposal\n * 3. 2-of-3 guardians each call approveForceExit(account, guardianSig) within their window\n * 4. Anyone calls executeForceExit(account) once threshold is met — triggers L2→L1 bridge call\n *\n * The module is an ERC-7579 Executor (moduleTypeId=2) — call installModule on the account, not here.\n */\nexport class ForceExitService {\n private readonly contract: ViemContract;\n\n constructor(\n private readonly moduleAddress: string,\n client: ForceExitClient\n ) {\n this.contract = getContract({\n address: moduleAddress as Address,\n abi: FORCE_EXIT_PARSED_ABI,\n // viem inspects the client's actions at runtime to expose read/write; the\n // cast only satisfies the static union — a wallet client still yields writes.\n client: client as unknown as PublicClient,\n }) as unknown as ViemContract;\n }\n\n // ── On-chain reads ──────────────────────────────────────────────\n\n async isInitialized(smartAccount: string): Promise<boolean> {\n return (await this.contract.read.isInitialized([smartAccount as Address])) as boolean;\n }\n\n async getPendingExit(account: string): Promise<PendingExit> {\n const [target, value, data, proposedAt, approvalBitmap, guardians] =\n (await this.contract.read.getPendingExit([account as Address])) as [\n string,\n bigint,\n string,\n bigint,\n bigint,\n [string, string, string],\n ];\n return {\n target,\n value: BigInt(value),\n data,\n proposedAt: BigInt(proposedAt),\n approvalBitmap: BigInt(approvalBitmap),\n guardians,\n };\n }\n\n async getAccountL2Type(account: string): Promise<number> {\n return Number(await this.contract.read.accountL2Type([account as Address]));\n }\n\n async getApprovalThreshold(): Promise<number> {\n return Number(await this.contract.read.APPROVAL_THRESHOLD([]));\n }\n\n async getModuleVersion(): Promise<string> {\n return (await this.contract.read.MODULE_VERSION([])) as string;\n }\n\n // ── Calldata encoders (for UserOp or direct tx submission) ─────\n\n /**\n * Encode onInstall calldata for installModule() call on the smart account.\n * Must be submitted by the account owner, with moduleTypeId=2 (EXECUTOR).\n *\n * @param l2Type - L2_TYPE.OPTIMISM (1) or L2_TYPE.ARBITRUM (2)\n * @example\n * const calldata = forceExit.encodeOnInstall(L2_TYPE.OPTIMISM);\n * // account.installModule(2, forceExitModuleAddress, calldata)\n */\n encodeOnInstall(l2Type: L2Type): string {\n return encodeFunctionData({\n abi: FORCE_EXIT_PARSED_ABI,\n functionName: \"onInstall\",\n args: [encodeAbiParams([\"uint8\"], [l2Type])],\n });\n }\n\n encodeOnUninstall(): string {\n return encodeFunctionData({\n abi: FORCE_EXIT_PARSED_ABI,\n functionName: \"onUninstall\",\n args: [\"0x\"],\n });\n }\n\n /**\n * Encode calldata for proposeForceExit — the exit payload to bridge out of L2.\n * `target` is the L2→L1 bridge contract; `data` is the bridge call payload.\n */\n encodeProposeForceExit(target: string, value: bigint, data: string): string {\n return encodeFunctionData({\n abi: FORCE_EXIT_PARSED_ABI,\n functionName: \"proposeForceExit\",\n args: [target as Address, value, data as Hex],\n });\n }\n\n /**\n * Encode calldata for approveForceExit — guardian signs off on the pending proposal.\n * `guardianSig` must be an EIP-191 personal_sign over the proposal hash.\n */\n encodeApproveForceExit(account: string, guardianSig: string): string {\n return encodeFunctionData({\n abi: FORCE_EXIT_PARSED_ABI,\n functionName: \"approveForceExit\",\n args: [account as Address, guardianSig as Hex],\n });\n }\n\n encodeExecuteForceExit(account: string): string {\n return encodeFunctionData({\n abi: FORCE_EXIT_PARSED_ABI,\n functionName: \"executeForceExit\",\n args: [account as Address],\n });\n }\n\n encodeCancelForceExit(account: string): string {\n return encodeFunctionData({\n abi: FORCE_EXIT_PARSED_ABI,\n functionName: \"cancelForceExit\",\n args: [account as Address],\n });\n }\n\n // ── Convenience: send transactions (requires a WalletClient) ──────────\n\n async proposeForceExit(target: string, value: bigint, data: string): Promise<Hex> {\n return (await this.contract.write.proposeForceExit([\n target as Address,\n value,\n data as Hex,\n ])) as Hex;\n }\n\n async approveForceExit(account: string, guardianSig: string): Promise<Hex> {\n return (await this.contract.write.approveForceExit([\n account as Address,\n guardianSig as Hex,\n ])) as Hex;\n }\n\n async executeForceExit(account: string): Promise<Hex> {\n return (await this.contract.write.executeForceExit([account as Address])) as Hex;\n }\n\n async cancelForceExit(account: string): Promise<Hex> {\n return (await this.contract.write.cancelForceExit([account as Address])) as Hex;\n }\n}\n","import {\n encodeAbiParameters,\n encodeFunctionData,\n keccak256,\n zeroAddress,\n type Abi,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\n// AIRACCOUNT_ABI is a local human-readable `string[]` signature set (not available\n// in @aastar/core), so parseAbi is required to feed it to viem's encode/read calls.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { AIRACCOUNT_ABI } from \"../constants/entrypoint\";\n\n/**\n * Parsed AirAccount ABI shared by the encoders and on-chain reads. Cast to the\n * loose `Abi` type so `encodeFunctionData`/`readContract` accept dynamic\n * function names and return `unknown` (mirrors the old `ethers.Interface` /\n * `ethers.Contract` dynamic surface).\n */\nconst AIRACCOUNT_ABI_PARSED = parseAbi(AIRACCOUNT_ABI) as Abi;\n\n/**\n * RECOVERY_THRESHOLD — number of distinct guardian approvals required to recover\n * (or to cancel a recovery). The contract hard-codes `RECOVERY_THRESHOLD = 2`\n * against a maximum of 3 guardians, i.e. a 2-of-3 social-recovery scheme.\n *\n * Source of truth: `AAStarAirAccountBase.RECOVERY_THRESHOLD` (internal constant).\n */\nexport const RECOVERY_THRESHOLD = 2;\n\n/**\n * MAX_GUARDIANS — the account stores at most 3 guardians (packed slots 12-14).\n * Source: `AAStarAirAccountBase.addGuardian` (`_guardianCount >= 3` reverts).\n */\nexport const MAX_GUARDIANS = 3;\n\n/**\n * RECOVERY_TIMELOCK_SECONDS — delay between `proposeRecovery` and the earliest\n * `executeRecovery`. The contract hard-codes `RECOVERY_TIMELOCK = 2 days`\n * (172800 seconds).\n *\n * NOTE: the prose in `docs/abi/capabilities.md` says \"72h\"; the deployed\n * contract uses 2 days (48h). The on-chain constant is authoritative.\n *\n * Source of truth: `AAStarAirAccountBase.RECOVERY_TIMELOCK` (internal constant).\n */\nexport const RECOVERY_TIMELOCK_SECONDS = 2n * 24n * 60n * 60n; // 2 days\n\n/**\n * GUARDIAN_SIG_VERSION — version byte folded into every guardian-signed challenge\n * (domain-separates signatures across contract versions). Source of truth:\n * `AAStarAirAccountBase.GUARDIAN_SIG_VERSION` (== 4 since v0.20.0).\n */\nexport const GUARDIAN_SIG_VERSION = 4;\n\n/**\n * P256_GUARDIAN_SENTINEL — the address stored in a guardian slot occupied by a\n * P-256 (WebAuthn) guardian; the real secp256r1 key lives in a side mapping. For\n * a plain ECDSA guardian the slot stores the guardian's own EOA address instead.\n * Source: `AAStarAirAccountBase.P256_GUARDIAN_SENTINEL` (`address(0x7026)`).\n */\nexport const P256_GUARDIAN_SENTINEL: Address = \"0x0000000000000000000000000000000000007026\";\n\n/**\n * Decoded view of the account's `activeRecovery()` struct (RecoveryProposal).\n *\n * On-chain layout (`AAStarAgentStorageLayout.RecoveryProposal`):\n * - newOwner : proposed new owner (address(0) ⇒ no active recovery)\n * - proposedAt : block.timestamp when the recovery was proposed\n * - approvalBitmap : bit i set ⇒ guardian[i] approved (2-of-3 to execute)\n * - cancellationBitmap : bit i set ⇒ guardian[i] voted to cancel (2-of-3 to cancel)\n *\n * The remaining fields are SDK-side conveniences derived from those values.\n */\nexport interface ActiveRecovery {\n /** Proposed new owner. `0x0000…0000` means there is no active recovery. */\n newOwner: string;\n /** `block.timestamp` at which the recovery was proposed (seconds). */\n proposedAt: bigint;\n /** Bitmap of guardian approvals (bit i ⇒ guardian[i] approved). */\n approvalBitmap: bigint;\n /** Bitmap of guardian cancel votes (bit i ⇒ guardian[i] voted to cancel). */\n cancellationBitmap: bigint;\n /** Number of distinct guardian approvals (popcount of `approvalBitmap`). */\n approvalCount: number;\n /** Number of distinct guardian cancel votes (popcount of `cancellationBitmap`). */\n cancellationCount: number;\n /** Earliest timestamp at which `executeRecovery` may succeed (`proposedAt + timelock`). */\n executeAfter: bigint;\n /** True when a recovery is currently active (`newOwner != address(0)`). */\n isActive: boolean;\n}\n\n/** Count the set bits of a non-negative bigint (guardian bitmap popcount). */\nfunction popcount(value: bigint): number {\n let v = value;\n let count = 0;\n while (v > 0n) {\n count += Number(v & 1n);\n v >>= 1n;\n }\n return count;\n}\n\n/**\n * RecoveryService — typed wrappers for AirAccount's on-chain social / guardian\n * recovery (capability F28). Unlike `ForceExitService` (an ERC-7579 module),\n * these functions live directly on the account contract, so every encoded\n * calldata below is meant to be submitted **to the account address itself**\n * (via a direct tx or a UserOp).\n *\n * ## Threshold & timelock\n * 2-of-3 guardians ({@link RECOVERY_THRESHOLD} of {@link MAX_GUARDIANS}), with a\n * {@link RECOVERY_TIMELOCK_SECONDS} (2-day) delay before execution.\n *\n * ## Lifecycle & who-can-call\n * 1. `addGuardian(guardian)` — **owner only**. Registers a guardian (max 3).\n * 2. `proposeRecovery(newOwner)` — **any guardian**. Starts the timelock and\n * records the proposer's approval bit (counts as the first of 2 approvals).\n * 3. `approveRecovery()` — **another guardian**. Sets its approval bit; once\n * 2-of-3 approvals are reached the threshold is satisfied.\n * 4. `executeRecovery()` — **anyone**, but only after the timelock has elapsed\n * AND the approval threshold is met. Rotates `owner` to `newOwner`.\n * 5. `cancelRecovery()` — **guardians only** (2-of-3 votes). The owner cannot\n * cancel: a thief who stole the owner key must not be able to block a\n * legitimate recovery. Each guardian votes independently.\n * 6. `removeGuardian(index, guardianSigs)` — **owner**, but additionally\n * requires >= {@link RECOVERY_THRESHOLD} guardian signatures over the\n * removal hash (and cannot drop below 2 guardians).\n *\n * Guardian signatures are domain-separated per operation (the contract hashes a\n * per-op label such as \"REMOVE_GUARDIAN\") to prevent cross-operation replay.\n *\n * ## Re-proposing\n * A new proposal reverts with `RecoveryAlreadyActive` while one is pending. The\n * docs reference a `clearStaleRecovery()` helper, but that function is NOT\n * present in the deployed V7 ABI/contract — a stale proposal must instead be\n * cleared via guardian `cancelRecovery()` votes before re-proposing.\n */\nexport class RecoveryService {\n /**\n * @param client viem read client (was `ethers.Provider | ethers.Signer`). Only\n * on-chain reads are performed here; calldata encoders are pure and never\n * touch the client.\n */\n constructor(private readonly client: PublicClient) {}\n\n // ── Calldata encoders (submit TO the account address) ─────────────\n\n /**\n * Encode `addGuardian(guardian)` calldata. **Owner only.**\n * Registers a recovery guardian; reverts once 3 guardians are set, or if the\n * guardian is `address(0)`, the owner, or already registered.\n */\n encodeAddGuardian(guardian: string): string {\n return encodeFunctionData({\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"addGuardian\",\n args: [guardian as Address],\n });\n }\n\n /**\n * Encode `removeGuardian(index, guardianSigs)` calldata. **Owner only**, and\n * requires >= {@link RECOVERY_THRESHOLD} guardian signatures over the removal\n * hash. Cannot remove while a recovery is active, nor drop below 2 guardians.\n *\n * @param index Guardian slot to remove (0-indexed).\n * @param guardianSigs EIP-191 guardian signatures over the removal hash.\n */\n encodeRemoveGuardian(index: number, guardianSigs: string[]): string {\n return encodeFunctionData({\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"removeGuardian\",\n args: [index, guardianSigs as Hex[]],\n });\n }\n\n /**\n * Build the RAW (un-prefixed) challenge hash that each guardian must sign to\n * authorize `removeGuardian(index, ...)` / `removeGuardianWithMixedSigs(...)`.\n *\n * ## v0.20.0 breaking change (#120 final-review [HIGH], spec §6.4)\n * The signed `opData` changed from `abi.encode(nonce, guardianToRemove)` to\n * `abi.encode(nonce, index, guardianToRemove, p256X, p256Y)` — it now binds the\n * SLOT INDEX and the slot's P-256 key. Because P-256 guardians all share the\n * sentinel address, the old 2-field payload was identical for every P-256 slot,\n * so a signature collected to remove slot A could be replayed to remove slot B\n * (or survive a key rotation). The new 5-field payload affects EVERY removal,\n * including the plain ECDSA path: for an ECDSA slot `p256X`/`p256Y` are both\n * `bytes32(0)`, but the payload STRUCTURE (extra `index` + two key words) still\n * changed, so the ECDSA `removeGuardian` signing payload MUST use this encoding.\n *\n * Hash construction (matches `AAStarAirAccountBase._guardianOpHash`):\n * ```\n * opData = abi.encode(uint256 nonce, uint8 index, address guardianToRemove,\n * bytes32 p256X, bytes32 p256Y)\n * challenge = keccak256(abi.encode(uint8 GUARDIAN_SIG_VERSION, uint256 chainId,\n * address account, \"REMOVE_GUARDIAN\", bytes opData))\n * ```\n * The contract additionally applies `toEthSignedMessageHash()` before\n * `ecrecover`, so this returns the RAW inner hash and each guardian signs it via\n * `personal_sign` / `signMessage({ raw: hash })` (which adds the EIP-191 prefix).\n * Do NOT pre-apply the prefix here (mirrors `buildGuardianAcceptanceHash`).\n *\n * @param account The AirAccount address whose guardian is being removed.\n * @param chainId EVM chain id (bound into the challenge).\n * @param removalNonce Current `_guardianRemovalNonce` — there is no on-chain\n * getter (internal storage slot 15), so the caller tracks\n * it (starts at 0, increments once per successful removal).\n * @param index Guardian slot being removed (0-indexed, < guardianCount).\n * @param guardianToRemove Address stored in that slot (a P-256 slot stores\n * {@link P256_GUARDIAN_SENTINEL}; an ECDSA slot stores the EOA).\n * @param p256X Slot's P-256 x coordinate; `bytes32(0)` for an ECDSA slot (default).\n * @param p256Y Slot's P-256 y coordinate; `bytes32(0)` for an ECDSA slot (default).\n * @returns raw hex keccak256 challenge — guardians sign it with `personal_sign`.\n */\n buildRemoveGuardianHash(args: {\n account: string;\n chainId: number | bigint;\n removalNonce: bigint;\n index: number;\n guardianToRemove: string;\n p256X?: Hex;\n p256Y?: Hex;\n }): Hex {\n const ZERO32: Hex =\n \"0x0000000000000000000000000000000000000000000000000000000000000000\";\n const opData = encodeAbiParameters(\n [\n { type: \"uint256\" }, // _guardianRemovalNonce\n { type: \"uint8\" }, // index\n { type: \"address\" }, // guardianToRemove\n { type: \"bytes32\" }, // p256X (0 for ECDSA slot)\n { type: \"bytes32\" }, // p256Y (0 for ECDSA slot)\n ],\n [\n args.removalNonce,\n args.index,\n args.guardianToRemove as Address,\n args.p256X ?? ZERO32,\n args.p256Y ?? ZERO32,\n ],\n );\n return keccak256(\n encodeAbiParameters(\n [\n { type: \"uint8\" }, // GUARDIAN_SIG_VERSION\n { type: \"uint256\" }, // chainId\n { type: \"address\" }, // address(this) — the account\n { type: \"string\" }, // opLabel\n { type: \"bytes\" }, // opData\n ],\n [\n GUARDIAN_SIG_VERSION,\n BigInt(args.chainId),\n args.account as Address,\n \"REMOVE_GUARDIAN\",\n opData,\n ],\n ),\n );\n }\n\n /**\n * Encode `proposeRecovery(newOwner)` calldata. **Any guardian** may call.\n * Starts the {@link RECOVERY_TIMELOCK_SECONDS} timelock and records the\n * proposer's approval (1 of {@link RECOVERY_THRESHOLD}).\n */\n encodeProposeRecovery(newOwner: string): string {\n return encodeFunctionData({\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"proposeRecovery\",\n args: [newOwner as Address],\n });\n }\n\n /**\n * Encode `approveRecovery()` calldata. **Another guardian** approves the\n * active proposal, setting its bit in `approvalBitmap`.\n */\n encodeApproveRecovery(): string {\n return encodeFunctionData({\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"approveRecovery\",\n args: [],\n });\n }\n\n /**\n * Encode `cancelRecovery()` calldata. **Guardians only** — each call is one\n * vote; recovery is dropped once {@link RECOVERY_THRESHOLD} cancel votes are\n * reached. The owner cannot cancel.\n */\n encodeCancelRecovery(): string {\n return encodeFunctionData({\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"cancelRecovery\",\n args: [],\n });\n }\n\n /**\n * Encode `executeRecovery()` calldata. **Anyone** may call, but it only\n * succeeds once the timelock has elapsed and the approval threshold is met.\n * Rotates the account owner to the proposed `newOwner`.\n */\n encodeExecuteRecovery(): string {\n return encodeFunctionData({\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"executeRecovery\",\n args: [],\n });\n }\n\n // ── On-chain reads (against the account address) ──────────────────\n\n /**\n * Read and decode the account's `activeRecovery()` struct.\n * Returns derived `approvalCount`, `cancellationCount`, `executeAfter`, and\n * `isActive` alongside the raw fields.\n *\n * @param account The AirAccount address to query.\n */\n async getActiveRecovery(account: string): Promise<ActiveRecovery> {\n const [newOwner, proposedAt, approvalBitmap, cancellationBitmap] =\n (await this.client.readContract({\n address: account as Address,\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"activeRecovery\",\n })) as readonly [Address, bigint, bigint, bigint];\n\n const proposedAtBn = BigInt(proposedAt);\n const approvalBitmapBn = BigInt(approvalBitmap);\n const cancellationBitmapBn = BigInt(cancellationBitmap);\n\n return {\n newOwner: newOwner as string,\n proposedAt: proposedAtBn,\n approvalBitmap: approvalBitmapBn,\n cancellationBitmap: cancellationBitmapBn,\n approvalCount: popcount(approvalBitmapBn),\n cancellationCount: popcount(cancellationBitmapBn),\n executeAfter: proposedAtBn + RECOVERY_TIMELOCK_SECONDS,\n isActive: (newOwner as string).toLowerCase() !== zeroAddress,\n };\n }\n\n /**\n * Read the number of registered guardians via `guardianCount()`.\n *\n * @param account The AirAccount address to query.\n */\n async getGuardianCount(account: string): Promise<number> {\n const count = (await this.client.readContract({\n address: account as Address,\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"guardianCount\",\n })) as number | bigint;\n return Number(count);\n }\n\n /**\n * Read the full guardian address list.\n *\n * The V7 account exposes positional `guardians(uint256 i)` (3 packed slots) plus\n * `guardianCount()` — there is no single `getGuardians()` getter on the account\n * (that exists only on `AirAccountDelegate`, the EIP-7702 path). This reads slots\n * `0..guardianCount-1` and returns the non-zero guardian addresses.\n *\n * @param account The AirAccount address to query.\n */\n async getGuardians(account: string): Promise<string[]> {\n const count = Number(\n (await this.client.readContract({\n address: account as Address,\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"guardianCount\",\n })) as number | bigint\n );\n const guardians: string[] = [];\n for (let i = 0; i < count; i++) {\n const g = (await this.client.readContract({\n address: account as Address,\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"guardians\",\n args: [BigInt(i)],\n })) as string;\n if (g.toLowerCase() !== zeroAddress) guardians.push(g);\n }\n return guardians;\n }\n}\n","import { encodeFunctionData, type Abi, type Address, type Hex, type PublicClient } from \"viem\";\n// DELEGATE_ABI is a local human-readable signature array (not in @aastar/core);\n// parseAbi is required to feed it to viem encodeFunctionData / readContract during\n// the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport {\n buildAuthorizationHash as buildAuthorizationHashViem,\n verifyAuthorization as verifyAuthorizationViem,\n} from \"../../migration/viem/signatures\";\n\n// AirAccountDelegate ABI — subset for SDK use\nconst DELEGATE_ABI = [\n \"function initialize(address guardian1, bytes calldata g1Sig, address guardian2, bytes calldata g2Sig, uint256 dailyLimit) external\",\n \"function owner() external view returns (address)\",\n \"function isInitialized() external view returns (bool)\",\n \"function entryPoint() external view returns (address)\",\n \"function getGuardians() external view returns (address[3] memory)\",\n \"function getDeposit() external view returns (uint256)\",\n \"function execute(address dest, uint256 value, bytes calldata data) external\",\n \"function executeBatch(address[] calldata dest, uint256[] calldata value, bytes[] calldata data) external\",\n \"function validateUserOp((address sender, uint256 nonce, bytes initCode, bytes callData, bytes32 accountGasLimits, uint256 preVerificationGas, bytes32 gasFees, bytes paymasterAndData, bytes signature) calldata userOp, bytes32 userOpHash, uint256 missingFunds) external returns (uint256)\",\n \"function initiateRescue(address rescueTo) external\",\n \"function approveRescue() external\",\n \"function cancelRescue() external\",\n \"function executeRescue() external\",\n \"function addDeposit() external payable\",\n \"function withdrawDepositTo(address to, uint256 amount) external\",\n \"error AlreadyInitialized()\",\n \"error NotInitialized()\",\n \"error InvalidAddress()\",\n \"error InvalidGuardianSignature()\",\n];\n\n// Sepolia AirAccountDelegate singleton deployment (unchanged since beta.1)\nexport const AIR_ACCOUNT_DELEGATE_ADDRESS = \"0x8603AAF6C3f07fdae810B323c95a198D796EC52E\";\n\nexport interface DelegateInitParams {\n /** Guardian 1 address */\n guardian1: string;\n /** EIP-712 acceptance signature from guardian 1 */\n guardian1Sig: string;\n /** Guardian 2 address */\n guardian2: string;\n /** EIP-712 acceptance signature from guardian 2 */\n guardian2Sig: string;\n /** Daily ETH spend limit in wei */\n dailyLimit: bigint;\n}\n\nexport interface EIP7702Authorization {\n /** Chain ID (e.g. 11155111 for Sepolia) */\n chainId: number;\n /** The delegation target — AirAccountDelegate singleton address */\n address: string;\n /** EOA nonce at time of signing */\n nonce: bigint;\n /** Signature over the EIP-7702 authorization hash (65 bytes, R||S||V) */\n signature: string;\n}\n\n/**\n * EIP7702DelegateService — Path A: SDK payload construction for AirAccountDelegate.\n *\n * Path A applies when the integrator controls the private key (KMS, server-side signer,\n * embedded wallet). The EOA signs a SET_CODE authorization offline; the integrator's relay\n * submits a Type-4 transaction to activate the delegation.\n *\n * This service does NOT submit transactions — it produces signed payloads for relay.\n *\n * Deployed address: AirAccountDelegate singleton at AIR_ACCOUNT_DELEGATE_ADDRESS (Sepolia).\n * The user's EOA address does NOT change — only its bytecode pointer changes to 0xef0100||addr.\n *\n * Usage:\n * 1. Build SET_CODE authorization payload (call signer.signAuthorization externally — viem)\n * 2. Build initialize() calldata for the first UserOp / direct tx\n * 3. Submit both via integrator's relay\n */\nexport class EIP7702DelegateService {\n /** Parsed ABI (loose viem `Abi` shape) used for encoding calldata and on-chain reads. */\n private readonly abi: Abi;\n /** Optional viem read client (was `ethers.Provider | ethers.Signer`). Required only for on-chain reads. */\n private readonly client?: PublicClient;\n\n constructor(\n private readonly delegateAddress: string = AIR_ACCOUNT_DELEGATE_ADDRESS,\n client?: PublicClient\n ) {\n this.abi = parseAbi(DELEGATE_ABI);\n this.client = client;\n }\n\n // ── Calldata encoders ─────────────────────────────────────────\n\n /**\n * Encode initialize() calldata for the first post-delegation UserOp.\n * Must be the callData of a UserOp sent immediately after the SET_CODE delegation activates.\n * Guardian acceptance sigs follow the same EIP-712 scheme as AirAccountV7 createAccount.\n */\n encodeInitialize(params: DelegateInitParams): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"initialize\",\n args: [\n params.guardian1,\n params.guardian1Sig,\n params.guardian2,\n params.guardian2Sig,\n params.dailyLimit,\n ],\n });\n }\n\n encodeExecute(dest: string, value: bigint, data: string): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"execute\",\n args: [dest, value, data],\n });\n }\n\n encodeExecuteBatch(\n dests: string[],\n values: bigint[],\n datas: string[]\n ): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"executeBatch\",\n args: [dests, values, datas],\n });\n }\n\n // ── EIP-7702 authorization hash construction ──────────────────\n\n /**\n * Compute the EIP-7702 SET_CODE authorization hash that the EOA must sign.\n *\n * Hash = keccak256(0x05 || RLP([chainId, address, nonce]))\n *\n * This is the hash the private key signs to delegate code execution to\n * AirAccountDelegate. Use this hash with your KMS sign-hash endpoint or\n * local viem account.\n *\n * @param chainId - Target chain ID (11155111 for Sepolia)\n * @param nonce - EOA's current transaction nonce\n * @returns 32-byte hash (0x-prefixed) ready for signing\n */\n buildAuthorizationHash(chainId: number, nonce: bigint): string {\n return buildAuthorizationHashViem(chainId, nonce, this.delegateAddress as Address);\n }\n\n /**\n * Build the full EIP-7702 authorization object for relay submission.\n * The caller must sign `buildAuthorizationHash()` externally and pass the result here.\n *\n * @param chainId - Target chain ID\n * @param nonce - EOA's current nonce\n * @param signature - 65-byte ECDSA signature (R||S||V) over the authorization hash\n */\n buildAuthorization(\n chainId: number,\n nonce: bigint,\n signature: string\n ): EIP7702Authorization {\n return {\n chainId,\n address: this.delegateAddress,\n nonce,\n signature,\n };\n }\n\n /**\n * Verify that a signature is a valid EIP-7702 authorization for the given EOA address.\n * Recovers the signer from the authorization hash and checks it matches `eoa`.\n *\n * NOTE: now async — viem's `recoverAddress` is asynchronous (ethers' was sync).\n */\n verifyAuthorization(\n eoa: string,\n chainId: number,\n nonce: bigint,\n signature: string\n ): Promise<boolean> {\n return verifyAuthorizationViem(\n eoa as Address,\n chainId,\n nonce,\n signature as Hex,\n this.delegateAddress as Address\n );\n }\n\n // ── On-chain reads (requires provider) ───────────────────────\n\n async isInitialized(eoa: string): Promise<boolean> {\n if (!this.client) throw new Error(\"EIP7702DelegateService: provider required for on-chain reads\");\n return (await this.client.readContract({\n address: eoa as Address,\n abi: this.abi,\n functionName: \"isInitialized\",\n })) as boolean;\n }\n\n async getOwner(eoa: string): Promise<string> {\n if (!this.client) throw new Error(\"EIP7702DelegateService: provider required for on-chain reads\");\n return (await this.client.readContract({\n address: eoa as Address,\n abi: this.abi,\n functionName: \"owner\",\n })) as string;\n }\n\n async getGuardians(eoa: string): Promise<[string, string, string]> {\n if (!this.client) throw new Error(\"EIP7702DelegateService: provider required for on-chain reads\");\n return (await this.client.readContract({\n address: eoa as Address,\n abi: this.abi,\n functionName: \"getGuardians\",\n })) as [string, string, string];\n }\n}\n","import { encodeFunctionData, type Hex, type PublicClient } from \"viem\";\n// The weighted-signature ABI below is a local human-readable `string[]` signature set\n// (not available in @aastar/core), so parseAbi is required to feed it to viem's\n// encodeFunctionData/readContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\n\n// AAStarAirAccount weighted-signature governance ABI — minimal subset for SDK use.\n// These functions live on the ACCOUNT itself (algId 0x07 / AirAccountExtension),\n// NOT on a separate ERC-7579 module. The WeightConfig tuple field order is\n// authoritative and matches packages/core/src/abis/AAStarAirAccountV7.json exactly.\nconst WEIGHTED_SIGNATURE_ABI = [\n // Direct owner set (first-time / strengthening only)\n \"function setWeightConfig((uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold) config) external\",\n // Guardian-governed change flow (required for any weakening)\n \"function proposeWeightChange((uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold) proposed) external\",\n \"function approveWeightChange() external\",\n \"function cancelWeightChange() external\",\n \"function executeWeightChange() external\",\n // State readers\n \"function weightConfig() external view returns (uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold)\",\n \"function pendingWeightChange() external view returns ((uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold) proposed, uint256 proposedAt, uint256 approvalBitmap)\",\n // Errors (for decoding reverts)\n \"error InsecureWeightConfig()\",\n \"error WeakeningRequiresProposal()\",\n \"error WeightChangePending()\",\n \"error NoWeightChangeProposal()\",\n \"error WeightChangeAlreadyApproved()\",\n \"error WeightChangeNotApproved()\",\n \"error WeightChangeTimelockNotExpired()\",\n];\n\n// Parsed (loosely-typed `Abi`) form for viem encodeFunctionData/readContract.\nconst WEIGHTED_SIGNATURE_ABI_PARSED = parseAbi(WEIGHTED_SIGNATURE_ABI as readonly string[]);\n\n/** Timelock that must elapse after a proposal before executeWeightChange() succeeds (WEIGHT_CHANGE_TIMELOCK = 2 days). */\nexport const WEIGHT_CHANGE_TIMELOCK_SECONDS = 2 * 24 * 60 * 60;\n/** Guardian approvals required to execute a pending weight change (WEIGHT_CHANGE_THRESHOLD = 2-of-3). */\nexport const WEIGHT_CHANGE_THRESHOLD = 2;\n/** A proposal expires this long after it is proposed; approvals/execution after expiry revert (WEIGHT_CHANGE_EXPIRY = 30 days). */\nexport const WEIGHT_CHANGE_EXPIRY_SECONDS = 30 * 24 * 60 * 60;\n\n/**\n * WeightConfig — the weighted multi-signature policy for an AAStarAirAccount (algId 0x07).\n *\n * Each signer type / guardian contributes its weight; a transaction is authorized when the\n * summed weight of present signatures meets the relevant tier threshold. tier1 is the base\n * (required, non-zero) threshold; tier2/tier3 gate higher-value operations and, when set,\n * must be monotonically non-decreasing (tier1 <= tier2 <= tier3).\n *\n * Field order MUST match the on-chain struct exactly (see AAStarAirAccountV7.json):\n * passkeyWeight, ecdsaWeight, blsWeight, guardian0Weight, guardian1Weight, guardian2Weight,\n * _padding, tier1Threshold, tier2Threshold, tier3Threshold.\n */\nexport interface WeightConfig {\n /** Weight granted by a valid passkey (P256/WebAuthn) signature. */\n passkeyWeight: number;\n /** Weight granted by a valid ECDSA (secp256k1 owner) signature. */\n ecdsaWeight: number;\n /** Weight granted by a valid BLS signature. */\n blsWeight: number;\n /** Weight granted by guardian slot 0. */\n guardian0Weight: number;\n /** Weight granted by guardian slot 1. */\n guardian1Weight: number;\n /** Weight granted by guardian slot 2. */\n guardian2Weight: number;\n /** Reserved padding byte (storage packing); keep 0. */\n _padding: number;\n /** Base threshold; must be non-zero and strictly greater than every individual weight. */\n tier1Threshold: number;\n /** Tier-2 threshold (0 = disabled); when set must be >= tier1Threshold. */\n tier2Threshold: number;\n /** Tier-3 threshold (0 = disabled); when set requires tier2 set and must be >= tier2Threshold. */\n tier3Threshold: number;\n}\n\n/** A pending weight-change proposal awaiting guardian approval + timelock. */\nexport interface PendingWeightChange {\n /** The proposed new WeightConfig. */\n proposed: WeightConfig;\n /** Unix timestamp when the proposal was created; 0 means no active proposal. */\n proposedAt: bigint;\n /** Bitmap of guardian indices that have approved (bit i set => guardian i approved). */\n approvalBitmap: bigint;\n}\n\n// Canonical field order of the WeightConfig tuple as encoded on-chain.\nconst WEIGHT_CONFIG_FIELDS = [\n \"passkeyWeight\",\n \"ecdsaWeight\",\n \"blsWeight\",\n \"guardian0Weight\",\n \"guardian1Weight\",\n \"guardian2Weight\",\n \"_padding\",\n \"tier1Threshold\",\n \"tier2Threshold\",\n \"tier3Threshold\",\n] as const;\n\nfunction toConfigTuple(config: WeightConfig): number[] {\n return WEIGHT_CONFIG_FIELDS.map((f) => config[f]);\n}\n\nfunction fromConfigResult(result: unknown): WeightConfig {\n const r = result as Record<string, unknown> & unknown[];\n // viem decodes a named-component tuple into an object (named access) while a\n // list of separate outputs decodes into an array (positional access); support both.\n const pick = (name: string, idx: number): number =>\n Number((r[name] ?? r[idx]) as number | bigint);\n return {\n passkeyWeight: pick(\"passkeyWeight\", 0),\n ecdsaWeight: pick(\"ecdsaWeight\", 1),\n blsWeight: pick(\"blsWeight\", 2),\n guardian0Weight: pick(\"guardian0Weight\", 3),\n guardian1Weight: pick(\"guardian1Weight\", 4),\n guardian2Weight: pick(\"guardian2Weight\", 5),\n _padding: pick(\"_padding\", 6),\n tier1Threshold: pick(\"tier1Threshold\", 7),\n tier2Threshold: pick(\"tier2Threshold\", 8),\n tier3Threshold: pick(\"tier3Threshold\", 9),\n };\n}\n\n/**\n * WeightedSignatureService — typed wrappers for AAStarAirAccount weighted-signature\n * governance (algId 0x07).\n *\n * Governance model:\n * - setWeightConfig(config): OWNER only. Used for the first-time config and for\n * *strengthening* changes (no individual weight or tier threshold decreased).\n * Reverts WeakeningRequiresProposal-equivalent path is enforced by the contract:\n * a weakening passed here reverts; route weakenings through proposeWeightChange.\n * Also reverts if a proposal is already pending (WeightChangePending).\n * - proposeWeightChange(config): OWNER only. Required when the new config *weakens*\n * security (lowers any weight or threshold). Opens a guardian-approved proposal.\n * - approveWeightChange(): GUARDIAN only (any of the 3 guardian slots). Each guardian\n * may approve once; approvals are tracked in approvalBitmap.\n * - executeWeightChange(): ANYONE, but only succeeds once BOTH conditions hold:\n * (1) approvals >= WEIGHT_CHANGE_THRESHOLD (2-of-3 guardians), and\n * (2) WEIGHT_CHANGE_TIMELOCK (2 days) has elapsed since proposedAt.\n * A proposal also expires after WEIGHT_CHANGE_EXPIRY (30 days).\n * - cancelWeightChange(): OWNER or any GUARDIAN may cancel a pending proposal.\n *\n * Unlike ForceExitService (an ERC-7579 module), these calls target the ACCOUNT itself.\n * Construct with the account address; encode* methods return calldata for a UserOp or\n * direct tx, and reads use the contract directly.\n */\nexport class WeightedSignatureService {\n private readonly address: `0x${string}`;\n\n constructor(\n private readonly accountAddress: string,\n private readonly client: PublicClient\n ) {\n this.address = accountAddress as `0x${string}`;\n }\n\n // ── On-chain reads ──────────────────────────────────────────────\n\n /** Read the account's current active WeightConfig. */\n async getWeightConfig(): Promise<WeightConfig> {\n const result = await this.client.readContract({\n address: this.address,\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"weightConfig\",\n });\n return fromConfigResult(result);\n }\n\n /**\n * Read the pending weight-change proposal. When `proposedAt === 0n` there is no\n * active proposal (the returned `proposed` config will be all zeros).\n */\n async getPendingWeightChange(): Promise<PendingWeightChange> {\n const [proposed, proposedAt, approvalBitmap] = (await this.client.readContract({\n address: this.address,\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"pendingWeightChange\",\n })) as [unknown, bigint, bigint];\n return {\n proposed: fromConfigResult(proposed),\n proposedAt: BigInt(proposedAt),\n approvalBitmap: BigInt(approvalBitmap),\n };\n }\n\n // ── Calldata encoders (for UserOp or direct tx submission) ─────\n\n /**\n * Encode setWeightConfig calldata. OWNER only; for first-time setup or strengthening.\n * Weakening an existing config must go through encodeProposeWeightChange instead.\n */\n encodeSetWeightConfig(config: WeightConfig): Hex {\n return encodeFunctionData({\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"setWeightConfig\",\n args: [toConfigTuple(config)],\n });\n }\n\n /**\n * Encode proposeWeightChange calldata. OWNER only; opens a guardian-governed proposal\n * (required for any weakening). Subject to 2-of-3 approval + 2-day timelock before execute.\n */\n encodeProposeWeightChange(config: WeightConfig): Hex {\n return encodeFunctionData({\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"proposeWeightChange\",\n args: [toConfigTuple(config)],\n });\n }\n\n /** Encode approveWeightChange calldata. GUARDIAN only; each guardian may approve once. */\n encodeApproveWeightChange(): Hex {\n return encodeFunctionData({\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"approveWeightChange\",\n });\n }\n\n /** Encode cancelWeightChange calldata. OWNER or any GUARDIAN may cancel a pending proposal. */\n encodeCancelWeightChange(): Hex {\n return encodeFunctionData({\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"cancelWeightChange\",\n });\n }\n\n /**\n * Encode executeWeightChange calldata. Callable by anyone, but only succeeds once the\n * threshold (2-of-3) and timelock (2 days) are both satisfied and the proposal has not expired.\n */\n encodeExecuteWeightChange(): Hex {\n return encodeFunctionData({\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"executeWeightChange\",\n });\n }\n}\n","import { encodeFunctionData, type Abi, type Address, type Hex, type PublicClient } from \"viem\";\n// The AgentRegistry / EntryPoint / AirAccount ABIs are local human-readable `string[]`\n// signatures (not available in @aastar/core), so parseAbi is required to feed them to\n// viem's encodeFunctionData / readContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { AIRACCOUNT_FACTORY_ABI, AIRACCOUNT_ABI } from \"../constants/entrypoint\";\n\n// Minimal ABI covering the AAStar AgentRegistry contract (SuperPaymaster-facing).\n// Mirrors packages/core/src/abis/AgentRegistry.json. The registry maps agent wallets\n// to their human owner and exposes paginated enumeration of an owner's agents.\nconst AGENT_REGISTRY_ABI = [\n // ── Writes ──\n \"function registerAgent(address agentWallet, bytes agentWalletSig) external\",\n \"function revokeAgent(address agentWallet) external\",\n \"function deregisterAgent(address agentWallet) external\",\n // ── Reads ──\n \"function isRegisteredAgent(address agentWallet) external view returns (bool)\",\n \"function isValidAccount(address account) external view returns (bool)\",\n \"function getHumanOwner(address agentWallet) external view returns (address)\",\n \"function getAgentCount(address owner) external view returns (uint256)\",\n \"function getAgentByIndex(address owner, uint256 index) external view returns (address)\",\n \"function getAgents(address humanOwner) external view returns (address[])\",\n \"function getAgentsPage(address owner, uint256 start, uint256 count) external view returns (address[] page)\",\n \"function agentWalletOwner(address agentWallet) external view returns (address)\",\n \"function ownerAgents(address owner, uint256 index) external view returns (address)\",\n \"function balanceOf(address humanOwner) external view returns (uint256)\",\n // ── Errors (for decoding reverts) ──\n \"error AgentAlreadyRegistered()\",\n \"error CallerNotAirAccount()\",\n \"error InvalidAddress()\",\n \"error InvalidAgentSignature()\",\n \"error NotAgentOwner()\",\n \"error SelfRegistrationForbidden()\",\n];\n\n// Parsed viem ABIs (loosely typed as `Abi`) used for both calldata encoding and reads.\n// Widening to `Abi` mirrors the hub's ViemContract approach: function names are indexed\n// dynamically and read return values are cast at the call site.\nconst REGISTRY_ABI: Abi = parseAbi(AGENT_REGISTRY_ABI as readonly string[]);\nconst FACTORY_ABI: Abi = parseAbi(AIRACCOUNT_FACTORY_ABI as readonly string[]);\nconst ACCOUNT_ABI: Abi = parseAbi(AIRACCOUNT_ABI as readonly string[]);\n\n// ─── Parameter / result types ───────────────────────────────────────────────\n\nexport interface CreateAgentAccountParams {\n /** The agent's own signing key (EOA controlled by the agent runtime / KMS). */\n agentKey: string;\n /** ERC-8004-style agent identifier (bytes32) binding this account to an off-chain identity. */\n agentId: string;\n /** The human guardian (guardian2) co-owning the agent account for recovery. */\n guardian2: string;\n /** Guardian2's acceptance signature over the creation hash (EIP-191). */\n guardian2Sig: string;\n /** The agent key's acceptance signature over the creation hash (EIP-191). */\n agentKeySig: string;\n /** Unix timestamp (uint48) after which the signatures are rejected. */\n deadline: bigint | number;\n /** Daily transfer limit in wei (on-chain guard enforcement; V7 requires > 0). */\n dailyLimit: bigint;\n}\n\n// ─── Service ────────────────────────────────────────────────────────────────\n\n/**\n * AgentRegistryService — typed wrappers for the AAStar AgentRegistry contract plus the\n * AAStarAirAccountFactoryV7 agent-account creation helpers.\n *\n * **Two contracts, two responsibilities:**\n *\n * 1. AgentRegistry (constructor `registryAddress`) — the canonical map of agent wallet →\n * human owner used by SuperPaymaster to authorise gasless sponsorship. The factory calls\n * `markValid`/registers the agent at deployment; humans manage the binding afterwards via\n * `registerAgent` / `revokeAgent` / `deregisterAgent`.\n *\n * 2. AAStarAirAccountFactoryV7 — deploys an agent-owned AirAccount. `encodeCreateAgentAccount`\n * targets the factory (NOT the registry); `getAgentAccountAddress` predicts the CREATE2\n * address before deployment.\n *\n * All `encode*` methods return ABI-encoded calldata ready for a UserOp (gasless) or a direct\n * owner transaction. Read methods require a viem `PublicClient`.\n */\nexport class AgentRegistryService {\n private readonly client: PublicClient;\n\n /**\n * @param client viem PublicClient for on-chain reads (e.g. `ethereum.getProvider()`).\n * @param registryAddress deployed AgentRegistry contract address.\n */\n constructor(\n client: PublicClient,\n private readonly registryAddress: string\n ) {\n this.client = client;\n }\n\n // ── Composed register/revoke-via-account scenario encoders ──────────────────\n // registerAgent/revokeAgent require msg.sender == the agent account, so they are delivered\n // through the account's execute(registry, 0, calldata). These return the FULL execute\n // calldata to submit TO the agent account (owner-signed) — the scenario-level entry point.\n\n /** Encode `account.execute(registry, 0, registerAgent(agentWallet, agentWalletSig))`. */\n encodeRegisterAgentViaAccount(agentWallet: string, agentWalletSig: string): string {\n return encodeFunctionData({\n abi: ACCOUNT_ABI,\n functionName: \"execute\",\n args: [\n this.registryAddress as Address,\n 0n,\n this.encodeRegisterAgent(agentWallet, agentWalletSig) as Hex,\n ],\n });\n }\n\n /** Encode `account.execute(registry, 0, revokeAgent(agentWallet))`. */\n encodeRevokeAgentViaAccount(agentWallet: string): string {\n return encodeFunctionData({\n abi: ACCOUNT_ABI,\n functionName: \"execute\",\n args: [this.registryAddress as Address, 0n, this.encodeRevokeAgent(agentWallet) as Hex],\n });\n }\n\n // ── AgentRegistry calldata encoders ─────────────────────────────────────────\n\n /**\n * Encode calldata for `registerAgent(agentWallet, agentWalletSig)`.\n *\n * Binds `agentWallet` to the caller (the human owner). `agentWalletSig` must be the agent\n * wallet's EIP-191 signature proving control of the key. Reverts with\n * `SelfRegistrationForbidden` if the caller registers itself, or `AgentAlreadyRegistered`\n * if the wallet is already bound.\n */\n encodeRegisterAgent(agentWallet: string, agentWalletSig: string): string {\n return encodeFunctionData({\n abi: REGISTRY_ABI,\n functionName: \"registerAgent\",\n args: [agentWallet as Address, agentWalletSig as Hex],\n });\n }\n\n /**\n * Encode calldata for `revokeAgent(agentWallet)`.\n *\n * Owner-initiated revocation of a previously registered agent wallet. Caller must be the\n * agent's human owner (else `NotAgentOwner`).\n */\n encodeRevokeAgent(agentWallet: string): string {\n return encodeFunctionData({\n abi: REGISTRY_ABI,\n functionName: \"revokeAgent\",\n args: [agentWallet as Address],\n });\n }\n\n /**\n * Encode calldata for `deregisterAgent(agentWallet)`.\n *\n * Removes the agent wallet from the registry (full deregistration, distinct from the\n * lighter-weight `revokeAgent`). Caller must be the agent's human owner.\n */\n encodeDeregisterAgent(agentWallet: string): string {\n return encodeFunctionData({\n abi: REGISTRY_ABI,\n functionName: \"deregisterAgent\",\n args: [agentWallet as Address],\n });\n }\n\n // ── AgentRegistry on-chain reads ────────────────────────────────────────────\n\n /** Whether `agentWallet` is currently registered in the registry. */\n async isRegisteredAgent(agentWallet: string): Promise<boolean> {\n return (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"isRegisteredAgent\",\n args: [agentWallet as Address],\n })) as boolean;\n }\n\n /** Whether `account` has been marked valid (e.g. an AirAccount minted by the bound factory). */\n async isValidAccount(account: string): Promise<boolean> {\n return (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"isValidAccount\",\n args: [account as Address],\n })) as boolean;\n }\n\n /** The human owner bound to `agentWallet` (ZeroAddress if unregistered). */\n async getHumanOwner(agentWallet: string): Promise<string> {\n return (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"getHumanOwner\",\n args: [agentWallet as Address],\n })) as string;\n }\n\n /** Number of agents registered under `owner`. */\n async getAgentCount(owner: string): Promise<bigint> {\n return BigInt(\n (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"getAgentCount\",\n args: [owner as Address],\n })) as bigint\n );\n }\n\n /** The agent wallet at `index` in `owner`'s agent list. */\n async getAgentByIndex(owner: string, index: bigint | number): Promise<string> {\n return (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"getAgentByIndex\",\n args: [owner as Address, BigInt(index)],\n })) as string;\n }\n\n /** Full list of agent wallets registered under `humanOwner`. */\n async getAgents(humanOwner: string): Promise<string[]> {\n const result = (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"getAgents\",\n args: [humanOwner as Address],\n })) as readonly string[];\n // Normalise the (readonly) viem result into a plain mutable array.\n return Array.from(result);\n }\n\n /**\n * Paginated slice of `owner`'s agent wallets: `count` entries starting at `start`.\n * The contract clamps `count` to the remaining length, so the returned array may be shorter.\n */\n async getAgentsPage(\n owner: string,\n start: bigint | number,\n count: bigint | number\n ): Promise<string[]> {\n const result = (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"getAgentsPage\",\n args: [owner as Address, BigInt(start), BigInt(count)],\n })) as readonly string[];\n return Array.from(result);\n }\n\n /** Raw `agentWalletOwner` mapping read (agentWallet → owner). */\n async agentWalletOwner(agentWallet: string): Promise<string> {\n return (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"agentWalletOwner\",\n args: [agentWallet as Address],\n })) as string;\n }\n\n /** Raw `ownerAgents` array read (owner, index → agentWallet). */\n async ownerAgents(owner: string, index: bigint | number): Promise<string> {\n return (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"ownerAgents\",\n args: [owner as Address, BigInt(index)],\n })) as string;\n }\n\n // ── Factory agent-account helpers (AAStarAirAccountFactoryV7) ───────────────\n\n /**\n * Encode calldata for the factory's `createAgentAccount(...)`.\n *\n * Targets the AAStarAirAccountFactoryV7, NOT the AgentRegistry. The factory deploys the agent\n * AirAccount and registers it in the bound AgentRegistry in one transaction. Submit this\n * calldata to the factory address (direct tx or via a relayer).\n */\n encodeCreateAgentAccount(params: CreateAgentAccountParams): string {\n return encodeFunctionData({\n abi: FACTORY_ABI,\n functionName: \"createAgentAccount\",\n args: [\n params.agentKey as Address,\n params.agentId as Hex,\n params.guardian2 as Address,\n params.guardian2Sig as Hex,\n params.agentKeySig as Hex,\n BigInt(params.deadline),\n params.dailyLimit,\n ],\n });\n }\n\n /**\n * Encode calldata for the factory's `setAgentRegistry(_agentRegistry)` (factory-admin only).\n */\n encodeSetAgentRegistry(agentRegistry: string): string {\n return encodeFunctionData({\n abi: FACTORY_ABI,\n functionName: \"setAgentRegistry\",\n args: [agentRegistry as Address],\n });\n }\n\n /**\n * Predict the CREATE2 address of an agent account via the factory's `getAgentAddress(...)`.\n *\n * @param factoryAddress AAStarAirAccountFactoryV7 address.\n * @param humanOwner the human guardian/owner co-owning the agent account.\n * @param agentKey the agent's signing key.\n * @param agentId the bytes32 agent identifier.\n */\n async getAgentAccountAddress(\n factoryAddress: string,\n humanOwner: string,\n agentKey: string,\n agentId: string\n ): Promise<string> {\n return (await this.client.readContract({\n address: factoryAddress as Address,\n abi: FACTORY_ABI,\n functionName: \"getAgentAddress\",\n args: [humanOwner as Address, agentKey as Address, agentId as Hex],\n })) as string;\n }\n\n /** Read the AgentRegistry address currently bound to the factory. */\n async getFactoryAgentRegistry(factoryAddress: string): Promise<string> {\n return (await this.client.readContract({\n address: factoryAddress as Address,\n abi: FACTORY_ABI,\n functionName: \"agentRegistry\",\n args: [],\n })) as string;\n }\n}\n","import { encodeFunctionData, getContract, type Abi, type PublicClient } from \"viem\";\n// parseAbi is required: the ERC-8004 ABI is a local human-readable string[] of function\n// signatures (not available in @aastar/core), and viem needs a parsed Abi to encode/read.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\n\n// Minimal ABI covering only the ERC-8004 agent functions on AAStarAirAccountV7.\n// These are routed via fallback→delegatecall to AirAccountExtension on the deployed account.\nconst ERC8004_ABI = [\n \"function setAgentWallet(uint256 agentId, address agentWallet, address agentRegistry, bytes agentWalletSig) external\",\n \"function mintAgentIdentity(address identityRegistry, string agentURI) external returns (uint256 agentId)\",\n \"function bindERC8004AgentWallet(address identityRegistry, uint256 agentId, address agentWallet, uint256 deadline, bytes signature) external\",\n \"function submitAgentReputation(address reputationRegistry, uint256 agentId, int128 value, uint8 valueDecimals, string tag1, string tag2, string endpoint, string feedbackURI, bytes32 feedbackHash) external\",\n \"function queryAgentReputation(address reputationRegistry, uint256 agentId, address[] clientAddresses, string tag1, string tag2) external view returns (uint64 count, int128 summaryValue, uint8 summaryDecimals)\",\n \"function agentExtension() external view returns (address)\",\n];\n\n// ─── Official ERC-8004 \"Trustless Agents\" registry addresses ─────────────────\n// Deployed at deterministic CREATE2 addresses (SAFE Singleton Factory).\n// Source: ../airaccount-contract/src/config/ERC8004Addresses.sol\n\nexport const ERC8004_ADDRESSES = {\n mainnet: {\n identityRegistry: \"0x8004A169FB4a3325136EB29fA0ceB6D2e539a432\",\n reputationRegistry: \"0x8004BAa17C55a88189AE136b182e5fdA19dE9b63\",\n validationRegistry: \"0x8004Cc8439f36fd5F9F049D9fF86523Df6dAAB58\",\n },\n testnet: {\n identityRegistry: \"0x8004A818BFB912233c491871b3d84c89A494BD9e\",\n reputationRegistry: \"0x8004B663056A597Dffe9eCcC1965A193B7388713\",\n validationRegistry: \"0x8004Cb1BF31DAf7788923b405b754f57acEB4272\",\n },\n} as const;\n\n// Mainnet chain IDs that have official ERC-8004 deployments.\nconst MAINNET_CHAIN_IDS = new Set([1, 10, 137, 8453, 42161, 43114, 56, 534352, 100, 42220, 59144, 5000, 167000, 360]);\nconst TESTNET_CHAIN_IDS = new Set([11155111, 11155420, 84532, 421614, 80002]);\n\nexport function erc8004AddressesForChain(chainId: number): (typeof ERC8004_ADDRESSES)[\"mainnet\"] | (typeof ERC8004_ADDRESSES)[\"testnet\"] {\n if (MAINNET_CHAIN_IDS.has(chainId)) return ERC8004_ADDRESSES.mainnet;\n if (TESTNET_CHAIN_IDS.has(chainId)) return ERC8004_ADDRESSES.testnet;\n throw new Error(`ERC-8004: unsupported chain ${chainId}`);\n}\n\n// ─── Parameter types ──────────────────────────────────────────────────────────\n\nexport interface SetAgentWalletParams {\n agentId: bigint;\n agentWallet: string;\n /** AAStar AgentRegistry contract address (SuperPaymaster-facing, NOT the official ERC-8004 registry) */\n agentRegistry: string;\n /** Signature from the agent wallet proving ownership */\n agentWalletSig: string;\n}\n\nexport interface MintAgentIdentityParams {\n /** Must be the official ERC-8004 identity registry for this chain */\n identityRegistry: string;\n /** Agent metadata URI (ERC-721 tokenURI) */\n agentURI: string;\n}\n\nexport interface BindERC8004AgentWalletParams {\n /** Must be the official ERC-8004 identity registry for this chain */\n identityRegistry: string;\n agentId: bigint;\n agentWallet: string;\n /** Unix timestamp — signature becomes invalid after this deadline */\n deadline: bigint;\n /** Signature authorising the wallet binding, signed by the identity registry's expected signer */\n signature: string;\n}\n\nexport interface SubmitAgentReputationParams {\n /** Must be the official ERC-8004 reputation registry for this chain */\n reputationRegistry: string;\n agentId: bigint;\n value: bigint;\n valueDecimals: number;\n tag1: string;\n tag2: string;\n endpoint: string;\n feedbackURI: string;\n feedbackHash: string; // bytes32 hex\n}\n\nexport interface QueryAgentReputationParams {\n /** Must be the official ERC-8004 reputation registry for this chain */\n reputationRegistry: string;\n agentId: bigint;\n clientAddresses: string[];\n tag1: string;\n tag2: string;\n}\n\nexport interface AgentReputationSummary {\n count: bigint;\n summaryValue: bigint;\n summaryDecimals: number;\n}\n\n// ─── Service ──────────────────────────────────────────────────────────────────\n\n/**\n * ERC8004Service — TypeScript wrappers for AirAccount's ERC-8004 \"Trustless Agents\" functions.\n *\n * **Two distinct registration paths:**\n *\n * 1. `encodeSetAgentWallet` — AAStar/SuperPaymaster path.\n * Registers the agent wallet in the AAStar AgentRegistry contract. Use this when you want\n * SuperPaymaster to recognise the agent for gasless sponsorship. The `agentRegistry` argument\n * is the deployed AgentRegistry address, NOT the official ERC-8004 IdentityRegistry.\n *\n * 2. `encodeMintAgentIdentity` + `encodeBindERC8004AgentWallet` — official ERC-8004 path.\n * Mints an ERC-721 identity NFT in the official ERC-8004 IdentityRegistry and binds an\n * execution wallet to it. The registry address MUST be from `erc8004AddressesForChain()`.\n * These calls revert on-chain if the wrong registry address is supplied.\n *\n * All `encode*` methods return ABI-encoded calldata ready to be submitted via UserOp (gasless)\n * or a direct owner transaction. The calldata targets the AirAccount address — the account's\n * fallback delegates to AirAccountExtension for these selectors.\n */\nexport class ERC8004Service {\n private readonly abi: Abi;\n private readonly provider?: PublicClient;\n\n constructor(provider?: PublicClient) {\n this.abi = parseAbi(ERC8004_ABI);\n this.provider = provider;\n }\n\n /**\n * Build a read-only viem contract bound to the account address. The ABI is loaded from\n * human-readable signatures via `parseAbi` (loose `Abi`), so `read` methods are indexed by\n * name and return `unknown` — cast at the call site. Mirrors the dynamic surface that\n * `ethers.Contract` previously exposed. Caller must ensure `this.provider` is set.\n */\n private contractAt(accountAddress: string): {\n read: Record<string, (args: readonly unknown[]) => Promise<unknown>>;\n } {\n return getContract({\n address: accountAddress as `0x${string}`,\n abi: this.abi,\n client: this.provider as PublicClient,\n }) as unknown as { read: Record<string, (args: readonly unknown[]) => Promise<unknown>> };\n }\n\n // ── AAStar AgentRegistry path ─────────────────────────────────────────────\n\n /**\n * Encode calldata for `setAgentWallet`.\n *\n * Registers `agentWallet` in the AAStar AgentRegistry (SuperPaymaster-facing). This is the\n * correct path when the goal is SuperPaymaster gasless sponsorship for the agent.\n *\n * **Not** a call to the official ERC-8004 IdentityRegistry. Use `encodeMintAgentIdentity`\n * + `encodeBindERC8004AgentWallet` for the ERC-8004 standard path.\n *\n * Callable: owner EOA direct tx OR via UserOp (gasless).\n */\n encodeSetAgentWallet(params: SetAgentWalletParams): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"setAgentWallet\",\n args: [params.agentId, params.agentWallet, params.agentRegistry, params.agentWalletSig],\n });\n }\n\n // ── Official ERC-8004 identity path ──────────────────────────────────────\n\n /**\n * Encode calldata for `mintAgentIdentity`.\n *\n * Mints an ERC-721 agent identity NFT in the official ERC-8004 IdentityRegistry and returns\n * the new `agentId` (decoded from the tx receipt). The `identityRegistry` must be\n * `erc8004AddressesForChain(chainId).identityRegistry` — the contract reverts otherwise.\n *\n * Callable: owner EOA direct tx OR via UserOp (gasless).\n */\n encodeMintAgentIdentity(params: MintAgentIdentityParams): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"mintAgentIdentity\",\n args: [params.identityRegistry, params.agentURI],\n });\n }\n\n /**\n * Encode calldata for `bindERC8004AgentWallet`.\n *\n * Binds an execution wallet to an existing ERC-8004 agent identity NFT. Requires a\n * deadline-bounded signature from the expected signer (see the IdentityRegistry contract).\n * The `identityRegistry` must be the official chain-specific address.\n *\n * Callable: owner EOA direct tx OR via UserOp (gasless).\n */\n encodeBindERC8004AgentWallet(params: BindERC8004AgentWalletParams): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"bindERC8004AgentWallet\",\n args: [\n params.identityRegistry,\n params.agentId,\n params.agentWallet,\n params.deadline,\n params.signature,\n ],\n });\n }\n\n // ── Reputation ────────────────────────────────────────────────────────────\n\n /**\n * Encode calldata for `submitAgentReputation`.\n *\n * Submits a reputation feedback entry to the official ERC-8004 ReputationRegistry.\n * `reputationRegistry` must be `erc8004AddressesForChain(chainId).reputationRegistry`.\n *\n * Callable: owner EOA direct tx OR via UserOp (gasless).\n */\n encodeSubmitAgentReputation(params: SubmitAgentReputationParams): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"submitAgentReputation\",\n args: [\n params.reputationRegistry,\n params.agentId,\n params.value,\n params.valueDecimals,\n params.tag1,\n params.tag2,\n params.endpoint,\n params.feedbackURI,\n params.feedbackHash,\n ],\n });\n }\n\n /**\n * Query aggregated reputation for an agent from the official ERC-8004 ReputationRegistry.\n * Returns `null` when no provider was supplied at construction.\n */\n async queryAgentReputation(\n accountAddress: string,\n params: QueryAgentReputationParams,\n ): Promise<AgentReputationSummary> {\n if (!this.provider) throw new Error(\"ERC8004Service: provider required for on-chain reads\");\n const contract = this.contractAt(accountAddress);\n const [count, summaryValue, summaryDecimals] = (await contract.read.queryAgentReputation([\n params.reputationRegistry,\n params.agentId,\n params.clientAddresses,\n params.tag1,\n params.tag2,\n ])) as readonly [bigint, bigint, number];\n return { count: BigInt(count), summaryValue: BigInt(summaryValue), summaryDecimals: Number(summaryDecimals) };\n }\n\n /**\n * Encode calldata for `queryAgentReputation` (for static-call or eth_call without a signer).\n */\n encodeQueryAgentReputation(params: QueryAgentReputationParams): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"queryAgentReputation\",\n args: [\n params.reputationRegistry,\n params.agentId,\n params.clientAddresses,\n params.tag1,\n params.tag2,\n ],\n });\n }\n\n /**\n * Read the agentExtension implementation address from a deployed AirAccount.\n */\n async getAgentExtensionAddress(accountAddress: string): Promise<string> {\n if (!this.provider) throw new Error(\"ERC8004Service: provider required for on-chain reads\");\n const contract = this.contractAt(accountAddress);\n const extension = await contract.read.agentExtension([]);\n return extension as string;\n }\n}\n","import axios, { AxiosInstance, AxiosRequestConfig } from \"axios\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\n\n/**\n * Canonical production KMS endpoint (IMX93 TEE behind Cloudflare Tunnel).\n * v0.20.0 (Beta2) — see AirAccount/kms/CHANGELOG.md.\n */\nexport const DEFAULT_KMS_ENDPOINT = \"https://kms.aastar.io\";\n\nexport interface KmsHttpClientOptions {\n kmsEndpoint?: string;\n kmsEnabled?: boolean;\n kmsApiKey?: string;\n logger?: ILogger;\n}\n\n/**\n * Shared low-level HTTP transport for all KMS service classes.\n *\n * Centralises axios setup (baseURL, x-api-key), the `enabled` gate, and the three\n * request flavours the KMS uses:\n * - plain JSON → `post` / `get`\n * - AWS-KMS framed → `amzPost` (adds x-amz-target + x-amz-json-1.1 content type)\n * - agent/session JWT → `postWithBearer` (Authorization: Bearer <jwt>)\n *\n * KmsManager and the composed services (agent / session / payment / monitor) all share\n * one instance so they reuse the same connection config and auth headers.\n */\nexport class KmsHttpClient {\n readonly endpoint: string;\n readonly enabled: boolean;\n readonly logger: ILogger;\n private readonly apiKey?: string;\n private readonly http: AxiosInstance;\n\n constructor(options: KmsHttpClientOptions) {\n this.endpoint = options.kmsEndpoint ?? DEFAULT_KMS_ENDPOINT;\n this.enabled = options.kmsEnabled === true;\n this.apiKey = options.kmsApiKey;\n this.logger = options.logger ?? new ConsoleLogger(\"[KmsHttpClient]\");\n\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (this.apiKey) {\n headers[\"x-api-key\"] = this.apiKey;\n }\n\n this.http = axios.create({ baseURL: this.endpoint, headers });\n }\n\n /** Throw if KMS is not enabled — every operation must call this first. */\n ensureEnabled(): void {\n if (!this.enabled) {\n throw new Error(\"KMS service is not enabled\");\n }\n }\n\n /**\n * Plain JSON POST. The axios `config` arg is only forwarded when defined, so a\n * config-less call results in `http.post(path, body)` (2 args) — preserving the\n * exact call shape the existing unit tests assert against.\n */\n async post<T>(path: string, body?: unknown, config?: AxiosRequestConfig): Promise<T> {\n const response = config === undefined\n ? await this.http.post(path, body)\n : await this.http.post(path, body, config);\n return response.data as T;\n }\n\n /** Plain JSON GET. */\n async get<T>(path: string, config?: AxiosRequestConfig): Promise<T> {\n const response = config === undefined\n ? await this.http.get(path)\n : await this.http.get(path, config);\n return response.data as T;\n }\n\n /** POST with AWS-KMS framing (x-amz-target header) — required for wallet/signing ops. */\n async amzPost<T>(path: string, target: string, body: unknown): Promise<T> {\n return this.post<T>(path, body, {\n headers: {\n \"Content-Type\": \"application/x-amz-json-1.1\",\n \"x-amz-target\": target,\n },\n });\n }\n\n /** POST authenticated with a TEE-issued agent/session JWT (Authorization: Bearer). */\n async postWithBearer<T>(path: string, body: unknown, jwt: string): Promise<T> {\n return this.post<T>(path, body, {\n headers: { authorization: `Bearer ${jwt}` },\n });\n }\n}\n","/**\n * Internal module for NIST P256, P384, P521 curves.\n * Do not use for now.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';\nimport { createHasher, type H2CHasher } from './abstract/hash-to-curve.ts';\nimport { Field } from './abstract/modular.ts';\nimport { createORPF, type OPRF } from './abstract/oprf.ts';\nimport {\n ecdsa,\n mapToCurveSimpleSWU,\n weierstrass,\n type ECDSA,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\n\n// p = 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n - 1n\n// a = Fp256.create(BigInt('-3'));\nconst p256_CURVE: WeierstrassOpts<bigint> = /* @__PURE__ */ (() => ({\n p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n h: BigInt(1),\n a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),\n b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n}))();\n\n// p = 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n\nconst p384_CURVE: WeierstrassOpts<bigint> = /* @__PURE__ */ (() => ({\n p: BigInt(\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'\n ),\n n: BigInt(\n '0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'\n ),\n h: BigInt(1),\n a: BigInt(\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc'\n ),\n b: BigInt(\n '0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'\n ),\n Gx: BigInt(\n '0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'\n ),\n Gy: BigInt(\n '0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'\n ),\n}))();\n\n// p = 2n**521n - 1n\nconst p521_CURVE: WeierstrassOpts<bigint> = /* @__PURE__ */ (() => ({\n p: BigInt(\n '0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n ),\n n: BigInt(\n '0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'\n ),\n h: BigInt(1),\n a: BigInt(\n '0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'\n ),\n b: BigInt(\n '0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'\n ),\n Gx: BigInt(\n '0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'\n ),\n Gy: BigInt(\n '0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'\n ),\n}))();\n\ntype SwuOpts = {\n A: bigint;\n B: bigint;\n Z: bigint;\n};\n\nfunction createSWU(Point: WeierstrassPointCons<bigint>, opts: SwuOpts) {\n const map = mapToCurveSimpleSWU(Point.Fp, opts);\n return (scalars: bigint[]) => map(scalars[0]);\n}\n\n// NIST P256\nconst p256_Point = /* @__PURE__ */ weierstrass(p256_CURVE);\n/**\n * NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods.\n * Hashes inputs with sha256 by default.\n *\n * @example\n * ```js\n * import { p256 } from '@noble/curves/nist.js';\n * const { secretKey, publicKey } = p256.keygen();\n * // const publicKey = p256.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256.sign(msg, secretKey);\n * const isValid = p256.verify(sig, msg, publicKey);\n * // const sigKeccak = p256.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const p256: ECDSA = /* @__PURE__ */ ecdsa(p256_Point, sha256);\n/** Hashing / encoding to p256 points / field. RFC 9380 methods. */\nexport const p256_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() => {\n return createHasher(\n p256_Point,\n createSWU(p256_Point, {\n A: p256_CURVE.a,\n B: p256_CURVE.b,\n Z: p256_Point.Fp.create(BigInt('-10')),\n }),\n {\n DST: 'P256_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n p: p256_CURVE.p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n );\n})();\n/** p256 OPRF, defined in RFC 9497. */\nexport const p256_oprf: OPRF = /* @__PURE__ */ (() =>\n createORPF({\n name: 'P256-SHA256',\n Point: p256_Point,\n hash: sha256,\n hashToGroup: p256_hasher.hashToCurve,\n hashToScalar: p256_hasher.hashToScalar,\n }))();\n\n// NIST P384\nconst p384_Point = /* @__PURE__ */ weierstrass(p384_CURVE);\n/** NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. Hashes inputs with sha384 by default. */\nexport const p384: ECDSA = /* @__PURE__ */ ecdsa(p384_Point, sha384);\n/** Hashing / encoding to p384 points / field. RFC 9380 methods. */\nexport const p384_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() => {\n return createHasher(\n p384_Point,\n createSWU(p384_Point, {\n A: p384_CURVE.a,\n B: p384_CURVE.b,\n Z: p384_Point.Fp.create(BigInt('-12')),\n }),\n {\n DST: 'P384_XMD:SHA-384_SSWU_RO_',\n encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n p: p384_CURVE.p,\n m: 1,\n k: 192,\n expand: 'xmd',\n hash: sha384,\n }\n );\n})();\n/** p384 OPRF, defined in RFC 9497. */\nexport const p384_oprf: OPRF = /* @__PURE__ */ (() =>\n createORPF({\n name: 'P384-SHA384',\n Point: p384_Point,\n hash: sha384,\n hashToGroup: p384_hasher.hashToCurve,\n hashToScalar: p384_hasher.hashToScalar,\n }))();\n\n// NIST P521\nconst Fn521 = /* @__PURE__ */ (() => Field(p521_CURVE.n, { allowedLengths: [65, 66] }))();\nconst p521_Point = /* @__PURE__ */ weierstrass(p521_CURVE, { Fn: Fn521 });\n/** NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. Hashes inputs with sha512 by default. */\nexport const p521: ECDSA = /* @__PURE__ */ ecdsa(p521_Point, sha512);\n/** Hashing / encoding to p521 points / field. RFC 9380 methods. */\nexport const p521_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() => {\n return createHasher(\n p521_Point,\n createSWU(p521_Point, {\n A: p521_CURVE.a,\n B: p521_CURVE.b,\n Z: p521_Point.Fp.create(BigInt('-4')),\n }),\n {\n DST: 'P521_XMD:SHA-512_SSWU_RO_',\n encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n p: p521_CURVE.p,\n m: 1,\n k: 256,\n expand: 'xmd',\n hash: sha512,\n }\n );\n})();\n/** p521 OPRF, defined in RFC 9497. */\nexport const p521_oprf: OPRF = /* @__PURE__ */ (() =>\n createORPF({\n name: 'P521-SHA512',\n Point: p521_Point,\n hash: sha512,\n hashToGroup: p521_hasher.hashToCurve,\n hashToScalar: p521_hasher.hashToScalar, // produces L=98 just like in RFC\n }))();\n","import { createHash } from \"node:crypto\";\nimport { p256 } from \"@noble/curves/nist.js\";\nimport { KmsHttpClient } from \"./kms-http-client\";\nimport { WebAuthnAssertion } from \"./kms-signer\";\n\n// ─────────────────────────────────────────────────────────────────────────\n// WebAuthn challenge-binding ceremony (AirAccount KMS #49 / Beta3)\n//\n// The KMS now issues a one-time challenge (nonce) from a `begin` endpoint and\n// requires that nonce to be embedded in the WebAuthn `clientDataJSON` of the\n// assertion submitted to the signing endpoints. This binds each signature to a\n// fresh server-issued challenge → replay protection.\n//\n// Transition vs. strict mode (KMS-side `ENFORCE_TA_CHALLENGE`):\n// - transition (current): requests WITH clientDataJSON get strict nonce\n// validation; requests WITHOUT it fall back to legacy ECDSA-only.\n// - strict (pre-mainnet flip): requests WITHOUT clientDataJSON are REJECTED.\n// This module always produces the clientDataJSON-bound assertion, so it is\n// correct under both modes.\n//\n// Wire format mirrors the authoritative reference ceremony:\n// AirAccount/kms/test/run-full-e2e.sh (ceremony / ceremony_grant)\n// AirAccount/kms/test/p256_helper.py (make_ceremony_assertion)\n// ─────────────────────────────────────────────────────────────────────────\n\n/**\n * RP id the TA verifies against. The TA hardcodes\n * `EXPECTED_RP_ID_HASH = SHA-256(\"aastar.io\")` (AirAccount PR#44 / Issue #39);\n * any other rpId makes the TA reject the assertion with \"rpId hash mismatch\".\n */\nexport const DEFAULT_RP_ID = \"aastar.io\";\n\n/** Origin embedded in clientDataJSON — must be the RP origin the TA expects. */\nexport const DEFAULT_ORIGIN = \"https://aastar.io\";\n\n/**\n * Placeholder credential id (base64url of \"test-credential\") matching the\n * reference ceremony fixtures. Production callers SHOULD pass the credential id\n * returned by CompleteRegistration for the registered passkey.\n */\nexport const DEFAULT_CREDENTIAL_ID = \"dGVzdC1jcmVkZW50aWFs\";\n\n// ── base64url (no padding) — the WebAuthn wire encoding ───────────────────\n\nexport function base64UrlEncode(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString(\"base64url\");\n}\n\nexport function base64UrlDecode(value: string): Uint8Array {\n return new Uint8Array(Buffer.from(value, \"base64url\"));\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n if (clean.length % 2 !== 0) {\n throw new Error(\"hexToBytes: odd-length hex string\");\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\n// ── Types ─────────────────────────────────────────────────────────────────\n\n/**\n * WebAuthn AuthenticationResponseJSON (the subset the KMS verifies). This is the\n * value placed in `WebAuthnAssertion.Credential`.\n */\nexport interface WebAuthnAuthenticationCredential {\n id: string;\n rawId: string;\n type: \"public-key\";\n response: {\n clientDataJSON: string; // base64url(JSON embedding the TA challenge)\n authenticatorData: string; // base64url(rpIdHash || flags || signCount)\n signature: string; // base64url(DER ECDSA P-256 / ES256)\n userHandle?: string;\n };\n clientExtensionResults?: Record<string, unknown>;\n}\n\n/**\n * Pluggable passkey signer. The ceremony helper builds clientDataJSON +\n * authenticatorData and computes the WebAuthn message\n * (authenticatorData || SHA-256(clientDataJSON)); this signer turns that message\n * into an ES256 (ECDSA P-256 over SHA-256) DER signature.\n *\n * Browser callers back this with the platform authenticator; server/test callers\n * use {@link P256PasskeySigner}.\n */\nexport interface PasskeyCeremonySigner {\n /** base64url credential id registered with the KMS for this passkey. */\n readonly credentialId: string;\n /**\n * Sign the WebAuthn message (authenticatorData || SHA-256(clientDataJSON)).\n * MUST return a DER-encoded ES256 signature (ECDSA P-256 with SHA-256 applied\n * to the message), matching the WebAuthn wire format.\n */\n sign(message: Uint8Array): Uint8Array | Promise<Uint8Array>;\n}\n\n/**\n * Server/test {@link PasskeyCeremonySigner} backed by a raw P-256 private key\n * (the passkey bound to the KMS key). Mirrors `p256_helper.py`'s\n * `make_ceremony_assertion`: ES256 DER signature over the WebAuthn message.\n */\nexport class P256PasskeySigner implements PasskeyCeremonySigner {\n readonly credentialId: string;\n private readonly privateKey: Uint8Array;\n\n /**\n * @param privateKey raw 32-byte P-256 scalar (Uint8Array or hex, 0x optional).\n * @param credentialId base64url credential id (defaults to the reference fixture).\n */\n constructor(privateKey: Uint8Array | string, credentialId: string = DEFAULT_CREDENTIAL_ID) {\n this.privateKey = typeof privateKey === \"string\" ? hexToBytes(privateKey) : privateKey;\n this.credentialId = credentialId;\n }\n\n /**\n * Uncompressed (0x04…, 65-byte) P-256 public key hex. Register this with the\n * KMS via CreateKey `PasskeyPublicKey` (or ChangePasskey) so the TA can verify\n * assertions produced by this signer.\n */\n get publicKeyHex(): string {\n return \"0x\" + Buffer.from(p256.getPublicKey(this.privateKey, false)).toString(\"hex\");\n }\n\n sign(message: Uint8Array): Uint8Array {\n // prehash:true → noble applies SHA-256 to `message` (= ES256), DER output.\n return p256.sign(message, this.privateKey, { prehash: true, format: \"der\" });\n }\n}\n\n// ── Builders ────────────────────────────────────────────────────────────\n\n/**\n * Build the clientDataJSON bytes embedding the TA-issued one-time challenge.\n *\n * Compact JSON (no whitespace) with field order `type, challenge, origin`,\n * mirroring the reference ceremony. The KMS parses this and asserts the\n * `challenge` field equals the stored nonce before verifying the signature over\n * (authenticatorData || SHA-256(clientDataJSON)).\n */\nexport function buildClientDataJSON(challenge: string, origin: string = DEFAULT_ORIGIN): Uint8Array {\n const json = JSON.stringify({ type: \"webauthn.get\", challenge, origin });\n return new TextEncoder().encode(json);\n}\n\n/**\n * Build authenticatorData = rpIdHash(32) || flags(1) || signCount(4, big-endian).\n * flags = 0x05 (UP | UV). `signCount` must strictly increase across ceremonies\n * for the same wallet (anti-clone check); callers performing multiple sequential\n * signs should pass an incrementing value.\n */\nexport function buildAuthenticatorData(rpId: string = DEFAULT_RP_ID, signCount: number = 1): Uint8Array {\n const rpIdHash = createHash(\"sha256\").update(rpId).digest();\n const out = new Uint8Array(37);\n out.set(rpIdHash, 0);\n out[32] = 0x05; // UP | UV\n new DataView(out.buffer).setUint32(33, signCount >>> 0, false);\n return out;\n}\n\nexport interface BuildCredentialOptions {\n /** The base64url challenge returned by the begin endpoint. */\n challenge: string;\n signer: PasskeyCeremonySigner;\n rpId?: string;\n origin?: string;\n signCount?: number;\n}\n\n/**\n * Build a complete WebAuthn AuthenticationResponseJSON for a dynamic TA\n * challenge: construct clientDataJSON (embedding the challenge) + authenticatorData,\n * then sign (authenticatorData || SHA-256(clientDataJSON)).\n */\nexport async function buildAuthenticationCredential(\n opts: BuildCredentialOptions\n): Promise<WebAuthnAuthenticationCredential> {\n const origin = opts.origin ?? DEFAULT_ORIGIN;\n const rpId = opts.rpId ?? DEFAULT_RP_ID;\n const signCount = opts.signCount ?? 1;\n\n const clientDataJSON = buildClientDataJSON(opts.challenge, origin);\n const authenticatorData = buildAuthenticatorData(rpId, signCount);\n const clientDataHash = createHash(\"sha256\").update(clientDataJSON).digest();\n\n // WebAuthn message: authenticatorData || SHA-256(clientDataJSON).\n const message = new Uint8Array(authenticatorData.length + clientDataHash.length);\n message.set(authenticatorData, 0);\n message.set(clientDataHash, authenticatorData.length);\n\n const signature = await opts.signer.sign(message);\n\n return {\n id: opts.signer.credentialId,\n rawId: opts.signer.credentialId,\n type: \"public-key\",\n response: {\n clientDataJSON: base64UrlEncode(clientDataJSON),\n authenticatorData: base64UrlEncode(authenticatorData),\n signature: base64UrlEncode(signature),\n },\n };\n}\n\n// ── Orchestration: begin → embed → assert ─────────────────────────────────\n\n/** Minimal shape returned by BeginAuthentication / begin-grant-session-auth. */\nexport interface BeginCeremonyResponse {\n ChallengeId: string;\n Options: { challenge: string };\n}\n\nexport interface RunCeremonyOptions {\n signer: PasskeyCeremonySigner;\n rpId?: string;\n origin?: string;\n signCount?: number;\n}\n\n/**\n * Run a full WebAuthn challenge-binding ceremony (AirAccount #49):\n * 1. fetch a one-time TA challenge from the `begin` endpoint,\n * 2. embed it in clientDataJSON,\n * 3. build + sign the assertion,\n * 4. return `{ ChallengeId, Credential }` for the KMS `WebAuthn` /\n * `webAuthnAssertion` field.\n *\n * `begin` is injected so the same helper serves both the generic\n * (purpose=\"authentication\") and grant-session (purpose=\"grant-session\")\n * challenge endpoints.\n */\nexport async function runWebAuthnCeremony(\n begin: () => Promise<BeginCeremonyResponse>,\n options: RunCeremonyOptions\n): Promise<WebAuthnAssertion> {\n const begun = await begin();\n const challenge = begun?.Options?.challenge;\n if (!begun?.ChallengeId || !challenge) {\n throw new Error(\n \"WebAuthn ceremony: begin endpoint did not return a ChallengeId + Options.challenge\"\n );\n }\n const credential = await buildAuthenticationCredential({\n challenge,\n signer: options.signer,\n rpId: options.rpId,\n origin: options.origin,\n signCount: options.signCount,\n });\n return { ChallengeId: begun.ChallengeId, Credential: credential };\n}\n\n// ── Begin-endpoint fetchers (shared by KmsManager + the agent/session services) ──\n\n/** Fetch a generic authentication challenge (purpose=\"authentication\"). */\nexport function beginAuthenticationChallenge(\n http: KmsHttpClient,\n keyId: string\n): Promise<BeginCeremonyResponse> {\n return http.post<BeginCeremonyResponse>(\"/BeginAuthentication\", { KeyId: keyId });\n}\n\n/** Fetch a grant-session challenge (purpose=\"grant-session\"). */\nexport function beginGrantSessionChallenge(\n http: KmsHttpClient,\n keyId: string\n): Promise<BeginCeremonyResponse> {\n return http.get<BeginCeremonyResponse>(\"/kms/begin-grant-session-auth\", {\n params: { keyId },\n });\n}\n\n/**\n * Convenience: run a generic authentication ceremony over an {@link KmsHttpClient}.\n * Covers DeriveAddress / Sign / SignHash / SignTypedData / agent-key /\n * p256-session signing paths.\n */\nexport function runAuthenticationCeremony(\n http: KmsHttpClient,\n keyId: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n): Promise<WebAuthnAssertion> {\n return runWebAuthnCeremony(() => beginAuthenticationChallenge(http, keyId), {\n signer,\n ...options,\n });\n}\n\n/**\n * Convenience: run a grant-session ceremony over an {@link KmsHttpClient}.\n * Required by sign-grant-session / sign-p256-grant-session, which reject the\n * generic 'authentication' challenge for cross-op replay safety.\n */\nexport function runGrantSessionCeremony(\n http: KmsHttpClient,\n keyId: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n): Promise<WebAuthnAssertion> {\n return runWebAuthnCeremony(() => beginGrantSessionChallenge(http, keyId), {\n signer,\n ...options,\n });\n}\n","import { hashMessage } from \"../../migration/viem/signatures\";\nimport { ILogger } from \"../interfaces/logger\";\nimport { KmsHttpClient } from \"./kms-http-client\";\nimport {\n PasskeyCeremonySigner,\n RunCeremonyOptions,\n runAuthenticationCeremony,\n runGrantSessionCeremony,\n} from \"./webauthn-ceremony\";\n\n// ── Legacy Passkey Assertion (reusable for BLS dual-signing) ─────\n\nexport interface LegacyPasskeyAssertion {\n AuthenticatorData: string; // \"0x...\"\n ClientDataHash: string; // \"0x...\"\n Signature: string; // \"0x...\"\n}\n\n// ── WebAuthn Assertion (v0.19.0+, one-time use) ──────────────────\n\nexport interface WebAuthnAssertion {\n // PascalCase to match the KMS wire format: the server struct uses\n // #[serde(rename = \"ChallengeId\")] / #[serde(rename = \"Credential\")].\n ChallengeId: string;\n Credential: unknown; // AuthenticationResponseJSON from @simplewebauthn/browser\n}\n\n// ── CreateKey ────────────────────────────────────────────────────\n\nexport interface KmsCreateKeyRequest {\n Description: string;\n KeyUsage?: string;\n KeySpec?: string;\n Origin?: string;\n PasskeyPublicKey: string; // P-256 public key hex (required for new KMS)\n}\n\nexport interface KmsCreateKeyResponse {\n KeyMetadata: {\n KeyId: string;\n Arn: string;\n CreationDate: string;\n Enabled: boolean;\n Description: string;\n KeyUsage: string;\n KeySpec: string;\n Origin: string;\n Address?: string;\n };\n Mnemonic: string;\n Address?: string;\n Status?: string; // \"deriving\" — address is derived asynchronously\n}\n\n// ── SignHash ─────────────────────────────────────────────────────\n\nexport interface KmsSignHashResponse {\n Signature: string;\n}\n\n// ── WebAuthn Registration ────────────────────────────────────────\n\nexport interface KmsBeginRegistrationRequest {\n Description?: string;\n UserName?: string;\n UserDisplayName?: string;\n}\n\nexport interface KmsBeginRegistrationResponse {\n ChallengeId: string;\n Options: PublicKeyCredentialCreationOptions;\n}\n\nexport interface KmsCompleteRegistrationRequest {\n ChallengeId: string;\n Credential: unknown; // RegistrationResponseJSON from @simplewebauthn/browser\n Description?: string;\n}\n\nexport interface KmsCompleteRegistrationResponse {\n KeyId: string;\n CredentialId: string;\n Status: string;\n}\n\n// ── WebAuthn Authentication ──────────────────────────────────────\n\nexport interface KmsBeginAuthenticationRequest {\n Address?: string;\n KeyId?: string;\n}\n\nexport interface KmsBeginAuthenticationResponse {\n ChallengeId: string;\n Options: PublicKeyCredentialRequestOptions;\n}\n\n// ── Sign Typed Data (v0.20.0) ────────────────────────────────────\n// The KMS hashes the typed data host-side, so the full EIP-712 structure is sent\n// (NOT pre-computed domainSeparator/structHash — that was the pre-v0.19 contract).\n\nexport interface KmsEip712Domain {\n name?: string;\n version?: string;\n chainId?: number;\n verifyingContract?: string;\n}\n\n/** One entry in a `types` definition: a struct name and its ordered fields. */\nexport interface KmsEip712TypeDef {\n name: string; // e.g. \"Mail\", \"EIP712Domain\"\n fields: Array<{ name: string; type: string }>;\n}\n\n/** One field value for the primary type's message. */\nexport interface KmsEip712FieldValue {\n name: string;\n value: unknown;\n}\n\nexport interface KmsSignTypedDataRequest {\n keyId: string;\n hdPath?: string; // defaults to m/44'/60'/0'/0/0 server-side\n domain: KmsEip712Domain;\n primaryType: string;\n types: KmsEip712TypeDef[];\n message: KmsEip712FieldValue[];\n /** Required unless a Bearer agent JWT is supplied. Legacy passkeyAssertion is rejected. */\n webAuthnAssertion?: WebAuthnAssertion;\n}\n\nexport interface KmsSignTypedDataResponse {\n keyId: string;\n signature: string; // 65-byte hex (R||S||V)\n}\n\n// ── Grant Session Signing (v0.19.0+) ────────────────────────────\n\nexport interface KmsBeginGrantSessionAuthRequest {\n keyId: string;\n}\n\nexport interface KmsBeginGrantSessionAuthResponse {\n // PascalCase to match the KMS AuthenticationOptionsResponse wire format\n // (#[serde(rename = \"ChallengeId\" / \"Options\")]).\n ChallengeId: string;\n Options: PublicKeyCredentialRequestOptions;\n}\n\nexport interface KmsSignGrantSessionRequest {\n keyId: string;\n hdPath?: string;\n chainId: number;\n verifyingContract: string;\n account: string;\n sessionKey: string;\n expiry: number;\n contractScope: string; // server type is String (scope mode marker)\n selectorScope: string; // bytes4 hex — server type is String\n velocityLimit: number;\n velocityWindow: number;\n callTargets: string[];\n selectorAllowlist: string[];\n nonce: number;\n webAuthnAssertion: WebAuthnAssertion;\n}\n\nexport interface KmsSignGrantSessionResponse {\n keyId: string;\n signature: string; // 65-byte hex (R||S||V, V=27/28)\n}\n\nexport interface KmsSignP256GrantSessionRequest {\n keyId: string;\n hdPath?: string;\n chainId: number;\n verifyingContract: string;\n account: string;\n keyX: string; // 32-byte hex P256 public key X coordinate\n keyY: string; // 32-byte hex P256 public key Y coordinate\n expiry: number;\n contractScope: string; // server type is String (scope mode marker)\n selectorScope: string; // bytes4 hex — server type is String\n velocityLimit: number;\n velocityWindow: number;\n callTargets: string[];\n selectorAllowlist: string[];\n nonce: number;\n webAuthnAssertion: WebAuthnAssertion;\n}\n\n// ── Key Status ───────────────────────────────────────────────────\n\nexport interface KmsKeyStatusResponse {\n KeyId: string;\n Status: \"creating\" | \"deriving\" | \"ready\" | \"error\";\n Address?: string;\n PublicKey?: string;\n DerivationPath?: string;\n Error?: string;\n}\n\n// ── Describe Key ─────────────────────────────────────────────────\n\nexport interface KmsDescribeKeyResponse {\n KeyMetadata: {\n KeyId: string;\n Address?: string;\n PublicKey?: string;\n DerivationPath?: string;\n PasskeyPublicKey?: string;\n Arn?: string;\n CreationDate?: string;\n Enabled?: boolean;\n Description?: string;\n KeyUsage?: string;\n KeySpec?: string;\n Origin?: string;\n };\n}\n\n// ── EthereumTransaction (for POST /Sign) ─────────────────────────\n\nexport interface KmsEthereumTransaction {\n chainId: number;\n nonce: number;\n to: string;\n value: string; // uint256 (decimal or 0x…)\n gasPrice: string;\n gas: number;\n data: string;\n}\n\n// ── Sign (message or EIP-155 transaction) ────────────────────────\n\nexport interface KmsSignRequest {\n KeyId?: string;\n Address?: string;\n DerivationPath?: string;\n /** Provide exactly one of Message or Transaction. */\n Message?: string; // hex\n Transaction?: KmsEthereumTransaction;\n SigningAlgorithm?: string;\n WebAuthn?: WebAuthnAssertion;\n Passkey?: LegacyPasskeyAssertion;\n}\n\nexport interface KmsSignResponse {\n Signature: string;\n TransactionHash?: string;\n}\n\n// ── GetPublicKey ─────────────────────────────────────────────────\n\nexport interface KmsGetPublicKeyResponse {\n KeyId: string;\n PublicKey: string;\n Address?: string;\n KeyUsage?: string;\n KeySpec?: string;\n}\n\n// ── DeriveAddress ────────────────────────────────────────────────\n\nexport interface KmsDeriveAddressResponse {\n Address: string;\n PublicKey?: string;\n}\n\n// ── ListKeys ─────────────────────────────────────────────────────\n\nexport interface KmsListKeysResponse {\n Keys: Array<{ KeyId: string; KeyArn?: string }>;\n Truncated?: boolean;\n NextMarker?: string;\n}\n\n// ── DeleteKey ────────────────────────────────────────────────────\n\nexport interface KmsDeleteKeyResponse {\n KeyId: string;\n DeletionDate?: string;\n}\n\n// ── ChangePasskey ────────────────────────────────────────────────\n\nexport interface KmsChangePasskeyResponse {\n KeyId: string;\n Changed: boolean;\n}\n\n// ── UnfreezeKey ──────────────────────────────────────────────────\n\nexport interface KmsUnfreezeKeyResponse {\n KeyId: string;\n // \"active\" once unfrozen (or already active); mirrors the KMS LifecycleStatus enum.\n LifecycleStatus: string;\n}\n\n/**\n * KMS service for remote key management with WebAuthn/Passkey integration.\n *\n * Targets the AAStar TEE KMS (v0.20.0, kms.aastar.io). WebAuthn registration /\n * authentication ceremonies are handled by the KMS directly; signing operations\n * require a Passkey assertion (Legacy hex) or a one-time WebAuthn ceremony.\n *\n * Wraps a shared {@link KmsHttpClient}; the composed services (agent / session /\n * payment / monitor) reuse the same client via {@link KmsManager.httpClient}.\n */\nexport class KmsManager {\n private readonly client: KmsHttpClient;\n readonly logger: ILogger;\n\n constructor(options: {\n kmsEndpoint?: string;\n kmsEnabled?: boolean;\n kmsApiKey?: string;\n logger?: ILogger;\n }) {\n this.client = new KmsHttpClient(options);\n this.logger = this.client.logger;\n }\n\n isKmsEnabled(): boolean {\n return this.client.enabled;\n }\n\n /** Shared HTTP transport — pass to KmsAgentService / KmsSessionService / etc. */\n get httpClient(): KmsHttpClient {\n return this.client;\n }\n\n private ensureEnabled(): void {\n this.client.ensureEnabled();\n }\n\n /** POST with x-amz-target header (required for wallet/signing operations). */\n private async amzPost<T>(path: string, target: string, body: unknown): Promise<T> {\n return this.client.amzPost<T>(path, target, body);\n }\n\n // ── Key Management ──────────────────────────────────────────────\n\n async createKey(description: string, passkeyPublicKey: string): Promise<KmsCreateKeyResponse> {\n this.ensureEnabled();\n\n return this.amzPost(\"/CreateKey\", \"TrentService.CreateKey\", {\n Description: description,\n KeyUsage: \"SIGN_VERIFY\",\n KeySpec: \"ECC_SECG_P256K1\",\n Origin: \"EXTERNAL_KMS\",\n PasskeyPublicKey: passkeyPublicKey,\n });\n }\n\n async getKeyStatus(keyId: string): Promise<KmsKeyStatusResponse> {\n this.ensureEnabled();\n\n return this.client.get<KmsKeyStatusResponse>(\"/KeyStatus\", {\n params: { KeyId: keyId },\n });\n }\n\n async describeKey(keyId: string): Promise<KmsDescribeKeyResponse> {\n this.ensureEnabled();\n\n return this.amzPost(\"/DescribeKey\", \"TrentService.DescribeKey\", { KeyId: keyId });\n }\n\n /** Get a key's public key (uncompressed). Not WebAuthn-gated. */\n async getPublicKey(target: { KeyId?: string; Address?: string }): Promise<KmsGetPublicKeyResponse> {\n this.ensureEnabled();\n return this.amzPost(\"/GetPublicKey\", \"TrentService.GetPublicKey\", target);\n }\n\n /**\n * Derive an Ethereum address at a BIP-44 path (WebAuthn-gated).\n * Provide a WebAuthn ceremony assertion (preferred) or a Legacy passkey assertion.\n */\n async deriveAddress(params: {\n KeyId: string;\n DerivationPath: string;\n WebAuthn?: WebAuthnAssertion;\n Passkey?: LegacyPasskeyAssertion;\n }): Promise<KmsDeriveAddressResponse> {\n this.ensureEnabled();\n return this.amzPost(\"/DeriveAddress\", \"TrentService.DeriveAddress\", params);\n }\n\n /** List keys (paginated). Not WebAuthn-gated. */\n async listKeys(params: { Limit?: number; Marker?: string } = {}): Promise<KmsListKeysResponse> {\n this.ensureEnabled();\n return this.amzPost(\"/ListKeys\", \"TrentService.ListKeys\", params);\n }\n\n /**\n * Schedule key deletion (AWS-KMS action ScheduleKeyDeletion; WebAuthn-gated).\n * RPMB-bound on the TEE — requires a passkey/WebAuthn assertion on the normal path.\n */\n async deleteKey(params: {\n KeyId: string;\n PendingWindowInDays?: number;\n WebAuthn?: WebAuthnAssertion;\n Passkey?: LegacyPasskeyAssertion;\n }): Promise<KmsDeleteKeyResponse> {\n this.ensureEnabled();\n return this.amzPost(\"/DeleteKey\", \"TrentService.ScheduleKeyDeletion\", params);\n }\n\n /**\n * Unfreeze a dormant (frozen) key (issue #42; WebAuthn-gated).\n * A key auto-frozen by the dormant-key sweep rejects signing until unfrozen.\n * The TEE verifies the owner via the same strict WebAuthn ceremony as\n * {@link deleteKey}; ownership is checked even when the key is already active,\n * so this cannot be used as an unauthenticated key-state probe. Unlike DeleteKey\n * this endpoint takes no `x-amz-target` header — it authenticates via the default\n * API key plus the WebAuthn assertion in the body.\n */\n async unfreezeKey(params: {\n KeyId: string;\n WebAuthn?: WebAuthnAssertion;\n }): Promise<KmsUnfreezeKeyResponse> {\n this.ensureEnabled();\n return this.client.post<KmsUnfreezeKeyResponse>(\"/UnfreezeKey\", params);\n }\n\n /**\n * Rotate the WebAuthn passkey bound to a key (WebAuthn-gated, RPMB-bound).\n * `PasskeyPublicKey` is the NEW P-256 public key (0x04… 65-byte uncompressed).\n */\n async changePasskey(params: {\n KeyId: string;\n PasskeyPublicKey: string;\n WebAuthn?: WebAuthnAssertion;\n Passkey?: LegacyPasskeyAssertion;\n }): Promise<KmsChangePasskeyResponse> {\n this.ensureEnabled();\n return this.amzPost(\"/ChangePasskey\", \"TrentService.ChangePasskey\", params);\n }\n\n /**\n * Sign a message or an EIP-155 transaction (WebAuthn-gated).\n * Provide exactly one of `Message` (hex) or `Transaction`. For a raw 32-byte\n * digest use {@link signHash} / {@link signHashWithWebAuthn} instead.\n */\n async sign(params: KmsSignRequest): Promise<KmsSignResponse> {\n this.ensureEnabled();\n return this.amzPost(\"/Sign\", \"TrentService.Sign\", params);\n }\n\n /**\n * Poll KeyStatus until the key is ready (address derived) or timeout.\n * STM32 key derivation takes 60-75 seconds on first creation.\n */\n async pollUntilReady(\n keyId: string,\n timeoutMs: number = 120_000,\n intervalMs: number = 3_000\n ): Promise<KmsKeyStatusResponse> {\n this.ensureEnabled();\n\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n const status = await this.getKeyStatus(keyId);\n this.logger.debug(`Key ${keyId} status: ${status.Status}`);\n\n if (status.Status === \"ready\") {\n return status;\n }\n if (status.Status === \"error\") {\n throw new Error(`KMS key derivation failed: ${status.Error ?? \"unknown error\"}`);\n }\n\n await new Promise(resolve => setTimeout(resolve, intervalMs));\n }\n\n throw new Error(`KMS key derivation timed out after ${timeoutMs}ms`);\n }\n\n // ── Signing ─────────────────────────────────────────────────────\n\n /**\n * Sign a hash using Legacy Passkey assertion (reusable for BLS dual-signing).\n */\n async signHash(\n hash: string,\n assertion: LegacyPasskeyAssertion,\n target: { Address?: string; KeyId?: string }\n ): Promise<KmsSignHashResponse> {\n this.ensureEnabled();\n\n const formattedHash = hash.startsWith(\"0x\") ? hash : `0x${hash}`;\n\n const body: Record<string, unknown> = {\n Hash: formattedHash,\n Passkey: assertion,\n };\n\n if (target.Address) {\n body.Address = target.Address;\n }\n if (target.KeyId) {\n body.KeyId = target.KeyId;\n }\n\n return this.amzPost(\"/SignHash\", \"TrentService.SignHash\", body);\n }\n\n /**\n * Sign a hash using a WebAuthn ceremony assertion (one-time use).\n */\n async signHashWithWebAuthn(\n hash: string,\n challengeId: string,\n credential: unknown,\n target: { Address?: string; KeyId?: string }\n ): Promise<KmsSignHashResponse> {\n this.ensureEnabled();\n\n const formattedHash = hash.startsWith(\"0x\") ? hash : `0x${hash}`;\n\n const body: Record<string, unknown> = {\n Hash: formattedHash,\n WebAuthn: { ChallengeId: challengeId, Credential: credential },\n };\n\n if (target.Address) {\n body.Address = target.Address;\n }\n if (target.KeyId) {\n body.KeyId = target.KeyId;\n }\n\n return this.amzPost(\"/SignHash\", \"TrentService.SignHash\", body);\n }\n\n // ── Sign Typed Data (v0.19.0+) ─────────────────────────────────\n\n /**\n * Sign arbitrary EIP-712 typed data via `POST /kms/SignTypedData` (v0.20.0).\n *\n * The KMS hashes the typed data host-side, so the FULL EIP-712 structure\n * (domain / primaryType / types / message) is sent — not a pre-hashed\n * domainSeparator/structHash. The `webAuthnAssertion` challenge comes from a\n * generic {@link beginAuthentication} ceremony (purpose=\"authentication\").\n *\n * Alternatively, agents authenticate with a Bearer JWT — see KmsAgentService.\n */\n async signTypedDataWithWebAuthn(\n params: KmsSignTypedDataRequest\n ): Promise<KmsSignTypedDataResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsSignTypedDataResponse>(\"/kms/SignTypedData\", params);\n }\n\n // ── Grant Session Off-chain Signing (v0.19.0+) ─────────────────\n\n /**\n * Begin a grant-session WebAuthn challenge.\n * The returned challengeId can ONLY be used with sign-grant-session, not sign-typed-data.\n */\n async beginGrantSessionAuth(\n params: KmsBeginGrantSessionAuthRequest\n ): Promise<KmsBeginGrantSessionAuthResponse> {\n this.ensureEnabled();\n\n return this.client.get<KmsBeginGrantSessionAuthResponse>(\"/kms/begin-grant-session-auth\", {\n params: { keyId: params.keyId },\n });\n }\n\n /**\n * Sign a GRANT_SESSION_V2 hash off-chain inside the TEE (secp256k1 session key).\n * Returns a 65-byte signature (R||S||V, V=27/28) for use in grantSessionWithSig().\n */\n async signGrantSession(\n params: KmsSignGrantSessionRequest\n ): Promise<KmsSignGrantSessionResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsSignGrantSessionResponse>(\"/kms/sign-grant-session\", params);\n }\n\n /**\n * Sign a GRANT_P256_SESSION_V2 hash off-chain inside the TEE (P256 session key).\n * Returns a 65-byte signature for use in grantP256SessionWithSig().\n */\n async signP256GrantSession(\n params: KmsSignP256GrantSessionRequest\n ): Promise<KmsSignGrantSessionResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsSignGrantSessionResponse>(\"/kms/sign-p256-grant-session\", params);\n }\n\n // ── Challenge-binding ceremonies (#49 / Beta3) ──────────────────\n //\n // These run the full WebAuthn challenge-binding ceremony in one call:\n // fetch the TA one-time nonce, embed it in clientDataJSON, build + sign the\n // assertion, then invoke the signing endpoint with the resulting\n // `WebAuthn` / `webAuthnAssertion`. They share the\n // {@link runAuthenticationCeremony} / {@link runGrantSessionCeremony} helper,\n // so every path produces an identical, replay-protected assertion structure.\n\n /**\n * Run a generic authentication ceremony (purpose=\"authentication\") bound to a\n * fresh TA challenge. The returned assertion is valid for DeriveAddress / Sign\n * / SignHash / SignTypedData / agent-key / p256-session signing.\n */\n async runAuthenticationCeremony(\n keyId: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<WebAuthnAssertion> {\n this.ensureEnabled();\n return runAuthenticationCeremony(this.client, keyId, signer, options);\n }\n\n /**\n * Run a grant-session ceremony (purpose=\"grant-session\") bound to a fresh TA\n * challenge — required by {@link signGrantSession} / {@link signP256GrantSession}\n * (the generic 'authentication' challenge is rejected there for replay safety).\n */\n async runGrantSessionCeremony(\n keyId: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<WebAuthnAssertion> {\n this.ensureEnabled();\n return runGrantSessionCeremony(this.client, keyId, signer, options);\n }\n\n /** Derive an address, running the challenge-binding ceremony internally. */\n async deriveAddressWithCeremony(\n params: { KeyId: string; DerivationPath: string },\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsDeriveAddressResponse> {\n this.ensureEnabled();\n const WebAuthn = await this.runAuthenticationCeremony(params.KeyId, signer, options);\n return this.deriveAddress({ ...params, WebAuthn });\n }\n\n /**\n * Sign a message or EIP-155 transaction, running the challenge-binding ceremony\n * internally. `params.KeyId` is required (it identifies the wallet to challenge).\n */\n async signWithCeremony(\n params: Omit<KmsSignRequest, \"WebAuthn\" | \"Passkey\"> & { KeyId: string },\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsSignResponse> {\n this.ensureEnabled();\n const WebAuthn = await this.runAuthenticationCeremony(params.KeyId, signer, options);\n return this.sign({ ...params, WebAuthn });\n }\n\n /** Sign a 32-byte digest, running the challenge-binding ceremony internally. */\n async signHashWithCeremony(\n hash: string,\n target: { KeyId: string },\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsSignHashResponse> {\n this.ensureEnabled();\n const assertion = await this.runAuthenticationCeremony(target.KeyId, signer, options);\n return this.signHashWithWebAuthn(hash, assertion.ChallengeId, assertion.Credential, target);\n }\n\n /** Sign EIP-712 typed data, running the challenge-binding ceremony internally. */\n async signTypedDataWithCeremony(\n params: Omit<KmsSignTypedDataRequest, \"webAuthnAssertion\">,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsSignTypedDataResponse> {\n this.ensureEnabled();\n const webAuthnAssertion = await this.runAuthenticationCeremony(params.keyId, signer, options);\n return this.signTypedDataWithWebAuthn({ ...params, webAuthnAssertion });\n }\n\n /**\n * Sign a GRANT_SESSION_V2 hash, running the grant-session ceremony internally\n * (uses the purpose-bound `begin-grant-session-auth` challenge).\n */\n async signGrantSessionWithCeremony(\n params: Omit<KmsSignGrantSessionRequest, \"webAuthnAssertion\">,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsSignGrantSessionResponse> {\n this.ensureEnabled();\n const webAuthnAssertion = await this.runGrantSessionCeremony(params.keyId, signer, options);\n return this.signGrantSession({ ...params, webAuthnAssertion });\n }\n\n /**\n * Sign a GRANT_P256_SESSION_V2 hash, running the grant-session ceremony\n * internally (uses the purpose-bound `begin-grant-session-auth` challenge).\n */\n async signP256GrantSessionWithCeremony(\n params: Omit<KmsSignP256GrantSessionRequest, \"webAuthnAssertion\">,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsSignGrantSessionResponse> {\n this.ensureEnabled();\n const webAuthnAssertion = await this.runGrantSessionCeremony(params.keyId, signer, options);\n return this.signP256GrantSession({ ...params, webAuthnAssertion });\n }\n\n // ── WebAuthn Ceremonies ─────────────────────────────────────────\n\n async beginRegistration(\n params: KmsBeginRegistrationRequest\n ): Promise<KmsBeginRegistrationResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsBeginRegistrationResponse>(\"/BeginRegistration\", params);\n }\n\n async completeRegistration(\n params: KmsCompleteRegistrationRequest\n ): Promise<KmsCompleteRegistrationResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsCompleteRegistrationResponse>(\"/CompleteRegistration\", params);\n }\n\n async beginAuthentication(\n params: KmsBeginAuthenticationRequest\n ): Promise<KmsBeginAuthenticationResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsBeginAuthenticationResponse>(\"/BeginAuthentication\", params);\n }\n\n /**\n * Begin a generic WebAuthn authentication ceremony for a key, returning a\n * challenge usable for SignHash / SignTypedData (purpose=\"authentication\").\n *\n * NOTE: there is no dedicated `begin-webauthn-auth` endpoint — this delegates\n * to `POST /BeginAuthentication`. (Grant-session signing needs a purpose-bound\n * challenge from {@link beginGrantSessionAuth} instead.)\n */\n async beginWebAuthnAuth(keyId: string): Promise<KmsBeginAuthenticationResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsBeginAuthenticationResponse>(\"/BeginAuthentication\", { KeyId: keyId });\n }\n\n // ── Factory ─────────────────────────────────────────────────────\n\n createKmsSigner(\n keyId: string,\n address: string,\n assertionProvider: () => Promise<LegacyPasskeyAssertion>\n ): KmsSigner {\n this.ensureEnabled();\n return new KmsSigner(keyId, address, this, assertionProvider);\n }\n}\n\n/**\n * KMS-backed signer with Passkey assertion.\n *\n * Each signing operation calls the `assertionProvider` to obtain a Legacy\n * Passkey assertion, which is then passed to KMS SignHash. The Legacy format\n * is reusable (no challenge consumption), enabling BLS dual-signing.\n *\n * Narrowed during the ethers -> viem migration: only the EIP-191 personal-sign\n * and address-read behaviour is actually consumed by the SDK, so the former\n * ethers.AbstractSigner surface (signTransaction / signTypedData / connect /\n * provider) has been dropped.\n */\nexport class KmsSigner {\n constructor(\n private readonly keyId: string,\n private readonly _address: string,\n private readonly kmsManager: KmsManager,\n private readonly assertionProvider: () => Promise<LegacyPasskeyAssertion>\n ) {}\n\n async getAddress(): Promise<string> {\n return this._address;\n }\n\n async signMessage(message: string | Uint8Array): Promise<string> {\n // EIP-191 personal-sign: a string is hashed as UTF-8 text, a byte array as\n // raw bytes — byte-identical to ethers `hashMessage(toUtf8Bytes(str) | bytes)`.\n const messageHash = hashMessage(message);\n const assertion = await this.assertionProvider();\n const signResponse = await this.kmsManager.signHash(messageHash, assertion, {\n Address: this._address,\n });\n return \"0x\" + signResponse.Signature;\n }\n}\n","import { KmsHttpClient } from \"./kms-http-client\";\nimport { WebAuthnAssertion, LegacyPasskeyAssertion } from \"./kms-signer\";\nimport {\n PasskeyCeremonySigner,\n RunCeremonyOptions,\n runAuthenticationCeremony,\n} from \"./webauthn-ceremony\";\n\n// ── CreateAgentKey ───────────────────────────────────────────────\n\n/**\n * Request to mint a new agent key under an existing human key.\n *\n * WebAuthn-gated: the human approves the mint with a one-time WebAuthn ceremony\n * (preferred) or a Legacy passkey assertion. The challenge is obtained via\n * {@link KmsManager.beginAuthentication} (generic, purpose=\"authentication\") —\n * the caller supplies the resulting assertion here.\n */\nexport interface KmsCreateAgentKeyRequest {\n humanKeyId: string;\n label?: string;\n webAuthnAssertion?: WebAuthnAssertion;\n passkeyAssertion?: LegacyPasskeyAssertion;\n}\n\nexport interface KmsCreateAgentKeyResponse {\n keyId: string; // \"wallet_uuid:agent_index\"\n agentAddress: string;\n derivationPath: string;\n agentCredential: string; // TEE-issued JWT\n expiresAt: number;\n}\n\n// ── SignAgent ────────────────────────────────────────────────────\n\n/**\n * Request to sign a userOpHash with an agent key, authenticated by the agent's\n * TEE-JWT credential (Bearer). Used for gasless ERC-4337 sponsorship.\n */\nexport interface KmsSignAgentRequest {\n keyId: string;\n payload: string; // hex userOpHash\n algorithm?: string; // defaults to \"secp256k1\" server-side\n accountAddress: string; // 0x… ERC-4337 account\n}\n\nexport interface KmsSignAgentResponse {\n keyId: string;\n agentAddress: string;\n /** Hex 106-byte signature: [0x08][account(20)][key(20)][r(32)][s(32)][v(1)]. */\n signature: string;\n}\n\n// ── RefreshAgentCredential ───────────────────────────────────────\n\n/**\n * Request to refresh (re-mint) an agent's TEE-JWT credential before it expires.\n *\n * Authenticated with the existing (still-valid) credential via Bearer JWT, plus\n * a WebAuthn / Legacy passkey assertion from the human key owner.\n */\nexport interface KmsRefreshAgentCredentialRequest {\n keyId: string;\n webAuthnAssertion?: WebAuthnAssertion;\n passkeyAssertion?: LegacyPasskeyAssertion;\n}\n\n/**\n * The server response shape is not strictly documented; this models the fields\n * the SDK relies on. `keyId` is echoed back optionally.\n */\nexport interface KmsRefreshAgentCredentialResponse {\n keyId?: string;\n agentCredential: string; // new TEE-issued JWT\n expiresAt: number;\n}\n\n// ── RevokeAgentCredential ────────────────────────────────────────\n\n/**\n * Request to revoke an agent's credential (WebAuthn-gated).\n *\n * The challenge is obtained via {@link KmsManager.beginAuthentication} (generic,\n * purpose=\"authentication\"); the caller supplies the resulting assertion here.\n */\nexport interface KmsRevokeAgentCredentialRequest {\n keyId: string;\n webAuthnAssertion?: WebAuthnAssertion;\n passkeyAssertion?: LegacyPasskeyAssertion;\n}\n\nexport interface KmsRevokeAgentCredentialResponse {\n success: boolean;\n revokedAt: number;\n}\n\n/**\n * Agent-key lifecycle service for the AAStar TEE KMS (v0.20.0).\n *\n * An \"agent key\" is a TEE-JWT credential minted under a human key, used for\n * gasless ERC-4337 sponsorship without re-prompting the human for each signature.\n * Lifecycle:\n * 1. {@link createAgentKey} — human mints the agent key (WebAuthn-gated)\n * 2. {@link signAgent} — agent signs userOpHashes (Bearer JWT auth)\n * 3. {@link refreshAgentCredential}— re-mint before expiry (Bearer JWT + WebAuthn)\n * 4. {@link revokeAgentCredential} — human revokes the agent key (WebAuthn-gated)\n *\n * Wraps a shared {@link KmsHttpClient} — obtain it via {@link KmsManager.httpClient}\n * so this service reuses the same connection config and auth headers.\n */\nexport class KmsAgentService {\n constructor(private readonly http: KmsHttpClient) {}\n\n /**\n * Mint a new agent key under an existing human key (WebAuthn-gated).\n *\n * The WebAuthn challenge is obtained from a generic\n * {@link KmsManager.beginAuthentication} ceremony (purpose=\"authentication\");\n * the caller supplies the resulting assertion in the request.\n */\n async createAgentKey(\n params: KmsCreateAgentKeyRequest\n ): Promise<KmsCreateAgentKeyResponse> {\n this.http.ensureEnabled();\n\n return this.http.post<KmsCreateAgentKeyResponse>(\"/kms/create-agent-key\", params);\n }\n\n /**\n * Sign a userOpHash with an agent key, authenticated by the agent's TEE-JWT\n * credential (`jwt`, the `agentCredential` from {@link createAgentKey}).\n * Returns the 106-byte packed signature for ERC-4337 sponsorship.\n */\n async signAgent(\n params: KmsSignAgentRequest,\n jwt: string\n ): Promise<KmsSignAgentResponse> {\n this.http.ensureEnabled();\n\n return this.http.postWithBearer<KmsSignAgentResponse>(\"/kms/sign-agent\", params, jwt);\n }\n\n /**\n * Refresh (re-mint) an agent credential before it expires. Authenticated with\n * the existing credential (`jwt`, Bearer) plus a human WebAuthn / passkey\n * assertion in the request.\n */\n async refreshAgentCredential(\n params: KmsRefreshAgentCredentialRequest,\n jwt: string\n ): Promise<KmsRefreshAgentCredentialResponse> {\n this.http.ensureEnabled();\n\n return this.http.postWithBearer<KmsRefreshAgentCredentialResponse>(\n \"/kms/refresh-agent-credential\",\n params,\n jwt\n );\n }\n\n /**\n * Revoke an agent's credential (WebAuthn-gated).\n *\n * The WebAuthn challenge is obtained from a generic\n * {@link KmsManager.beginAuthentication} ceremony (purpose=\"authentication\");\n * the caller supplies the resulting assertion in the request.\n */\n async revokeAgentCredential(\n params: KmsRevokeAgentCredentialRequest\n ): Promise<KmsRevokeAgentCredentialResponse> {\n this.http.ensureEnabled();\n\n return this.http.post<KmsRevokeAgentCredentialResponse>(\n \"/kms/revoke-agent-credential\",\n params\n );\n }\n\n // ── Challenge-binding ceremony variants (#49 / Beta3) ────────────\n //\n // All agent-key WebAuthn gates use the generic purpose=\"authentication\"\n // challenge bound to the HUMAN key. These helpers run the full ceremony\n // (begin → clientDataJSON → assertion) via the shared\n // {@link runAuthenticationCeremony} helper, then invoke the endpoint.\n\n /** Mint an agent key, running the challenge-binding ceremony internally. */\n async createAgentKeyWithCeremony(\n params: Omit<KmsCreateAgentKeyRequest, \"webAuthnAssertion\" | \"passkeyAssertion\">,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsCreateAgentKeyResponse> {\n this.http.ensureEnabled();\n const webAuthnAssertion = await runAuthenticationCeremony(\n this.http,\n params.humanKeyId,\n signer,\n options\n );\n return this.createAgentKey({ ...params, webAuthnAssertion });\n }\n\n /**\n * Refresh an agent credential, running the challenge-binding ceremony\n * internally. `humanKeyId` is the owning human key challenged by the ceremony\n * (distinct from the agent `keyId` in `params`); `jwt` is the existing credential.\n */\n async refreshAgentCredentialWithCeremony(\n params: Omit<KmsRefreshAgentCredentialRequest, \"webAuthnAssertion\" | \"passkeyAssertion\">,\n humanKeyId: string,\n jwt: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsRefreshAgentCredentialResponse> {\n this.http.ensureEnabled();\n const webAuthnAssertion = await runAuthenticationCeremony(this.http, humanKeyId, signer, options);\n return this.refreshAgentCredential({ ...params, webAuthnAssertion }, jwt);\n }\n\n /**\n * Revoke an agent credential, running the challenge-binding ceremony internally.\n * `humanKeyId` is the owning human key challenged by the ceremony (distinct from\n * the agent `keyId` in `params`).\n */\n async revokeAgentCredentialWithCeremony(\n params: Omit<KmsRevokeAgentCredentialRequest, \"webAuthnAssertion\" | \"passkeyAssertion\">,\n humanKeyId: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsRevokeAgentCredentialResponse> {\n this.http.ensureEnabled();\n const webAuthnAssertion = await runAuthenticationCeremony(this.http, humanKeyId, signer, options);\n return this.revokeAgentCredential({ ...params, webAuthnAssertion });\n }\n}\n","import { KmsHttpClient } from \"./kms-http-client\";\nimport { WebAuthnAssertion } from \"./kms-signer\";\nimport {\n PasskeyCeremonySigner,\n RunCeremonyOptions,\n runAuthenticationCeremony,\n} from \"./webauthn-ceremony\";\n\n// ── Create P256 Session Key (v0.20.0) ───────────────────────────\n\nexport interface CreateP256SessionKeyRequest {\n /** Human (root) key under which the session key is minted. */\n humanKeyId: string;\n /** Optional human-readable label for the session key. */\n label?: string;\n /**\n * One-time WebAuthn assertion gating creation. The challenge comes from a\n * generic {@link KmsManager.beginAuthentication} ceremony — the caller runs\n * the ceremony and supplies the resulting assertion here.\n */\n webAuthnAssertion?: WebAuthnAssertion;\n}\n\nexport interface CreateP256SessionKeyResponse {\n keyId: string;\n pubKeyX: string; // 0x… 32-byte P256 public key X coordinate\n pubKeyY: string; // 0x… 32-byte P256 public key Y coordinate\n algorithm: string; // \"p256\"\n agentCredential: string; // JWT — bearer token for subsequent per-UserOp signing\n expiresAt: number; // unix seconds\n}\n\n// ── Sign P256 UserOp (Bearer JWT auth) ──────────────────────────\n\nexport interface SignP256UserOpRequest {\n keyId: string;\n payload: string; // hex userOpHash (32 bytes)\n accountAddress: string; // 0x… ERC-4337 account address\n}\n\nexport interface SignP256UserOpResponse {\n keyId: string;\n pubKeyX: string;\n pubKeyY: string;\n /**\n * 149-byte P256 session-key wire format (hex):\n * [0x08][account(20)][keyX(32)][keyY(32)][r(32)][s(32)].\n */\n signature: string;\n}\n\n// ── Revoke P256 Session Key (v0.20.0) ───────────────────────────\n\nexport interface RevokeP256SessionKeyRequest {\n keyId: string;\n /**\n * One-time WebAuthn assertion gating revocation. The challenge comes from a\n * generic {@link KmsManager.beginAuthentication} ceremony — the caller runs\n * the ceremony and supplies the resulting assertion here.\n */\n webAuthnAssertion?: WebAuthnAssertion;\n}\n\nexport interface RevokeP256SessionKeyResponse {\n success: boolean;\n revokedAt: number; // unix seconds\n}\n\n/**\n * Manages the lifecycle of a P-256 session key minted under a human key for\n * ERC-4337 UserOp signing (AAStar TEE KMS v0.20.0).\n *\n * A session key is created under a root (human) key, used to sign UserOps via a\n * TEE-issued bearer JWT (the `agentCredential`), and eventually revoked. The\n * per-UserOp signature is the 149-byte P256 session-key wire format.\n *\n * Relationship to {@link KmsManager.signP256GrantSession}: that method signs the\n * GRANT_P256_SESSION_V2 authorization needed to *install* this key on-chain\n * (granting the session key its on-chain scope/policies). This service instead\n * manages the session key's own lifecycle (create / sign / revoke) once granted.\n *\n * Create and revoke are WebAuthn-gated: the challenge originates from a generic\n * {@link KmsManager.beginAuthentication} ceremony and the caller supplies the\n * resulting assertion. Per-UserOp signing authenticates with the bearer JWT.\n *\n * Wraps a shared {@link KmsHttpClient} — pass `KmsManager.httpClient`.\n */\nexport class KmsSessionService {\n constructor(private readonly http: KmsHttpClient) {}\n\n /**\n * Create a P-256 session key under a human key (WebAuthn-gated).\n *\n * `POST /kms/create-p256-session-key`. The `webAuthnAssertion` challenge comes\n * from a generic {@link KmsManager.beginAuthentication} ceremony supplied by\n * the caller. Returns the session key's public key plus an `agentCredential`\n * JWT used to authenticate subsequent {@link signP256UserOp} calls.\n */\n async createP256SessionKey(\n params: CreateP256SessionKeyRequest\n ): Promise<CreateP256SessionKeyResponse> {\n this.http.ensureEnabled();\n\n return this.http.post<CreateP256SessionKeyResponse>(\n \"/kms/create-p256-session-key\",\n params\n );\n }\n\n /**\n * Sign an ERC-4337 UserOp hash with a P-256 session key (Bearer JWT auth).\n *\n * `POST /kms/sign-p256-user-op`, authenticated with the `agentCredential` JWT\n * returned by {@link createP256SessionKey}. Returns the 149-byte P256\n * session-key wire-format signature.\n */\n async signP256UserOp(\n params: SignP256UserOpRequest,\n jwt: string\n ): Promise<SignP256UserOpResponse> {\n this.http.ensureEnabled();\n\n return this.http.postWithBearer<SignP256UserOpResponse>(\n \"/kms/sign-p256-user-op\",\n params,\n jwt\n );\n }\n\n /**\n * Revoke a P-256 session key (WebAuthn-gated, idempotent).\n *\n * `POST /kms/revoke-p256-session-key`. The `webAuthnAssertion` challenge comes\n * from a generic {@link KmsManager.beginAuthentication} ceremony supplied by\n * the caller. Idempotent: revoking an already-revoked key still resolves.\n */\n async revokeP256SessionKey(\n params: RevokeP256SessionKeyRequest\n ): Promise<RevokeP256SessionKeyResponse> {\n this.http.ensureEnabled();\n\n return this.http.post<RevokeP256SessionKeyResponse>(\n \"/kms/revoke-p256-session-key\",\n params\n );\n }\n\n // ── Challenge-binding ceremony variants (#49 / Beta3) ────────────\n //\n // Create + revoke gate on the generic purpose=\"authentication\" challenge bound\n // to the HUMAN key. These helpers run the full ceremony (begin → clientDataJSON\n // → assertion) via the shared {@link runAuthenticationCeremony} helper.\n\n /** Create a P-256 session key, running the challenge-binding ceremony internally. */\n async createP256SessionKeyWithCeremony(\n params: Omit<CreateP256SessionKeyRequest, \"webAuthnAssertion\">,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<CreateP256SessionKeyResponse> {\n this.http.ensureEnabled();\n const webAuthnAssertion = await runAuthenticationCeremony(\n this.http,\n params.humanKeyId,\n signer,\n options\n );\n return this.createP256SessionKey({ ...params, webAuthnAssertion });\n }\n\n /**\n * Revoke a P-256 session key, running the challenge-binding ceremony internally.\n * `humanKeyId` is the owning human key challenged by the ceremony (distinct from\n * the session `keyId` in `params`).\n */\n async revokeP256SessionKeyWithCeremony(\n params: Omit<RevokeP256SessionKeyRequest, \"webAuthnAssertion\">,\n humanKeyId: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<RevokeP256SessionKeyResponse> {\n this.http.ensureEnabled();\n const webAuthnAssertion = await runAuthenticationCeremony(this.http, humanKeyId, signer, options);\n return this.revokeP256SessionKey({ ...params, webAuthnAssertion });\n }\n}\n","import { KmsHttpClient } from \"./kms-http-client\";\nimport { WebAuthnAssertion } from \"./kms-signer\";\n\n// ── Auth modes (v0.20.0 P2 SuperPaymaster convenience signers) ───\n//\n// Each KMS payment endpoint authorizes the signing operation in ONE of two ways:\n// - a one-time WebAuthn ceremony assertion carried in the request body, or\n// - an agent/session JWT carried in the `Authorization: Bearer <jwt>` header.\n// Callers pick exactly one via the discriminated `KmsPaymentAuth` union.\n\nexport type KmsPaymentAuth = { jwt: string } | { webAuthnAssertion: WebAuthnAssertion };\n\n/** Shared signature response for all payment signing endpoints. */\nexport interface KmsPaymentSignatureResponse {\n keyId: string;\n signature: string; // 65-byte hex (R||S||V)\n}\n\n// ── SignMicropaymentVoucher ──────────────────────────────────────\n\nexport interface KmsSignMicropaymentVoucherRequest {\n keyId: string;\n hdPath?: string; // defaults to m/44'/60'/0'/0/0 server-side\n chainId: number;\n verifyingContract: string; // MicroPaymentChannel address (0x… 20-byte)\n channelId: string; // 0x… 32-byte\n cumulativeAmount: string; // uint256 (decimal or 0x…)\n}\n\n// ── SignGTokenAuthorization (EIP-3009 TransferWithAuthorization) ──\n\nexport interface KmsSignGTokenAuthorizationRequest {\n keyId: string;\n hdPath?: string; // defaults to m/44'/60'/0'/0/0 server-side\n chainId: number;\n gTokenAddress: string;\n from: string; // MUST equal the derived address\n to: string;\n value: string; // uint256\n validAfter: string;\n validBefore: string;\n nonce: string; // 0x… 32-byte\n}\n\n// ── SignX402Payment ──────────────────────────────────────────────\n\nexport interface KmsSignX402PaymentRequest {\n keyId: string;\n hdPath?: string; // defaults to m/44'/60'/0'/0/0 server-side\n chainId: number;\n verifyingContract: string;\n paymentId: string; // 0x… 32-byte\n amount: string; // uint256\n recipient: string;\n deadline: string;\n}\n\n/**\n * Convenience signers for SuperPaymaster payment flows (v0.20.0 P2).\n *\n * Each method maps to a fixed EIP-712 domain + type that the KMS builds host-side\n * and signs inside the TEE; the SDK only forwards the structured parameters. Every\n * endpoint accepts EITHER a one-time `webAuthnAssertion` in the body OR an agent\n * Bearer JWT — see {@link KmsPaymentAuth}.\n *\n * Wraps a shared {@link KmsHttpClient}; reuse the same instance across the agent /\n * session / payment / monitor services.\n */\nexport class KmsPaymentSigner {\n constructor(private readonly http: KmsHttpClient) {}\n\n /**\n * Dispatch a payment-signing request with the chosen auth mode.\n * JWT auth uses `postWithBearer`; WebAuthn auth merges the assertion into the body.\n */\n private async signWithAuth(\n path: string,\n body: Record<string, unknown>,\n auth: KmsPaymentAuth\n ): Promise<KmsPaymentSignatureResponse> {\n if (\"jwt\" in auth) {\n return this.http.postWithBearer<KmsPaymentSignatureResponse>(path, body, auth.jwt);\n }\n return this.http.post<KmsPaymentSignatureResponse>(path, {\n ...body,\n webAuthnAssertion: auth.webAuthnAssertion,\n });\n }\n\n /**\n * Sign a MicroPaymentChannel voucher (cumulative-amount EIP-712 message)\n * via `POST /kms/SignMicropaymentVoucher`.\n */\n async signMicropaymentVoucher(\n params: KmsSignMicropaymentVoucherRequest,\n auth: KmsPaymentAuth\n ): Promise<KmsPaymentSignatureResponse> {\n this.http.ensureEnabled();\n return this.signWithAuth(\"/kms/SignMicropaymentVoucher\", { ...params }, auth);\n }\n\n /**\n * Sign an EIP-3009 TransferWithAuthorization for a GToken transfer\n * via `POST /kms/SignGTokenAuthorization`. `from` MUST equal the derived address.\n */\n async signGTokenAuthorization(\n params: KmsSignGTokenAuthorizationRequest,\n auth: KmsPaymentAuth\n ): Promise<KmsPaymentSignatureResponse> {\n this.http.ensureEnabled();\n return this.signWithAuth(\"/kms/SignGTokenAuthorization\", { ...params }, auth);\n }\n\n /**\n * Sign an x402 payment authorization via `POST /kms/SignX402Payment`.\n */\n async signX402Payment(\n params: KmsSignX402PaymentRequest,\n auth: KmsPaymentAuth\n ): Promise<KmsPaymentSignatureResponse> {\n this.http.ensureEnabled();\n return this.signWithAuth(\"/kms/SignX402Payment\", { ...params }, auth);\n }\n}\n","import { KmsHttpClient } from \"./kms-http-client\";\n\n// ── Health (GET /health, no auth) ────────────────────────────────\n\n/**\n * Liveness probe response. Returned by `GET /health` without auth — works even\n * when the SDK's KMS feature flag is off.\n */\nexport interface KmsHealthResponse {\n status: string;\n service?: string;\n ta_mode?: string;\n version?: string;\n}\n\n// ── Version (GET /version, no auth) ──────────────────────────────\n\n/**\n * Version / capability descriptor. Returned by `GET /version` without auth.\n * Extra fields are passed through.\n */\nexport interface KmsVersionResponse {\n version?: string;\n ta_mode?: string;\n endpoints?: string[];\n [k: string]: unknown;\n}\n\n// ── Queue Status (GET /QueueStatus) ──────────────────────────────\n\n/**\n * KMS request-queue health, including circuit-breaker state. Useful for\n * back-pressure decisions before submitting signing operations.\n */\nexport interface KmsQueueStatusResponse {\n queue_depth: number;\n estimated_wait_seconds: number;\n circuit_breaker_open: boolean;\n consecutive_failures: number;\n}\n\n// ── Rollback Counter (GET /RollbackCounter, v0.20.0) ─────────────\n\n/**\n * RPMB anti-rollback monotonic counter (diagnostic, v0.20.0). The exact shape\n * is undocumented; the known `counter` field is surfaced and all other fields\n * are passed through.\n */\nexport interface KmsRollbackCounterResponse {\n counter?: number;\n [k: string]: unknown;\n}\n\n// ── Stats (GET /stats, v0.20.0) ──────────────────────────────────\n\n/**\n * Machine-readable runtime statistics (v0.20.0). Pass-through; the response is\n * not strongly typed. Known top-level fields:\n * - `wallets` — wallet / key counts\n * - `tx` — transaction / signing counts\n * - `queue` — queue depth and timing metrics\n * - `warnings` — active operational warnings\n */\nexport interface KmsStatsResponse {\n [k: string]: unknown;\n}\n\n// ── TEE remote-attestation (GET /attestation + .well-known, #37/#12/#87) ──\n\n/** `GET /attestation` evidence bound to a caller nonce (#37). */\nexport interface KmsAttestationResponse {\n schema?: string;\n nonce?: string;\n ta_uuid?: string;\n ta_measurement?: string;\n signature?: string;\n attest_pubkey_exp?: string;\n attest_pubkey_mod?: string;\n sig_alg?: number;\n ree_time_secs?: number;\n trust_root?: string;\n [k: string]: unknown;\n}\n\n/** `GET /.well-known/attestation-measurements.json` — Ed25519-signed manifest (#12). */\nexport interface KmsAttestationManifestResponse {\n body?: Record<string, unknown>;\n publisher_key?: string;\n signature?: string;\n [k: string]: unknown;\n}\n\n/** `GET /.well-known/attestation-measurements-proof.json` — Sigsum proof sidecar (#87). */\nexport interface KmsAttestationProofResponse {\n proof?: Record<string, unknown>;\n [k: string]: unknown;\n}\n\n// ── Admin Purge Key (POST /admin/purge-key, v0.20.0) ─────────────\n\n/**\n * Response of the destructive operator-only purge action (v0.20.0).\n * Pass-through; the response shape is not strongly typed.\n */\nexport interface KmsPurgeKeyResponse {\n [k: string]: unknown;\n}\n\n/**\n * Infrastructure monitoring + operator admin surface for the AAStar TEE KMS\n * (v0.20.0, kms.aastar.io).\n *\n * Wraps a shared {@link KmsHttpClient}. Liveness probes (`health`, `version`)\n * intentionally bypass the `enabled` gate so they work even when the SDK's KMS\n * feature flag is off; every other method calls `ensureEnabled()` first.\n */\nexport class KmsMonitorService {\n constructor(private readonly http: KmsHttpClient) {}\n\n /**\n * Liveness probe (`GET /health`, no auth). Does NOT require the KMS feature\n * flag to be enabled.\n */\n async health(): Promise<KmsHealthResponse> {\n return this.http.get<KmsHealthResponse>(\"/health\");\n }\n\n /**\n * Version / capability descriptor (`GET /version`, no auth). Does NOT require\n * the KMS feature flag to be enabled.\n */\n async version(): Promise<KmsVersionResponse> {\n return this.http.get<KmsVersionResponse>(\"/version\");\n }\n\n /**\n * Request-queue health and circuit-breaker state (`GET /QueueStatus`).\n */\n async queueStatus(): Promise<KmsQueueStatusResponse> {\n this.http.ensureEnabled();\n return this.http.get<KmsQueueStatusResponse>(\"/QueueStatus\");\n }\n\n /**\n * RPMB anti-rollback monotonic counter (`GET /RollbackCounter`, diagnostic,\n * v0.20.0).\n */\n async rollbackCounter(): Promise<KmsRollbackCounterResponse> {\n this.http.ensureEnabled();\n return this.http.get<KmsRollbackCounterResponse>(\"/RollbackCounter\");\n }\n\n /**\n * Machine-readable runtime statistics (`GET /stats`, v0.20.0) — wallets, tx,\n * queue, warnings.\n */\n async stats(): Promise<KmsStatsResponse> {\n this.http.ensureEnabled();\n return this.http.get<KmsStatsResponse>(\"/stats\");\n }\n\n /**\n * TEE remote-attestation evidence bound to a caller nonce (`GET /attestation`,\n * #37). Public (no auth) — pass a fresh random `nonce` (hex, ≤64 bytes) to bind\n * the evidence + defeat replay, then verify the returned signed measurement.\n */\n async getAttestation(nonce: string): Promise<KmsAttestationResponse> {\n return this.http.get<KmsAttestationResponse>(\"/attestation\", { params: { nonce } });\n }\n\n /**\n * Ed25519-signed measurement manifest, version → ta_measurement\n * (`GET /.well-known/attestation-measurements.json`, #12). Public.\n */\n async getAttestationMeasurements(): Promise<KmsAttestationManifestResponse> {\n return this.http.get<KmsAttestationManifestResponse>(\"/.well-known/attestation-measurements.json\");\n }\n\n /**\n * Sigsum transparency proof sidecar for the measurement manifest\n * (`GET /.well-known/attestation-measurements-proof.json`, #87). Public.\n */\n async getAttestationMeasurementsProof(): Promise<KmsAttestationProofResponse> {\n return this.http.get<KmsAttestationProofResponse>(\"/.well-known/attestation-measurements-proof.json\");\n }\n\n /**\n * WARNING — DESTRUCTIVE, IRREVERSIBLE. Force-purges a key from both the TEE\n * and the SQLite store with NO passkey/WebAuthn check (`POST /admin/purge-key`,\n * v0.20.0). Operator-only: authorised solely by the `KMS_ADMIN_TOKEN` operator\n * secret sent as `Authorization: Bearer <adminToken>`. There is no recovery\n * once a key is purged.\n *\n * @internal Operator/break-glass tooling only — not part of the general SDK surface.\n * The endpoint is gated server-side and intentionally omitted from the public KMS\n * docs; do not expose it in application-facing flows.\n */\n async adminPurgeKey(\n params: { key_id: string; reason: string },\n adminToken: string\n ): Promise<KmsPurgeKeyResponse> {\n this.http.ensureEnabled();\n return this.http.postWithBearer<KmsPurgeKeyResponse>(\"/admin/purge-key\", params, adminToken);\n }\n}\n","import {\n IStorageAdapter,\n AccountRecord,\n TransferRecord,\n PaymasterRecord,\n BlsConfigRecord,\n} from \"../interfaces/storage-adapter\";\n\n/**\n * In-memory storage adapter — useful for testing and demos.\n * All data is lost when the process exits.\n */\nexport class MemoryStorage implements IStorageAdapter {\n private accounts: AccountRecord[] = [];\n private transfers: TransferRecord[] = [];\n private paymasters: Map<string, PaymasterRecord[]> = new Map();\n private blsConfig: BlsConfigRecord | null = null;\n\n // ── Accounts ─────────────────────────────────────────────────\n\n async getAccounts(): Promise<AccountRecord[]> {\n return [...this.accounts];\n }\n\n async saveAccount(account: AccountRecord): Promise<void> {\n this.accounts.push({ ...account });\n }\n\n async findAccountByUserId(userId: string): Promise<AccountRecord | null> {\n return this.accounts.find(a => a.userId === userId) ?? null;\n }\n\n async updateAccount(userId: string, updates: Partial<AccountRecord>): Promise<void> {\n const index = this.accounts.findIndex(a => a.userId === userId);\n if (index >= 0) {\n this.accounts[index] = { ...this.accounts[index], ...updates };\n }\n }\n\n // ── Transfers ────────────────────────────────────────────────\n\n async saveTransfer(transfer: TransferRecord): Promise<void> {\n this.transfers.push({ ...transfer });\n }\n\n async findTransfersByUserId(userId: string): Promise<TransferRecord[]> {\n return this.transfers.filter(t => t.userId === userId);\n }\n\n async findTransferById(id: string): Promise<TransferRecord | null> {\n return this.transfers.find(t => t.id === id) ?? null;\n }\n\n async updateTransfer(id: string, updates: Partial<TransferRecord>): Promise<void> {\n const index = this.transfers.findIndex(t => t.id === id);\n if (index >= 0) {\n this.transfers[index] = { ...this.transfers[index], ...updates };\n }\n }\n\n // ── Paymasters ───────────────────────────────────────────────\n\n async getPaymasters(userId: string): Promise<PaymasterRecord[]> {\n return this.paymasters.get(userId) ?? [];\n }\n\n async savePaymaster(userId: string, paymaster: PaymasterRecord): Promise<void> {\n const list = this.paymasters.get(userId) ?? [];\n const existingIndex = list.findIndex(p => p.name === paymaster.name);\n if (existingIndex >= 0) {\n list[existingIndex] = { ...paymaster };\n } else {\n list.push({ ...paymaster });\n }\n this.paymasters.set(userId, list);\n }\n\n async removePaymaster(userId: string, name: string): Promise<boolean> {\n const list = this.paymasters.get(userId) ?? [];\n const filtered = list.filter(p => p.name !== name);\n if (filtered.length < list.length) {\n this.paymasters.set(userId, filtered);\n return true;\n }\n return false;\n }\n\n // ── BLS Config ───────────────────────────────────────────────\n\n async getBlsConfig(): Promise<BlsConfigRecord | null> {\n return this.blsConfig;\n }\n\n async updateSignerNodesCache(nodes: unknown[]): Promise<void> {\n this.blsConfig = {\n ...this.blsConfig,\n signerNodes: {\n nodes: nodes as BlsConfigRecord[\"signerNodes\"] extends { nodes: infer N } ? N : never,\n },\n } as BlsConfigRecord;\n }\n}\n","import { privateKeyToAccount, type PrivateKeyAccount } from \"viem/accounts\";\nimport { ISignerAdapter, PasskeyAssertionContext } from \"../interfaces/signer-adapter\";\n\n/**\n * Local wallet signer — backs all users with a single private key.\n * Suitable for testing, demos, and single-tenant server setups.\n *\n * For multi-tenant production use, implement ISignerAdapter with\n * per-user key management (e.g., KMS, HSM, or encrypted database).\n */\nexport class LocalWalletSigner implements ISignerAdapter {\n private readonly account: PrivateKeyAccount;\n\n constructor(privateKey: string) {\n this.account = privateKeyToAccount(privateKey as `0x${string}`);\n }\n\n async getAddress(_userId: string): Promise<`0x${string}`> {\n return this.account.address;\n }\n\n async signMessage(\n _userId: string,\n message: `0x${string}` | Uint8Array,\n _ctx?: PasskeyAssertionContext\n ): Promise<`0x${string}`> {\n // EIP-191 personal-sign over raw bytes — identical to\n // ethers `wallet.signMessage(bytes)`. `{ raw }` signs the bytes as-is\n // (no UTF-8 reinterpretation of a 0x hex digest).\n return this.account.signMessage({ message: { raw: message } });\n }\n\n async ensureSigner(_userId: string): Promise<{ address: `0x${string}` }> {\n return { address: this.account.address };\n }\n}\n"]}
1
+ {"version":3,"sources":["../../airaccount/src/server/constants/entrypoint.ts","../../airaccount/src/server/config.ts","../../airaccount/src/server/interfaces/logger.ts","../../airaccount/src/server/providers/ethereum-provider.ts","../../airaccount/src/server/providers/typed-reads.ts","../../airaccount/src/server/services/account-init-config.ts","../../airaccount/src/server/services/account-manager.ts","../../airaccount/src/server/utils/execute-user-op.ts","../../airaccount/src/server/services/paymaster-manager.ts","../../airaccount/src/server/services/transfer-manager.ts","../../airaccount/src/server/services/bls-signature-service.ts","../../airaccount/src/server/services/token-service.ts","../../airaccount/src/server/services/wallet-manager.ts","../../airaccount/src/server/server-client.ts","../../airaccount/src/migration/viem/signatures.ts","../../airaccount/src/server/services/module-manager.ts","../../airaccount/src/server/services/session-key-service.ts","../../airaccount/src/server/services/guard-state-reader.ts","../../airaccount/src/server/utils/oapd.ts","../../airaccount/src/server/services/guard-checker.ts","../../airaccount/src/server/services/force-exit-service.ts","../../airaccount/src/server/services/recovery-service.ts","../../airaccount/src/server/services/eip7702-delegate-service.ts","../../airaccount/src/server/services/weighted-signature-service.ts","../../airaccount/src/server/services/agent-registry-service.ts","../../airaccount/src/server/services/erc8004-service.ts","../../airaccount/src/server/services/kms-http-client.ts","../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/nist.ts","../../airaccount/src/server/services/webauthn-ceremony.ts","../../airaccount/src/server/services/kms-signer.ts","../../airaccount/src/server/services/kms-agent-service.ts","../../airaccount/src/server/services/kms-session-service.ts","../../airaccount/src/server/services/kms-payment-signer.ts","../../airaccount/src/server/services/kms-monitor-service.ts","../../airaccount/src/server/adapters/memory-storage.ts","../../airaccount/src/server/adapters/local-wallet-signer.ts"],"names":["EntryPointVersion","parseAbi","getContract","concat","zeroAddress","ZERO32","EMPTY_P256","encodeFunctionData","numberToHex","parseEther","hexToBytes","parseUnits","viemHashMessage","viemRecoverAddress","keccak256","AIRACCOUNT_ABI_PARSED","FACTORY_ABI","ACCOUNT_ABI","axios","http"],"mappings":";;;;;;;;;AAMA,IAAM,YAAA,GAAe,oBAAoB,QAAQ,CAAA;AAE1C,IAAK,iBAAA,qBAAAA,kBAAAA,KAAL;AACL,EAAAA,mBAAA,MAAA,CAAA,GAAO,KAAA;AACP,EAAAA,mBAAA,MAAA,CAAA,GAAO,KAAA;AACP,EAAAA,mBAAA,MAAA,CAAA,GAAO,KAAA;AAHG,EAAA,OAAAA,kBAAAA;AAAA,CAAA,EAAA,iBAAA,IAAA,EAAA;AAcL,IAAM,oBAAA,GAAuB;AAAA,EAClC,CAAC,mBAAyB;AAAA,IACxB,OAAA,EAAS,4CAAA;AAAA,IACT,OAAA,EAAS,4CAAA;AAAA,IACT,QAAA,EA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AAS,MAAA,GAAS,IAAA,CAAK,MAAA,EAAQ;AACjC,MAAA,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,MAAA,EAAQ,QAAQ,CAAA;AACpC,MAAA,OAAO,IAAA;AAAA,IACT;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AAAA;AAAA,EAIA,MAAM,YAAA,GAAgD;AACpD,IAAA,OAAO,IAAA,CAAK,SAAA;AAAA,EACd;AAAA,EAEA,MAAM,uBAAuB,KAAA,EAAiC;AAC5D,IAAA,IAAA,CAAK,SAAA,GAAY;AAAA,MACf,GAAG,IAAA,CAAK,SAAA;AAAA,MACR,WAAA,EAAa;AAAA,QACX;AAAA;AACF,KACF;AAAA,EACF;AACF;AC3FO,IAAM,oBAAN,MAAkD;AAAA,EACtC,OAAA;AAAA,EAEjB,YAAY,UAAA,EAAoB;AAC9B,IAAA,IAAA,CAAK,OAAA,GAAU,oBAAoB,UAA2B,CAAA;AAAA,EAChE;AAAA,EAEA,MAAM,WAAW,OAAA,EAAyC;AACxD,IAAA,OAAO,KAAK,OAAA,CAAQ,OAAA;AAAA,EACtB;AAAA,EAEA,MAAM,WAAA,CACJ,OAAA,EACA,OAAA,EACA,IAAA,EACwB;AAIxB,IAAA,OAAO,IAAA,CAAK,QAAQ,WAAA,CAAY,EAAE,SAAS,EAAE,GAAA,EAAK,OAAA,EAAQ,EAAG,CAAA;AAAA,EAC/D;AAAA,EAEA,MAAM,aAAa,OAAA,EAAsD;AACvE,IAAA,OAAO,EAAE,OAAA,EAAS,IAAA,CAAK,OAAA,CAAQ,OAAA,EAAQ;AAAA,EACzC;AACF","file":"chunk-BPAAWQQA.js","sourcesContent":["import { CANONICAL_ADDRESSES } from \"@aastar/core\";\n\n// Single source of truth: derive AirAccount's CURRENT (non-deprecated) Sepolia\n// contract addresses from @aastar/core's CANONICAL_ADDRESSES. core is the\n// foundation package and never imports airaccount, so there is no circular dep.\n// See AIRACCOUNT_ADDRESSES below for the per-field key mapping.\nconst CORE_SEPOLIA = CANONICAL_ADDRESSES[11155111];\n\nexport enum EntryPointVersion {\n V0_6 = \"0.6\",\n V0_7 = \"0.7\",\n V0_8 = \"0.8\",\n}\n\nexport interface EntryPointConfig {\n version: EntryPointVersion;\n address: string;\n factoryAddress: string;\n validatorAddress: string;\n}\n\n/** Default EntryPoint addresses (same on Sepolia, Mainnet, and OP Mainnet). */\nexport const ENTRYPOINT_ADDRESSES = {\n [EntryPointVersion.V0_6]: {\n sepolia: \"0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789\",\n mainnet: \"0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789\",\n optimism: \"0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789\",\n },\n [EntryPointVersion.V0_7]: {\n sepolia: \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\",\n mainnet: \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\",\n optimism: \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\",\n },\n [EntryPointVersion.V0_8]: {\n sepolia: \"0x0576a174D229E3cFA37253523E645A78A0C91B57\",\n mainnet: \"0x0576a174D229E3cFA37253523E645A78A0C91B57\",\n optimism: \"0x0576a174D229E3cFA37253523E645A78A0C91B57\",\n },\n};\n\nexport const ENTRYPOINT_ABI_V6 = [\n \"function simulateValidation((address,uint256,bytes,bytes,uint256,uint256,uint256,uint256,uint256,bytes,bytes) userOp) external\",\n \"function getNonce(address sender, uint192 key) external view returns (uint256 nonce)\",\n \"function getUserOpHash((address,uint256,bytes,bytes,uint256,uint256,uint256,uint256,uint256,bytes,bytes) userOp) external view returns (bytes32)\",\n \"function handleOps((address,uint256,bytes,bytes,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[] ops, address payable beneficiary) external\",\n];\n\nexport const ENTRYPOINT_ABI_V7_V8 = [\n \"function simulateValidation((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes) packedUserOp) external\",\n \"function getNonce(address sender, uint192 key) external view returns (uint256 nonce)\",\n \"function getUserOpHash((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes) packedUserOp) external view returns (bytes32)\",\n \"function handleOps((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes)[] ops, address payable beneficiary) external\",\n];\n\nexport const FACTORY_ABI_V6 = [\n \"function getAddress(address creator, address signer, address validator, bool useAAStarValidator, uint256 salt) view returns (address)\",\n \"function createAccountWithAAStarValidator(address creator, address signer, address aaStarValidator, bool useAAStarValidator, uint256 salt) returns (address)\",\n];\n\nexport const FACTORY_ABI_V7_V8 = [\n \"function getAddress(address creator, address signer, address validator, bool useAAStarValidator, uint256 salt) view returns (address)\",\n \"function createAccount(address creator, address signer, address aaStarValidator, bool useAAStarValidator, uint256 salt) returns (address)\",\n];\n\nexport const ACCOUNT_ABI = [\n \"function execute(address dest, uint256 value, bytes calldata func) external\",\n];\n\nexport const VALIDATOR_ABI = [\n \"function getGasEstimate(uint256 nodeCount) external pure returns (uint256 gasEstimate)\",\n];\n\n// ── AirAccount Contract Addresses (Sepolia) ──────────────────────\n\nexport const AIRACCOUNT_ADDRESSES = {\n sepolia: {\n // M4 factory (legacy — 3-field InitConfig)\n factoryM4: \"0x914db0a849f55e68a726c72fd02b7114b1176d88\",\n // M5 factory r5 — 6-field InitConfig, guardian acceptance sigs required\n factoryM5: \"0xd72a236d84be6c388a8bc7deb64afd54704ae385\",\n /** @deprecated defaultCommunityGuardian was address(0); superseded by r6 and r4. Do not use for new accounts. */\n factoryM7r5Prev: \"0xa0007c5dB27548D8c1582773856dB1D123107383\",\n\n // ── Deprecated: r6 addresses (2026-03-29 deployment, superseded by r4 audit-final) ──────────\n // Retain for legacy account lookups and historical event indexing ONLY.\n // DO NOT use for new account creation — CREATE2 address will differ from r4.\n /** @deprecated Use {@link factory} (r4 audit-final) for new accounts. */\n factoryM7r6: \"0x42f82d77f9cf940686b6a64a369245cb563e0e85\",\n /** @deprecated Use {@link accountImpl} (r4 audit-final). */\n accountImplM7r6: \"0x2F1B4EB63143D338bE78d0AF878B806f075080c1\",\n /** @deprecated Use {@link compositeValidator} (r4 audit-final). */\n compositeValidatorM7r6: \"0x4135c539fec5e200fe9762b721f6829b2315cbe1\",\n /** @deprecated Use {@link tierGuardHook} (r4 audit-final). */\n tierGuardHookM7r6: \"0x73572e9e6138fd53465ee243e2fb4842cf86a787\",\n /** @deprecated Use {@link agentSessionKeyValidator} (r4 audit-final). */\n agentSessionKeyValidatorM7r6: \"0xa3e52db4b6e0a9d7cd5dd1414a90eedcf950e029\",\n\n // ── Deprecated: r4 audit-final (v0.16.0 era — pre-beta). Retained for existing account recovery. ─\n /** @deprecated Use factory (beta.4) for new accounts. */\n factoryM7r4: \"0x61bBAf9E1b8Fd78fF874776cFa50497dB9d43C3F\",\n /** @deprecated */\n accountImplM7r4: \"0xA674D308ce22230B70412b20Ee5a66fC6B24F49c\",\n /** @deprecated Use validatorRouter. */\n validatorRouterM7r4: \"0x730a162Ce3202b94cC5B74181B75b11eBB3045B1\",\n /** @deprecated */\n compositeValidatorM7r4: \"0xB65569950C48AA56dbe876915ca3605fD6FF2980\",\n /** @deprecated */\n tierGuardHookM7r4: \"0x67f878295cFF7451CBD2A775C4490607AF1b07d7\",\n /** @deprecated */\n agentSessionKeyValidatorM7r4: \"0x1F06961e133217801F92e1CF552187F594a32873\",\n\n // ── Current: derived from @aastar/core CANONICAL_ADDRESSES[11155111] ───────────\n // SINGLE SOURCE OF TRUTH. Do NOT hand-copy hex here. core is synced on every\n // protocol redeploy (currently AirAccount v0.20.0, Sepolia 2026-06-20),\n // and these fields re-derive automatically. The key mapping (airaccount field ←\n // core key) is asserted by entrypoint.addresses.test.ts so it can't silently drift.\n factory: CORE_SEPOLIA.airAccountFactoryV7,\n factoryM7: CORE_SEPOLIA.airAccountFactoryV7,\n accountImpl: CORE_SEPOLIA.airAccountV7Impl,\n validatorRouter: CORE_SEPOLIA.aaStarValidator,\n blsAlgorithm: CORE_SEPOLIA.aaStarBLSAlgorithm,\n blsAggregator: CORE_SEPOLIA.aaStarBLSAggregator,\n // SuperPaymaster proxy — same concept as core's `superPaymaster` proxy.\n superPaymaster: CORE_SEPOLIA.superPaymaster,\n sessionKeyValidator: CORE_SEPOLIA.sessionKeyValidator,\n forceExitModule: CORE_SEPOLIA.forceExitModule,\n airAccountDelegate: CORE_SEPOLIA.airAccountDelegate,\n airAccountExtension: CORE_SEPOLIA.airAccountExtension,\n agentRegistry: CORE_SEPOLIA.agentRegistry,\n calldataParserRegistry: CORE_SEPOLIA.calldataParserRegistry,\n // uniswapV3Parser is airaccount-specific (not in core) — keep hardcoded.\n uniswapV3Parser: \"0x5671810ac8aa1857397870e60232579cfc519515\",\n },\n};\n\n// ── AirAccount ABIs ──────────────────────────────────────────────\n\nexport const AIRACCOUNT_ABI = [\n // ── Core execution ──\n \"function execute(address dest, uint256 value, bytes calldata func) external\",\n \"function executeBatch(address[] calldata dest, uint256[] calldata value, bytes[] calldata func) external\",\n // ── ERC-7579 Module Management (M7.2) ──\n \"function installModule(uint256 moduleTypeId, address module, bytes calldata initData) external\",\n \"function uninstallModule(uint256 moduleTypeId, address module, bytes calldata deInitData) external\",\n \"function executeFromExecutor(bytes32 mode, bytes calldata executionCalldata) external returns (bytes[] memory returnData)\",\n // ── ERC-7579 Introspection ──\n \"function accountId() external pure returns (string memory)\",\n \"function supportsModule(uint256 moduleTypeId) external pure returns (bool)\",\n \"function isModuleInstalled(uint256 moduleTypeId, address module, bytes calldata additionalContext) external view returns (bool)\",\n // ── ERC-1271 / ERC-165 ──\n \"function isValidSignature(bytes32 hash, bytes calldata sig) external view returns (bytes4)\",\n \"function validateCompositeSignature(bytes32 hash, bytes calldata sig) external returns (uint256)\",\n \"function supportsInterface(bytes4 interfaceId) external pure returns (bool)\",\n // ── State readers ──\n \"function owner() external view returns (address)\",\n \"function entryPoint() external view returns (address)\",\n \"function validator() external view returns (address)\",\n \"function guard() external view returns (address)\",\n \"function guardianCount() external view returns (uint8)\",\n \"function guardians(uint256 index) external view returns (address)\",\n \"function p256KeyX() external view returns (bytes32)\",\n \"function p256KeyY() external view returns (bytes32)\",\n // abitype/viem human-readable ABIs use a bare parenthesised tuple `(...)`, not the\n // ethers-style `tuple(...)` keyword (which parseAbi rejects with \"Invalid ABI parameter\").\n \"function getConfigDescription() external view returns ((address accountOwner, address guardAddress, uint256 dailyLimit, uint256 dailyRemaining, uint256 tier1Limit, uint256 tier2Limit, address[3] guardianAddresses, uint8 guardianCount, bool hasP256Key, bool hasValidator, bool hasAggregator, bool hasActiveRecovery))\",\n // ── Owner / key management ──\n \"function setValidator(address _validator) external\",\n \"function setP256Key(bytes32 _x, bytes32 _y) external\",\n \"function setTierLimits(uint256 _tier1, uint256 _tier2) external\",\n \"function modifyTierLimitsWithGuardians(uint256 _tier1, uint256 _tier2, uint256 deadline, bytes[] calldata guardianSigs) external\",\n // ── Algorithm whitelist (v0.17.2-beta.4: single source of truth on the ACCOUNT, not the guard) ──\n \"function approvedAlgorithms(uint8 algId) external view returns (bool)\",\n \"function guardApproveAlgorithm(uint8 algId) external\",\n // ── Social / guardian recovery (F28) ──\n // Guardian set: owner adds guardians (max 3); removal needs RECOVERY_THRESHOLD guardian sigs.\n // Recovery lifecycle: a guardian proposes a new owner (starts the timelock), guardians\n // approve to reach 2-of-3 threshold, then anyone executes after the timelock; guardians\n // (not the owner) can vote to cancel. See RecoveryService for the full flow.\n \"function addGuardian(address _guardian) external\",\n \"function removeGuardian(uint8 index, bytes[] calldata guardianSigs) external\",\n \"function proposeRecovery(address _newOwner) external\",\n \"function approveRecovery() external\",\n \"function cancelRecovery() external\",\n \"function executeRecovery() external\",\n \"function activeRecovery() external view returns (address newOwner, uint256 proposedAt, uint256 approvalBitmap, uint256 cancellationBitmap)\",\n // ── Weighted-signature governance (algId 0x07) ──\n // WeightConfig tuple = (passkeyWeight, ecdsaWeight, blsWeight, guardian0Weight,\n // guardian1Weight, guardian2Weight, _padding, tier1Threshold, tier2Threshold, tier3Threshold)\n \"function setWeightConfig((uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold) config) external\",\n \"function proposeWeightChange((uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold) proposed) external\",\n \"function approveWeightChange() external\",\n \"function cancelWeightChange() external\",\n \"function executeWeightChange() external\",\n \"function weightConfig() external view returns (uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold)\",\n \"function pendingWeightChange() external view returns ((uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold) proposed, uint256 proposedAt, uint256 approvalBitmap)\",\n // ── ERC-4337 v0.7 bundler entrypoint (v0.17.2-beta.4) ──\n // Routes a UserOp whose callData starts with the executeUserOp selector to the account,\n // re-deriving the signature algId in-frame (fixes guard-account bundler gas estimation).\n // Only an inner execute()/executeBatch() may be wrapped (else reverts UnsupportedInnerSelector).\n \"function executeUserOp((address sender, uint256 nonce, bytes initCode, bytes callData, bytes32 accountGasLimits, uint256 preVerificationGas, bytes32 gasFees, bytes paymasterAndData, bytes signature) userOp, bytes32 userOpHash) external\",\n // ── Events ──\n \"event ModuleInstalled(uint256 indexed moduleTypeId, address indexed module)\",\n \"event ModuleUninstalled(uint256 indexed moduleTypeId, address indexed module)\",\n \"event OwnerChanged(address indexed oldOwner, address indexed newOwner)\",\n // v0.20.0 (#120): recovery events gained a trailing `uint8 guardianIdx` naming the\n // authorizing guardian slot (on P-256 relayer-submitted paths msg.sender is the relayer,\n // not the guardian). topic0 of these three events changed — decoders must use the new shape.\n \"event RecoveryProposed(address indexed newOwner, address indexed proposedBy, uint8 guardianIdx)\",\n \"event RecoveryApproved(address indexed newOwner, address indexed approvedBy, uint256 approvalCount, uint8 guardianIdx)\",\n \"event RecoveryCancelVoted(address indexed votedBy, uint256 cancelCount, uint8 guardianIdx)\",\n \"event RecoveryExecuted(address indexed oldOwner, address indexed newOwner)\",\n];\n\n// M7 factory ABI — ERC-7579 modules pre-installed, ERC-7828 chain-qualified addresses\n// v0.20.0 (#120): InitConfig inserted bytes32[3] guardianP256X, bytes32[3] guardianP256Y\n// (P-256 guardian keys) immediately after `address[3] guardians`. ECDSA-only accounts pass\n// [0x0,0x0,0x0] for both. Field ORDER is consensus-critical (CREATE2 address prediction).\n// InitConfig: (address[3] guardians, bytes32[3] guardianP256X, bytes32[3] guardianP256Y, uint256 dailyLimit, uint8[] approvedAlgIds, uint256 minDailyLimit, address[] initialTokens, (uint128 tier1Limit, uint128 tier2Limit, uint256 dailyLimit)[] initialTokenConfigs)\n// #118: TokenConfig packs tier1Limit/tier2Limit as uint128 (airaccount-contract #82) while dailyLimit\n// stays uint256. The selector is part of the type string, so even an EMPTY initialTokenConfigs must\n// declare (uint128,uint128,uint256) — declaring (uint256,uint256,uint256) yields the WRONG getAddress/\n// createAccount selector and reverts on the live v0.20.0 factory. Verified vs the canonical JSON ABI.\nexport const AIRACCOUNT_FACTORY_ABI = [\n // Full config creation\n \"function createAccount(address owner, uint256 salt, (address[3] guardians, bytes32[3] guardianP256X, bytes32[3] guardianP256Y, uint256 dailyLimit, uint8[] approvedAlgIds, uint256 minDailyLimit, address[] initialTokens, (uint128 tier1Limit, uint128 tier2Limit, uint256 dailyLimit)[] initialTokenConfigs) config) external returns (address)\",\n \"function getAddress(address owner, uint256 salt, (address[3] guardians, bytes32[3] guardianP256X, bytes32[3] guardianP256Y, uint256 dailyLimit, uint8[] approvedAlgIds, uint256 minDailyLimit, address[] initialTokens, (uint128 tier1Limit, uint128 tier2Limit, uint256 dailyLimit)[] initialTokenConfigs) config) external view returns (address)\",\n // Default guardian setup (requires guardian acceptance sigs — M5.3+)\n \"function createAccountWithDefaults(address owner, uint256 salt, address guardian1, bytes guardian1Sig, address guardian2, bytes guardian2Sig, uint256 dailyLimit) external returns (address)\",\n \"function getAddressWithDefaults(address owner, uint256 salt, address guardian1, address guardian2, uint256 dailyLimit) external view returns (address)\",\n // Agent-account creation (V7: agentKey + human-guardian2 co-owned account, registered in AgentRegistry)\n \"function createAgentAccount(address agentKey, bytes32 agentId, address guardian2, bytes guardian2Sig, bytes agentKeySig, uint48 deadline, uint256 dailyLimit) external returns (address account)\",\n \"function getAgentAddress(address humanOwner, address agentKey, bytes32 agentId) external view returns (address)\",\n \"function setAgentRegistry(address _agentRegistry) external\",\n \"function agentRegistry() external view returns (address)\",\n // M7 immutable state\n \"function implementation() external view returns (address)\",\n \"function entryPoint() external view returns (address)\",\n \"function defaultCommunityGuardian() external view returns (address)\",\n \"function defaultValidatorModule() external view returns (address)\",\n \"function defaultHookModule() external view returns (address)\",\n // M7.4 ERC-7828 chain-qualified address helpers\n \"function getChainQualifiedAddress(address account) external view returns (bytes32)\",\n \"function getAddressWithChainId(address owner, uint256 salt, (address[3] guardians, bytes32[3] guardianP256X, bytes32[3] guardianP256Y, uint256 dailyLimit, uint8[] approvedAlgIds, uint256 minDailyLimit, address[] initialTokens, (uint128 tier1Limit, uint128 tier2Limit, uint256 dailyLimit)[] initialTokenConfigs) config) external view returns (address account, bytes32 chainQualified)\",\n // Events\n \"event AccountCreated(address indexed account, address indexed owner, uint256 salt)\",\n];\n\n// v0.17.2-beta.4: the guard is now pure spend accounting. The algorithm whitelist\n// moved to the ACCOUNT (see AIRACCOUNT_ABI.approvedAlgorithms). checkTransaction/\n// checkTokenTransaction were renamed to recordSpend/recordTokenSpend, and\n// approveAlgorithm/approvedAlgorithms/AlgorithmNotApproved were removed from the guard.\nexport const GLOBAL_GUARD_ABI = [\n \"function remainingDailyAllowance() external view returns (uint256)\",\n \"function dailyLimit() external view returns (uint256)\",\n \"function account() external view returns (address)\",\n // Spend accounting (record* — algId dropped from the ETH path; kept for per-token tier math)\n \"function recordSpend(uint256 value) external returns (bool)\",\n \"function recordTokenSpend(address token, uint256 amount, uint8 algId) external returns (bool)\",\n];\n\nexport const ERC20_ABI = [\n \"function name() view returns (string)\",\n \"function symbol() view returns (string)\",\n \"function decimals() view returns (uint8)\",\n \"function totalSupply() view returns (uint256)\",\n \"function balanceOf(address owner) view returns (uint256)\",\n \"function transfer(address to, uint256 amount) returns (bool)\",\n \"function allowance(address owner, address spender) view returns (uint256)\",\n \"function approve(address spender, uint256 amount) returns (bool)\",\n];\n\n// ── M7 Module ABIs ───────────────────────────────────────────────\n\n// AgentSessionKeyValidator — ERC-7579 Validator module for AI agent capability delegation.\n// Supports velocity limits, selector allowlists, spend caps, and hierarchical delegation chains.\nexport const AGENT_SESSION_KEY_VALIDATOR_ABI = [\n // ERC-7579 lifecycle\n \"function onInstall(bytes calldata data) external\",\n \"function onUninstall(bytes calldata data) external\",\n \"function isInitialized(address smartAccount) external view returns (bool)\",\n // Session management\n \"function grantAgentSession(address sessionKey, (uint48 expiry, uint16 velocityLimit, uint32 velocityWindow, bool revoked, address[] callTargets, bytes4[] selectorAllowlist) cfg) external\",\n \"function delegateSession(address account, address subKey, (uint48 expiry, uint16 velocityLimit, uint32 velocityWindow, bool revoked, address[] callTargets, bytes4[] selectorAllowlist) subCfg) external\",\n \"function revokeAgentSession(address sessionKey) external\",\n // Validation\n \"function validateUserOp((address sender, uint256 nonce, bytes initCode, bytes callData, bytes32 accountGasLimits, uint256 preVerificationGas, bytes32 gasFees, bytes paymasterAndData, bytes signature) userOp, bytes32 userOpHash) external returns (uint256 validationData)\",\n \"function isValidSignatureWithSender(address sender, bytes32 hash, bytes calldata data) external pure returns (bytes4)\",\n // Enforcement\n \"function enforceSessionScope(address account, address sessionKey, address callTarget, bytes4 selector) external view\",\n // State readers\n \"function agentSessions(address account, address sessionKey) external view returns (uint48 expiry, uint16 velocityLimit, uint32 velocityWindow, bool revoked, address[] memory callTargets, bytes4[] memory selectorAllowlist)\",\n \"function sessionStates(address account, address sessionKey) external view returns (uint256 callCount, uint256 windowStart)\",\n \"function sessionKeyOwner(address sessionKey) external view returns (address)\",\n \"function delegatedBy(address account, address subKey) external view returns (address parentKey)\",\n // Events\n \"event AgentSessionGranted(address indexed account, address indexed sessionKey, uint48 expiry)\",\n \"event AgentSessionRevoked(address indexed account, address indexed sessionKey)\",\n \"event AgentSessionDelegated(address indexed parentAccount, address indexed parentKey, address indexed subKey, uint48 expiry)\",\n];\n\n// TierGuardHook — ERC-7579 Hook module wrapping tier-based spending enforcement.\n// Enforces per-execution ETH/token tier limits via preCheck/postCheck hooks.\nexport const TIER_GUARD_HOOK_ABI = [\n // ERC-7579 lifecycle\n \"function onInstall(bytes calldata data) external\",\n \"function onUninstall(bytes calldata data) external\",\n \"function isInitialized(address smartAccount) external view returns (bool)\",\n // ERC-7579 Hook interface\n \"function preCheck(address msgSender, uint256 msgValue, bytes calldata msgData) external returns (bytes memory hookData)\",\n \"function postCheck(bytes calldata hookData) external\",\n // State readers\n \"function accountGuard(address account) external view returns (address)\",\n \"function accountTier1(address account) external view returns (uint256)\",\n \"function accountTier2(address account) external view returns (uint256)\",\n];\n\n// AirAccountCompositeValidator — ERC-7579 Validator merging weighted + cumulative T2/T3 signature schemes.\n// Routes validation to the account's built-in algId dispatch via nonce-key routing.\nexport const AIR_ACCOUNT_COMPOSITE_VALIDATOR_ABI = [\n // ERC-7579 lifecycle\n \"function onInstall(bytes calldata data) external\",\n \"function onUninstall(bytes calldata data) external\",\n \"function isInitialized(address smartAccount) external view returns (bool)\",\n // ERC-7579 Validator interface\n \"function validateUserOp((address sender, uint256 nonce, bytes initCode, bytes callData, bytes32 accountGasLimits, uint256 preVerificationGas, bytes32 gasFees, bytes paymasterAndData, bytes signature) userOp, bytes32 userOpHash) external returns (uint256 validationData)\",\n \"function isValidSignatureWithSender(address sender, bytes32 hash, bytes calldata data) external view returns (bytes4 magicValue)\",\n];\n\n// ForceExitModule — ERC-7579 Executor module for guardian-gated L2→L1 emergency withdrawals.\n// Requires 2-of-3 guardian approvals before executing the force exit.\nexport const FORCE_EXIT_MODULE_ABI = [\n // ERC-7579 lifecycle\n \"function onInstall(bytes calldata data) external\",\n \"function onUninstall(bytes calldata data) external\",\n \"function isInitialized(address smartAccount) external view returns (bool)\",\n // Force exit flow\n \"function proposeForceExit(address target, uint256 value, bytes calldata data) external\",\n \"function approveForceExit(address account, bytes calldata guardianSig) external\",\n \"function executeForceExit(address account) external\",\n \"function cancelForceExit(address account) external\",\n // State readers\n \"function accountL2Type(address account) external view returns (uint8)\",\n \"function getPendingExit(address account) external view returns (address target, uint256 value, bytes memory data, uint256 proposedAt, uint256 approvalBitmap, address[3] memory guardians)\",\n // Events\n \"event ExitProposed(address indexed account, address indexed target, uint256 value)\",\n \"event ExitApproved(address indexed account, address indexed guardian, uint256 bitmap)\",\n \"event ExitExecuted(address indexed account, address indexed target, uint256 value)\",\n \"event ExitCancelled(address indexed account)\",\n];\n\n// ERC-7579 Module type IDs (spec: 1=validator, 2=executor, 3=fallback, 4=hook)\nexport const MODULE_TYPE = {\n VALIDATOR: 1,\n EXECUTOR: 2,\n FALLBACK: 3,\n HOOK: 4,\n} as const;\n\n// AirAccount algorithm IDs (algId values for signature dispatch)\nexport const ALG_ID = {\n BLS: 0x01,\n ECDSA: 0x02,\n P256: 0x03,\n CUMULATIVE_T2: 0x04, // P256 + BLS\n CUMULATIVE_T3: 0x05, // P256 + BLS + Guardian ECDSA\n COMBINED_T1: 0x06, // P256 AND ECDSA simultaneously\n WEIGHTED: 0x07, // Weighted multi-signature\n SESSION_KEY: 0x08, // Time-limited session key (SessionKeyValidator)\n AGENT_SESSION_KEY: 0x09, // AI agent session key (AgentSessionKeyValidator)\n} as const;\n\n// ── M6 继承合约 ABIs ─────────────────────────────────────────────\n\n// SessionKeyValidator — M6 基础 session key(algId=0x08)\n// 支持 ECDSA + P256 两种 session key,带合约/selector 作用域限制\nexport const SESSION_KEY_VALIDATOR_ABI = [\n // Session struct (8 fields) — authoritative tuple shape from\n // airaccount-contract/src/validators/SessionKeyValidator.sol and\n // packages/core/src/abis/SessionKeyValidator.json. The grant/build/read\n // functions take/return this tuple as a single arg — NOT flat params.\n // Canonical tuple type: (uint48,address,bytes4,bool,uint16,uint32,address[],bytes4[])\n // ECDSA session key\n \"function grantSession(address account, address sessionKey, (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist) cfg, bytes calldata ownerSig) external\",\n \"function grantSessionDirect(address account, address sessionKey, (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist) cfg) external\",\n \"function revokeSession(address account, address sessionKey) external\",\n \"function isSessionActive(address account, address sessionKey) external view returns (bool)\",\n \"function getSession(address account, address sessionKey) external view returns ((uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist))\",\n \"function buildGrantHash(address account, address sessionKey, (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist) cfg) external view returns (bytes32)\",\n // P256 session key\n \"function grantP256Session(address account, bytes32 p256KeyX, bytes32 p256KeyY, (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist) cfg, bytes calldata ownerSig) external\",\n \"function grantP256SessionDirect(address account, bytes32 p256KeyX, bytes32 p256KeyY, (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist) cfg) external\",\n \"function revokeP256Session(address account, bytes32 p256KeyX, bytes32 p256KeyY) external\",\n \"function isP256SessionActive(address account, bytes32 p256KeyX, bytes32 p256KeyY) external view returns (bool)\",\n \"function getP256Session(address account, bytes32 p256KeyHash) external view returns ((uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist))\",\n \"function buildP256GrantHash(address account, bytes32 p256KeyX, bytes32 p256KeyY, (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked, uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist) cfg) external view returns (bytes32)\",\n // Events\n \"event SessionGranted(address indexed account, address indexed sessionKey, uint48 expiry, address contractScope, bytes4 selectorScope)\",\n \"event SessionRevoked(address indexed account, address indexed sessionKey)\",\n \"event P256SessionGranted(address indexed account, bytes32 indexed p256KeyHash, uint48 expiry)\",\n \"event P256SessionRevoked(address indexed account, bytes32 indexed p256KeyHash)\",\n];\n\n// CalldataParserRegistry — DeFi 协议解析器注册表\n// 让 guard 能识别 Uniswap/Railgun 等协议的 calldata,精确核算 token 消费\nexport const CALLDATA_PARSER_REGISTRY_ABI = [\n \"function registerParser(address dest, address parser) external\",\n \"function getParser(address dest) external view returns (address)\",\n \"function transferOwnership(address newOwner) external\",\n \"function parserFor(address dest) external view returns (address)\",\n \"event ParserRegistered(address indexed dest, address indexed parser)\",\n \"event OwnershipTransferred(address indexed previousOwner, address indexed newOwner)\",\n];\n\n// AirAccountDelegate — EIP-7702 EOA 委托为 AirAccount(M7 新增)\n// EOA 通过 EIP-7702 授权后,调用 initialize() 即获得 AirAccount 能力\nexport const AIR_ACCOUNT_DELEGATE_ABI = [\n // EIP-7702 初始化(仅限 EOA 自身调用)\n \"function initialize(address guardian1, bytes calldata g1Sig, address guardian2, bytes calldata g2Sig, uint256 dailyLimit) external\",\n // ERC-4337 执行\n \"function validateUserOp((address sender, uint256 nonce, bytes initCode, bytes callData, bytes32 accountGasLimits, uint256 preVerificationGas, bytes32 gasFees, bytes paymasterAndData, bytes signature) userOp, bytes32 userOpHash, uint256 missingAccountFunds) external returns (uint256)\",\n \"function execute(address dest, uint256 value, bytes calldata data) external\",\n \"function executeBatch(address[] calldata dest, uint256[] calldata value, bytes[] calldata data) external\",\n // 社会恢复(Rescue,EIP-7702 术语避免与 AirAccount Recovery 混淆)\n \"function initiateRescue(address rescueTo) external\",\n \"function approveRescue() external\",\n \"function executeRescue() external\",\n // Events\n \"event DelegateInitialized(address indexed eoa, address guard, address g1, address g2)\",\n \"event RescueInitiated(address indexed eoa, address rescueTo, address indexed initiator)\",\n \"event RescueApproved(address indexed eoa, address indexed guardian, uint8 approvals)\",\n \"event RescueExecuted(address indexed eoa, address rescueTo, uint256 ethAmount)\",\n \"event RescueCancelled(address indexed eoa)\",\n];\n","import { IStorageAdapter } from \"./interfaces/storage-adapter\";\nimport { ISignerAdapter } from \"./interfaces/signer-adapter\";\nimport { ILogger } from \"./interfaces/logger\";\nimport { AIRACCOUNT_ADDRESSES, ENTRYPOINT_ADDRESSES, EntryPointVersion } from \"./constants/entrypoint\";\n\n/**\n * Per-version EntryPoint configuration.\n */\nexport interface EntryPointVersionConfig {\n entryPointAddress: string;\n factoryAddress: string;\n validatorAddress: string;\n}\n\n/**\n * Server SDK configuration — replaces NestJS ConfigService.\n */\nexport interface ServerConfig {\n /** Main network RPC URL. */\n rpcUrl: string;\n /** Bundler RPC URL (e.g. Pimlico, StackUp). */\n bundlerRpcUrl: string;\n /** Chain ID of the target network. */\n chainId: number;\n\n /** EntryPoint configurations — at least one version must be provided. */\n entryPoints: {\n v06?: EntryPointVersionConfig;\n v07?: EntryPointVersionConfig;\n v08?: EntryPointVersionConfig;\n };\n\n /** Default EntryPoint version to use when not specified. */\n defaultVersion?: \"0.6\" | \"0.7\" | \"0.8\";\n\n /** BLS signer seed nodes for gossip discovery. */\n blsSeedNodes?: string[];\n /** Timeout for BLS node discovery in ms. */\n blsDiscoveryTimeout?: number;\n\n /** KMS endpoint URL (optional, for KMS-based signing). */\n kmsEndpoint?: string;\n /** Whether KMS signing is enabled. */\n kmsEnabled?: boolean;\n /** KMS API key for authenticated requests. */\n kmsApiKey?: string;\n\n /** Storage adapter (required). */\n storage: IStorageAdapter;\n /** Signer adapter (required). */\n signer: ISignerAdapter;\n /** Logger (optional, defaults to ConsoleLogger). */\n logger?: ILogger;\n}\n\n/** AirAccount contract version selection.\n * - \"M7\" — r4 audit-final (default). Use for all new account creation.\n * - \"M7r6\" — r6 deployment (2026-03-29, superseded). Use ONLY to recover existing r6-deployed accounts.\n * - \"M5\" — legacy 6-field InitConfig deployment.\n */\nexport type AirAccountVersion = \"M5\" | \"M7\" | \"M7r6\";\n\n/**\n * Build a pre-configured EntryPointVersionConfig for Sepolia using a known AirAccount deployment.\n * Eliminates the need to look up contract addresses manually.\n *\n * @example\n * // Use M7 r4 audit-final (default)\n * const config = { entryPoints: { v07: sepoliaV07Config() }, ... };\n *\n * // Recover an existing r6-deployed account (do NOT use for new accounts)\n * const config = { entryPoints: { v07: sepoliaV07Config(\"M7r6\") }, ... };\n *\n * // Use M5 legacy\n * const config = { entryPoints: { v07: sepoliaV07Config(\"M5\") }, ... };\n */\nexport function sepoliaV07Config(version: AirAccountVersion = \"M7\"): EntryPointVersionConfig {\n const factoryAddress =\n version === \"M5\"\n ? AIRACCOUNT_ADDRESSES.sepolia.factoryM5\n : version === \"M7r6\"\n ? AIRACCOUNT_ADDRESSES.sepolia.factoryM7r6\n : AIRACCOUNT_ADDRESSES.sepolia.factory; // \"M7\" = r4 audit-final (default)\n\n return {\n entryPointAddress: ENTRYPOINT_ADDRESSES[EntryPointVersion.V0_7].sepolia,\n factoryAddress,\n validatorAddress: AIRACCOUNT_ADDRESSES.sepolia.validatorRouter,\n };\n}\n\n/**\n * Validate a ServerConfig and throw descriptive errors for missing fields.\n */\nexport function validateConfig(config: ServerConfig): void {\n if (!config.rpcUrl) {\n throw new Error(\"ServerConfig: rpcUrl is required\");\n }\n if (!config.bundlerRpcUrl) {\n throw new Error(\"ServerConfig: bundlerRpcUrl is required\");\n }\n if (!config.chainId) {\n throw new Error(\"ServerConfig: chainId is required\");\n }\n\n const { entryPoints } = config;\n if (!entryPoints || (!entryPoints.v06 && !entryPoints.v07 && !entryPoints.v08)) {\n throw new Error(\"ServerConfig: at least one entryPoint version must be configured\");\n }\n\n for (const [key, ep] of Object.entries(entryPoints)) {\n if (ep) {\n if (!ep.entryPointAddress) {\n throw new Error(`ServerConfig: entryPoints.${key}.entryPointAddress is required`);\n }\n if (!ep.factoryAddress) {\n throw new Error(`ServerConfig: entryPoints.${key}.factoryAddress is required`);\n }\n if (!ep.validatorAddress) {\n throw new Error(`ServerConfig: entryPoints.${key}.validatorAddress is required`);\n }\n }\n }\n\n if (!config.storage) {\n throw new Error(\"ServerConfig: storage adapter is required\");\n }\n if (!config.signer) {\n throw new Error(\"ServerConfig: signer adapter is required\");\n }\n}\n","/**\n * Optional logger interface for server SDK.\n * Implement this to integrate with your application's logging framework.\n */\nexport interface ILogger {\n debug(message: string, ...args: unknown[]): void;\n log(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n}\n\n/**\n * Default console logger used when no custom logger is provided.\n */\nexport class ConsoleLogger implements ILogger {\n constructor(private readonly prefix: string = \"[YAAA]\") {}\n\n debug(message: string, ...args: unknown[]): void {\n console.debug(`${this.prefix} ${message}`, ...args);\n }\n\n log(message: string, ...args: unknown[]): void {\n console.log(`${this.prefix} ${message}`, ...args);\n }\n\n warn(message: string, ...args: unknown[]): void {\n console.warn(`${this.prefix} ${message}`, ...args);\n }\n\n error(message: string, ...args: unknown[]): void {\n console.error(`${this.prefix} ${message}`, ...args);\n }\n}\n\n/**\n * Silent logger that suppresses all output.\n */\nexport class SilentLogger implements ILogger {\n debug(): void {}\n log(): void {}\n warn(): void {}\n error(): void {}\n}\n","import {\n createPublicClient,\n http,\n getContract,\n formatEther,\n parseUnits,\n type PublicClient,\n type Address,\n type Abi,\n} from \"viem\";\n// EntryPoint/AirAccount ABIs are local human-readable signatures (not in @aastar/core);\n// parseAbi is required to feed them to viem's getContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { ServerConfig, EntryPointVersionConfig } from \"../config\";\nimport {\n EntryPointVersion,\n ENTRYPOINT_ABI_V6,\n ENTRYPOINT_ABI_V7_V8,\n FACTORY_ABI_V6,\n AIRACCOUNT_FACTORY_ABI,\n ACCOUNT_ABI,\n AIRACCOUNT_ABI,\n VALIDATOR_ABI,\n AGENT_SESSION_KEY_VALIDATOR_ABI,\n TIER_GUARD_HOOK_ABI,\n AIR_ACCOUNT_COMPOSITE_VALIDATOR_ABI,\n FORCE_EXIT_MODULE_ABI,\n AIRACCOUNT_ADDRESSES,\n} from \"../constants/entrypoint\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\nimport { UserOperation, PackedUserOperation } from \"../../core/types\";\n\n/**\n * A viem contract instance bound to a read-only PublicClient.\n *\n * The EntryPoint/AirAccount ABIs are loaded from human-readable signatures via\n * `parseAbi`, which yields the loosely-typed `Abi` shape. As a result `read`/`write`\n * method access is not statically typed per-function; callers index by name and the\n * returned value is `unknown` (cast at the call site). This mirrors the dynamic\n * surface that `ethers.Contract` previously exposed.\n */\nexport type ViemContractMethods = Record<string, (...args: unknown[]) => Promise<unknown>>;\nexport interface ViemContract {\n address: Address;\n abi: Abi;\n /** Read (view/pure) calls: `contract.read.fnName([...args])`. */\n read: ViemContractMethods;\n /** State-changing calls (requires a wallet client — not provided by this read-only hub). */\n write: ViemContractMethods;\n estimateGas: ViemContractMethods;\n simulate: ViemContractMethods;\n getEvents: ViemContractMethods;\n}\n\n/**\n * Unified Ethereum provider — replaces NestJS EthereumService.\n * Manages RPC + Bundler clients (viem) and contract interactions.\n */\nexport class EthereumProvider {\n /** Main-network read client. Pass to viem getContract / readContract calls. */\n private readonly provider: PublicClient;\n /** Bundler client — used only for raw eth_ / pimlico_ userOp JSON-RPC. */\n private readonly bundlerProvider: PublicClient;\n private readonly config: ServerConfig;\n private readonly logger: ILogger;\n\n constructor(config: ServerConfig) {\n this.config = config;\n this.logger = config.logger ?? new ConsoleLogger(\"[EthereumProvider]\");\n this.provider = createPublicClient({ transport: http(config.rpcUrl) });\n this.bundlerProvider = createPublicClient({ transport: http(config.bundlerRpcUrl) });\n }\n\n /** Returns the viem PublicClient for the main network RPC. */\n getProvider(): PublicClient {\n return this.provider;\n }\n\n /** Returns the viem PublicClient bound to the bundler RPC (raw .request only). */\n getBundlerProvider(): PublicClient {\n return this.bundlerProvider;\n }\n\n /** EVM chain id from the validated ServerConfig (deterministic — no RPC round-trip). */\n getChainId(): number {\n return this.config.chainId;\n }\n\n /**\n * Raw bundler JSON-RPC call. The bundler exposes non-standard methods\n * (eth_sendUserOperation, pimlico_getUserOperationGasPrice, ...) that are not in\n * viem's typed RPC schema, so we go through the transport's request fn untyped.\n */\n private async bundlerRequest<T = unknown>(method: string, params: unknown[]): Promise<T> {\n return (await this.bundlerProvider.request({\n method: method as never,\n params: params as never,\n })) as T;\n }\n\n // ── Config helpers ──────────────────────────────────────────────\n\n private getVersionConfig(version: EntryPointVersion): EntryPointVersionConfig {\n const map: Record<EntryPointVersion, EntryPointVersionConfig | undefined> = {\n [EntryPointVersion.V0_6]: this.config.entryPoints.v06,\n [EntryPointVersion.V0_7]: this.config.entryPoints.v07,\n [EntryPointVersion.V0_8]: this.config.entryPoints.v08,\n };\n const versionConfig = map[version];\n if (!versionConfig) {\n throw new Error(`EntryPoint version ${version} is not configured`);\n }\n return versionConfig;\n }\n\n getEntryPointAddress(version: EntryPointVersion): string {\n return this.getVersionConfig(version).entryPointAddress;\n }\n\n getFactoryAddress(version: EntryPointVersion): string {\n return this.getVersionConfig(version).factoryAddress;\n }\n\n getValidatorAddress(version: EntryPointVersion): string {\n return this.getVersionConfig(version).validatorAddress;\n }\n\n getDefaultVersion(): EntryPointVersion {\n const v = this.config.defaultVersion;\n if (v === \"0.7\") return EntryPointVersion.V0_7;\n if (v === \"0.8\") return EntryPointVersion.V0_8;\n return EntryPointVersion.V0_6;\n }\n\n // ── Contract factories ──────────────────────────────────────────\n\n /** Build a read-only viem contract bound to the main-network PublicClient. */\n private contractAt(address: string, abi: readonly string[]): ViemContract {\n return getContract({\n address: address as Address,\n abi: parseAbi(abi as readonly string[]),\n client: this.provider,\n }) as unknown as ViemContract;\n }\n\n getFactoryContract(version: EntryPointVersion = EntryPointVersion.V0_6): ViemContract {\n const address = this.getFactoryAddress(version);\n const abi = version === EntryPointVersion.V0_6 ? FACTORY_ABI_V6 : AIRACCOUNT_FACTORY_ABI;\n return this.contractAt(address, abi);\n }\n\n getEntryPointContract(version: EntryPointVersion = EntryPointVersion.V0_6): ViemContract {\n const address = this.getEntryPointAddress(version);\n const abi = version === EntryPointVersion.V0_6 ? ENTRYPOINT_ABI_V6 : ENTRYPOINT_ABI_V7_V8;\n return this.contractAt(address, abi);\n }\n\n getValidatorContract(version: EntryPointVersion = EntryPointVersion.V0_6): ViemContract {\n const address = this.getValidatorAddress(version);\n return this.contractAt(address, VALIDATOR_ABI);\n }\n\n getAccountContract(address: string): ViemContract {\n return this.contractAt(address, AIRACCOUNT_ABI);\n }\n\n // ── M7 Module contracts ─────────────────────────────────────────\n\n // M7 r4 module helpers — addresses renamed to *M7r4 suffix in beta.3 to avoid ambiguity.\n // These methods are retained for backwards compatibility; callers should pass an explicit address.\n getAgentSessionKeyValidatorContract(address: string = AIRACCOUNT_ADDRESSES.sepolia.agentSessionKeyValidatorM7r4): ViemContract {\n return this.contractAt(address, AGENT_SESSION_KEY_VALIDATOR_ABI);\n }\n\n getTierGuardHookContract(address: string = AIRACCOUNT_ADDRESSES.sepolia.tierGuardHookM7r4): ViemContract {\n return this.contractAt(address, TIER_GUARD_HOOK_ABI);\n }\n\n getCompositeValidatorContract(address: string = AIRACCOUNT_ADDRESSES.sepolia.compositeValidatorM7r4): ViemContract {\n return this.contractAt(address, AIR_ACCOUNT_COMPOSITE_VALIDATOR_ABI);\n }\n\n getForceExitModuleContract(address: string): ViemContract {\n return this.contractAt(address, FORCE_EXIT_MODULE_ABI);\n }\n\n // ── On-chain queries ────────────────────────────────────────────\n\n async getBalance(address: string): Promise<string> {\n const balance = await this.provider.getBalance({ address: address as Address });\n return formatEther(balance);\n }\n\n async getNonce(\n accountAddress: string,\n key: number = 0,\n version: EntryPointVersion = EntryPointVersion.V0_6\n ): Promise<bigint> {\n const entryPoint = this.getEntryPointContract(version);\n return (await (entryPoint.read as Record<string, (args: unknown[]) => Promise<unknown>>).getNonce([\n accountAddress as Address,\n BigInt(key),\n ])) as bigint;\n }\n\n async getUserOpHash(\n userOp: UserOperation | PackedUserOperation,\n version: EntryPointVersion = EntryPointVersion.V0_6\n ): Promise<string> {\n const entryPoint = this.getEntryPointContract(version);\n const read = entryPoint.read as Record<string, (args: unknown[]) => Promise<unknown>>;\n\n if (version === EntryPointVersion.V0_6) {\n const op = userOp as UserOperation;\n // uint256 fields coerced to bigint for viem (byte-identical to ethers' BigNumberish handling).\n const userOpArray = [\n op.sender,\n BigInt(op.nonce),\n op.initCode || \"0x\",\n op.callData,\n BigInt(op.callGasLimit),\n BigInt(op.verificationGasLimit),\n BigInt(op.preVerificationGas),\n BigInt(op.maxFeePerGas),\n BigInt(op.maxPriorityFeePerGas),\n op.paymasterAndData || \"0x\",\n \"0x\", // Always use empty signature for hash calculation\n ];\n return (await read.getUserOpHash([userOpArray])) as string;\n } else {\n const packedOp = userOp as PackedUserOperation;\n const packedOpArray = [\n packedOp.sender,\n BigInt(packedOp.nonce),\n packedOp.initCode || \"0x\",\n packedOp.callData,\n packedOp.accountGasLimits,\n BigInt(packedOp.preVerificationGas),\n packedOp.gasFees,\n packedOp.paymasterAndData || \"0x\",\n \"0x\",\n ];\n return (await read.getUserOpHash([packedOpArray])) as string;\n }\n }\n\n // ── Bundler RPC ─────────────────────────────────────────────────\n\n async estimateUserOperationGas(\n userOp: unknown,\n version: EntryPointVersion = EntryPointVersion.V0_6\n ): Promise<{ callGasLimit: string; verificationGasLimit: string; preVerificationGas: string }> {\n try {\n return await this.bundlerRequest(\"eth_estimateUserOperationGas\", [\n userOp,\n this.getEntryPointAddress(version),\n ]);\n } catch {\n return {\n callGasLimit: \"0x249f0\",\n verificationGasLimit: \"0x3d0900\", // 4M — enough for M4 factory deployment + BLS verification\n preVerificationGas: \"0x11170\",\n };\n }\n }\n\n async sendUserOperation(\n userOp: unknown,\n version: EntryPointVersion = EntryPointVersion.V0_6\n ): Promise<string> {\n return await this.bundlerRequest(\"eth_sendUserOperation\", [\n userOp,\n this.getEntryPointAddress(version),\n ]);\n }\n\n async getUserOperationReceipt(userOpHash: string): Promise<unknown> {\n return await this.bundlerRequest(\"eth_getUserOperationReceipt\", [userOpHash]);\n }\n\n async waitForUserOp(userOpHash: string, maxAttempts: number = 60): Promise<string> {\n const pollInterval = 2000;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n try {\n const receipt = (await this.getUserOperationReceipt(userOpHash)) as Record<\n string,\n unknown\n > | null;\n if (receipt) {\n const txHash =\n (receipt.transactionHash as string) ||\n ((receipt.receipt as Record<string, unknown>)?.transactionHash as string);\n if (txHash) return txHash;\n }\n } catch {\n // Continue polling\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error(`UserOp timeout: ${userOpHash}`);\n }\n\n async getUserOperationGasPrice(): Promise<{\n maxFeePerGas: string;\n maxPriorityFeePerGas: string;\n }> {\n try {\n const gasPrice = await this.bundlerRequest<{\n fast: { maxFeePerGas: string; maxPriorityFeePerGas: string };\n }>(\"pimlico_getUserOperationGasPrice\", []);\n return {\n maxFeePerGas: gasPrice.fast.maxFeePerGas,\n maxPriorityFeePerGas: gasPrice.fast.maxPriorityFeePerGas,\n };\n } catch {\n try {\n const feeData = await this.provider.estimateFeesPerGas();\n const baseFee = feeData.maxFeePerGas || parseUnits(\"20\", 9); // gwei\n const priorityFee = feeData.maxPriorityFeePerGas || parseUnits(\"2\", 9); // gwei\n const maxFeePerGas = (baseFee * 3n) / 2n;\n const maxPriorityFeePerGas = (priorityFee * 3n) / 2n;\n return {\n maxFeePerGas: \"0x\" + maxFeePerGas.toString(16),\n maxPriorityFeePerGas: \"0x\" + maxPriorityFeePerGas.toString(16),\n };\n } catch {\n return {\n maxFeePerGas: \"0x\" + parseUnits(\"3\", 9).toString(16), // gwei\n maxPriorityFeePerGas: \"0x\" + parseUnits(\"1\", 9).toString(16), // gwei\n };\n }\n }\n }\n}\n","import type { Address, Hex } from \"viem\";\nimport type { ViemContract } from \"./ethereum-provider\";\n\n/**\n * Audited boundary for HIGH-risk contract reads.\n *\n * Background: the ethers->viem migration loads the EntryPoint / AirAccount /\n * validator / guard ABIs from human-readable signatures via `parseAbi`, then\n * widens them to the loose `Abi` shape (`ViemContract.read` is a bare\n * `Record<string, (...args) => Promise<unknown>>`). On that surface a wrong\n * function name, a wrong argument type (e.g. a JS `number` where a `uint256`\n * `bigint` is required, which can silently truncate outside the 53-bit safe\n * range), or a wrong decode shape is NOT caught at compile time.\n *\n * This module confines every such cast to one reviewable place. It only wraps\n * reads whose result flows into a money-movement / signing / authorization\n * decision (per the risk framework): gas math that gets signed, the\n * counterfactual account address that holds funds, the guard / tier / algorithm\n * gates that allow or deny a transfer, and the grant hashes the account owner\n * signs to authorize a session key. Pure display / logging reads are\n * deliberately left on the loose surface to keep this boundary small.\n *\n * Each wrapper declares explicit parameter types (bigint for every uint256) and\n * an explicit return type next to the on-chain function name it targets, so the\n * single `as` cast is documented against the real ABI signature.\n */\n\n/** Resolve a loosely-typed read method by name. The only cast escape hatch. */\nfunction readFn(contract: ViemContract, name: string): (args: readonly unknown[]) => Promise<unknown> {\n return contract.read[name] as (args: readonly unknown[]) => Promise<unknown>;\n}\n\n// ── Validator: gas estimate folded into the signed UserOp gas budget ──────────\n\n/**\n * `getGasEstimate(uint256 nodeCount) view returns (uint256)`.\n * `nodeCount` MUST be a bigint — the loose surface would accept a JS number and\n * risk silent truncation for a uint256 arg.\n */\nexport function readValidatorGasEstimate(\n validator: ViemContract,\n nodeCount: bigint\n): Promise<bigint> {\n return readFn(validator, \"getGasEstimate\")([nodeCount]) as Promise<bigint>;\n}\n\n// ── Factory: counterfactual account address (= fund-custody address) ──────────\n\n/**\n * `getAddress(address owner, uint256 salt, InitConfig config) view returns (address)`.\n * The predicted address is where user funds are sent before deployment, so a\n * mistyped `salt` (uint256) would yield a different, unrecoverable address.\n */\nexport function readPredictedAddress(\n factory: ViemContract,\n owner: string,\n salt: bigint,\n config: readonly unknown[]\n): Promise<Address> {\n return readFn(factory, \"getAddress\")([owner, salt, config]) as Promise<Address>;\n}\n\n/**\n * `getAddressWithDefaults(address owner, uint256 salt, address guardian1,\n * address guardian2, uint256 dailyLimit) view returns (address)`.\n * Both `salt` and `dailyLimit` are uint256 and MUST be bigint.\n */\nexport function readPredictedAddressWithDefaults(\n factory: ViemContract,\n owner: string,\n salt: bigint,\n guardian1: string,\n guardian2: string,\n dailyLimit: bigint\n): Promise<Address> {\n return readFn(factory, \"getAddressWithDefaults\")([\n owner,\n salt,\n guardian1,\n guardian2,\n dailyLimit,\n ]) as Promise<Address>;\n}\n\n// ── Account: authorization gates consumed by GuardChecker.preCheck ────────────\n\n/**\n * `tier1Limit()` / `tier2Limit()` (both uint256). These resolve the transfer\n * tier -> signing algId, gating which algorithm may authorize the transfer.\n */\nexport async function readAccountTierLimits(\n account: ViemContract\n): Promise<{ tier1Limit: bigint; tier2Limit: bigint }> {\n const [tier1Limit, tier2Limit] = await Promise.all([\n readFn(account, \"tier1Limit\")([]) as Promise<bigint>,\n readFn(account, \"tier2Limit\")([]) as Promise<bigint>,\n ]);\n return { tier1Limit, tier2Limit };\n}\n\n/**\n * `approvedAlgorithms(uint8 algId) view returns (bool)`. Gates whether the\n * signing algorithm for the resolved tier is allowed to authorize the tx.\n * `algId` is a uint8 (small enum), so a JS number is the correct ABI type.\n */\nexport function readAlgorithmApproved(account: ViemContract, algId: number): Promise<boolean> {\n return readFn(account, \"approvedAlgorithms\")([algId]) as Promise<boolean>;\n}\n\n/**\n * `getConfigDescription()` -> named struct; we read only `guardAddress`, which\n * decides whether the per-account spending guard is enforced at all.\n */\nexport async function readAccountGuardAddress(account: ViemContract): Promise<Address> {\n const config = (await readFn(account, \"getConfigDescription\")([])) as { guardAddress: Address };\n return config.guardAddress;\n}\n\n// ── Guard: daily spend allowance gate ─────────────────────────────────────────\n\n/**\n * `dailyLimit()` / `remainingDailyAllowance()` (both uint256). These cap the\n * value that may move per day; comparing the wrong (mistyped) value would let an\n * over-limit transfer through the pre-check.\n */\nexport async function readGuardDailyAllowance(\n guard: ViemContract\n): Promise<{ dailyLimit: bigint; dailyRemaining: bigint }> {\n const [dailyLimit, dailyRemaining] = await Promise.all([\n readFn(guard, \"dailyLimit\")([]) as Promise<bigint>,\n readFn(guard, \"remainingDailyAllowance\")([]) as Promise<bigint>,\n ]);\n return { dailyLimit, dailyRemaining };\n}\n\n// ── SessionKeyValidator: grant hashes the account owner SIGNS ─────────────────\n\n/** The on-chain `Session` struct passed to the grant-hash builders. */\nexport interface SessionGrantConfig {\n expiry: number;\n contractScope: string;\n selectorScope: string;\n revoked: boolean;\n velocityLimit: number;\n velocityWindow: number;\n callTargets: string[];\n selectorAllowlist: string[];\n}\n\n/**\n * `buildGrantHash(address account, address sessionKey, Session cfg) view returns (bytes32)`.\n * The returned digest is signed by the account owner to authorize the grant — a\n * wrong function name or decode shape would have the owner sign the wrong hash.\n */\nexport function readBuildGrantHash(\n validator: ViemContract,\n account: string,\n sessionKey: string,\n cfg: SessionGrantConfig\n): Promise<Hex> {\n return readFn(validator, \"buildGrantHash\")([account, sessionKey, cfg]) as Promise<Hex>;\n}\n\n/**\n * `buildP256GrantHash(address account, bytes32 keyX, bytes32 keyY, Session cfg)\n * view returns (bytes32)`. Owner-signed authorization digest for a P256 grant.\n */\nexport function readBuildP256GrantHash(\n validator: ViemContract,\n account: string,\n keyX: string,\n keyY: string,\n cfg: SessionGrantConfig\n): Promise<Hex> {\n return readFn(validator, \"buildP256GrantHash\")([account, keyX, keyY, cfg]) as Promise<Hex>;\n}\n","import { type Address, type Hex } from \"viem\";\nimport { buildInitConfig, type GuardianSpec, type InitConfig } from \"@aastar/core\";\nimport type { AccountRecord } from \"../interfaces/storage-adapter\";\n\n/**\n * Shared helpers for the FULL-config (8-field `InitConfig`) account-creation path —\n * the only factory path that can install P-256 (passkey) guardian keys at deploy time\n * (airaccount-contract v0.20.0 / #120, #118).\n *\n * ## Why a dedicated path (not `createAccountWithDefaults`)\n * The factory exposes two account-creation entrypoints with DIFFERENT salt + acceptance\n * semantics (verified against `AAStarAirAccountFactoryV7.sol`):\n *\n * - `createAccountWithDefaults(owner, salt, g1, g1Sig, g2, g2Sig, dailyLimit)` — ECDSA-only.\n * CREATE2 salt = `keccak256(owner, salt)` (does NOT bind the config), so the contract\n * REQUIRES each ECDSA guardian's `ACCEPT_GUARDIAN` acceptance signature to stop a\n * front-runner from seizing the counterfactual address with different guardians. This is\n * the existing `AccountManager.createAccountWithGuardians` path; it has no InitConfig and\n * thus no way to set `guardianP256X/Y`.\n *\n * - `createAccount(owner, salt, config)` — full 8-field `InitConfig`. CREATE2 salt =\n * `keccak256(owner, salt, keccak256(InitConfig))` (`_getSalt` over `_getConfigHash`),\n * so the address is BOUND to the exact config. Because any config change yields a\n * different address, the contract performs NO guardian-acceptance check on this path —\n * for either ECDSA or P-256 guardians (`_initAccount` installs every slot directly).\n * P-256 guardian bootstrap is owner-only and acceptance-sig-free by design (#110④):\n * a single guardian cannot form a recovery quorum, so no consent ceremony is needed.\n *\n * Consequence: the deploy-time initCode MUST embed the BYTE-IDENTICAL `InitConfig` used to\n * predict the address, or the deployed account lands at a different CREATE2 address. These\n * helpers build the config once (via the core `buildInitConfig`) and reconstruct it\n * deterministically from the persisted record at first-UserOp deploy time so the two match.\n */\n\n/** A P-256 (passkey) guardian public key — SEC1 affine coordinates, each a 32-byte hex word. */\nexport interface P256GuardianKey {\n x: Hex;\n y: Hex;\n}\n\n/** Inputs for the full-config (8-field `InitConfig`) account-creation path. */\nexport interface FullConfigGuardianParams {\n /** P-256 (passkey) guardians installed at deploy time. Owner-bootstrap — NO acceptance sig. */\n p256Guardians: P256GuardianKey[];\n /**\n * Optional ECDSA guardians, installed via the SAME full-config path. NOTE: on this path the\n * contract does not verify ECDSA acceptance signatures (the config-hash-in-salt binding stands\n * in for them), so none are required or accepted here.\n */\n ecdsaGuardians?: Address[];\n /** Daily spend limit (wei). MUST be > 0 — a guardian set enables the on-chain GUARD. */\n dailyLimit: bigint;\n /** Validator algorithm ids approved at init. Defaults (in buildInitConfig) to ECDSA (+P-256). */\n approvedAlgIds?: number[];\n /** Floor the daily limit may be lowered to via the guard. Defaults to 0. */\n minDailyLimit?: bigint;\n}\n\n/** A guardian slot serialized for JSON persistence on the {@link AccountRecord}. */\nexport type SerializedGuardianSpec = { ecdsa: string } | { p256: { x: string; y: string } };\n\n/**\n * Map the public params to core {@link GuardianSpec}s in a DETERMINISTIC order\n * (ECDSA slots first, then P-256). Order is consensus-critical: it determines both the\n * predicted CREATE2 address and the guardian slot index each key occupies on-chain.\n */\nexport function toGuardianSpecs(p: FullConfigGuardianParams): GuardianSpec[] {\n const specs: GuardianSpec[] = [];\n for (const e of p.ecdsaGuardians ?? []) specs.push({ ecdsa: e });\n for (const k of p.p256Guardians) specs.push({ p256: { x: k.x, y: k.y } });\n return specs;\n}\n\n/**\n * Build the full 8-field `InitConfig` for the create path. Delegates to the core\n * `buildInitConfig` (the 0.22.0 builder) so the P-256 slots, sentinel handling, and\n * approvedAlgId defaulting are produced by ONE audited implementation — never hand-rolled.\n */\nexport function buildFullInitConfig(p: FullConfigGuardianParams): InitConfig {\n return buildInitConfig({\n guardians: toGuardianSpecs(p),\n dailyLimit: p.dailyLimit,\n ...(p.approvedAlgIds ? { approvedAlgIds: p.approvedAlgIds } : {}),\n ...(p.minDailyLimit !== undefined ? { minDailyLimit: p.minDailyLimit } : {}),\n });\n}\n\n/**\n * Flatten a typed {@link InitConfig} into the POSITIONAL tuple the local human-readable\n * factory ABI (`AIRACCOUNT_FACTORY_ABI`, fed through viem `parseAbi`) expects as the\n * `config` argument of `getAddress` / `createAccount`. Field order is consensus-critical\n * and matches `AAStarAirAccountBase.InitConfig` exactly.\n */\nexport function initConfigToTuple(c: InitConfig): readonly unknown[] {\n return [\n c.guardians,\n c.guardianP256X,\n c.guardianP256Y,\n c.dailyLimit,\n c.approvedAlgIds,\n c.minDailyLimit,\n c.initialTokens,\n c.initialTokenConfigs.map((t) => [t.tier1Limit, t.tier2Limit, t.dailyLimit]),\n ];\n}\n\n/** Serialize core {@link GuardianSpec}s for JSON storage on the account record. */\nexport function serializeGuardianSpecs(specs: readonly GuardianSpec[]): SerializedGuardianSpec[] {\n return specs.map((s) =>\n s.p256 ? { p256: { x: s.p256.x, y: s.p256.y } } : { ecdsa: s.ecdsa as string }\n );\n}\n\n/**\n * Reconstruct the BYTE-IDENTICAL `InitConfig` from a persisted record at deploy time.\n *\n * Re-derivation is exact because the record persists the RESOLVED `approvedAlgIds`,\n * `minDailyLimit`, and `dailyLimit` (not just the create-time inputs), and `buildInitConfig`\n * is a pure function of its arguments. The resulting config therefore hashes to the same\n * `_getConfigHash`, yielding the same CREATE2 address that was predicted at create time.\n *\n * @throws if the record carries no `guardianSpecs` (i.e. it is not a full-config account).\n */\nexport function initConfigFromRecord(record: AccountRecord): InitConfig {\n if (!record.guardianSpecs || record.guardianSpecs.length === 0) {\n throw new Error(\n \"initConfigFromRecord: record has no guardianSpecs (not a full-config / P-256 account)\"\n );\n }\n const guardians: GuardianSpec[] = record.guardianSpecs.map((s) =>\n \"p256\" in s\n ? { p256: { x: s.p256.x as Hex, y: s.p256.y as Hex } }\n : { ecdsa: s.ecdsa as Address }\n );\n return buildInitConfig({\n guardians,\n dailyLimit: record.dailyLimit ? BigInt(record.dailyLimit) : 0n,\n ...(record.approvedAlgIds ? { approvedAlgIds: record.approvedAlgIds } : {}),\n ...(record.minDailyLimit !== undefined ? { minDailyLimit: BigInt(record.minDailyLimit) } : {}),\n });\n}\n","import { zeroAddress, parseEther, type Address, type Hash, type WalletClient } from \"viem\";\n// AIRACCOUNT_ABI is a local human-readable signature array (not in @aastar/core);\n// parseAbi is required to feed it to viem's encodeFunctionData during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi, encodeFunctionData } from \"viem\";\nimport {\n needsValidatorRouter,\n getCanonicalAddresses,\n airAccountActions,\n airAccountFactoryActions,\n} from \"@aastar/core\";\nimport { keccak256 } from \"../../migration/viem/hashing\";\nimport { solidityPacked } from \"../../migration/viem/abi-encoding\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport {\n readPredictedAddress,\n readPredictedAddressWithDefaults,\n} from \"../providers/typed-reads\";\nimport { IStorageAdapter, AccountRecord } from \"../interfaces/storage-adapter\";\nimport { ISignerAdapter } from \"../interfaces/signer-adapter\";\nimport { EntryPointVersion, AIRACCOUNT_FACTORY_ABI, AIRACCOUNT_ABI } from \"../constants/entrypoint\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\nimport {\n buildFullInitConfig,\n toGuardianSpecs,\n serializeGuardianSpecs,\n initConfigToTuple,\n initConfigFromRecord,\n type FullConfigGuardianParams,\n type P256GuardianKey,\n} from \"./account-init-config\";\n\n// v0.20.0 (#120): InitConfig gained bytes32[3] guardianP256X / guardianP256Y (P-256 guardian\n// keys) right after `guardians`. ECDSA-only accounts pass three zero words for each.\nconst ZERO32 = (\"0x\" + \"0\".repeat(64)) as `0x${string}`;\nconst EMPTY_P256: readonly [`0x${string}`, `0x${string}`, `0x${string}`] = [ZERO32, ZERO32, ZERO32];\n\n/**\n * Result of {@link AccountManager.ensureValidatorRouter}.\n * `set: true` only when an on-chain `setValidator(router)` tx was actually sent (`tx`\n * carries the hash). `set: false` is a no-op with a `reason` explaining the decision.\n */\nexport interface EnsureValidatorRouterResult {\n set: boolean;\n reason?: string;\n tx?: Hash;\n router?: Address;\n}\n\n/**\n * Account manager — extracted from NestJS AccountService.\n * Creates and retrieves smart accounts without framework dependencies.\n */\nexport class AccountManager {\n private readonly logger: ILogger;\n\n constructor(\n private readonly ethereum: EthereumProvider,\n private readonly storage: IStorageAdapter,\n private readonly signer: ISignerAdapter,\n logger?: ILogger\n ) {\n this.logger = logger ?? new ConsoleLogger(\"[AccountManager]\");\n }\n\n async createAccount(\n userId: string,\n options?: {\n entryPointVersion?: EntryPointVersion;\n salt?: number | bigint;\n /** Daily transfer limit in wei. When > 0 the account is created with on-chain guard enforcement. */\n dailyLimit?: bigint;\n /**\n * P-256 (passkey) guardians to install at deploy time. When present, the account is created\n * via the full-config createAccount(owner, salt, config) path (delegates to\n * {@link createAccountWithP256Guardians}); `dailyLimit` MUST be > 0 (guardians enable the guard).\n */\n p256Guardians?: P256GuardianKey[];\n /** Optional ECDSA guardians installed via the same full-config path (no acceptance sig required). */\n ecdsaGuardians?: Address[];\n /** Validator algorithm ids approved at init (full-config path). Defaults to ECDSA (+P-256). */\n approvedAlgIds?: number[];\n /** Floor the daily limit may be lowered to via the guard (full-config path). Defaults to 0. */\n minDailyLimit?: bigint;\n }\n ): Promise<AccountRecord> {\n // Full-config path: any passkey (P-256) guardian routes through the 8-field InitConfig builder\n // so the deploy-time initCode can inject guardianP256X/Y (the ECDSA-only createAccountWithDefaults\n // path cannot). See createAccountWithP256Guardians for the contract-level rationale.\n if (options?.p256Guardians && options.p256Guardians.length > 0) {\n return this.createAccountWithP256Guardians(userId, {\n p256Guardians: options.p256Guardians,\n ecdsaGuardians: options.ecdsaGuardians,\n dailyLimit: options.dailyLimit ?? 0n,\n approvedAlgIds: options.approvedAlgIds,\n minDailyLimit: options.minDailyLimit,\n salt: options.salt,\n entryPointVersion: options.entryPointVersion,\n });\n }\n\n const version = options?.entryPointVersion ?? this.ethereum.getDefaultVersion();\n const versionStr = version as string;\n\n // Check for existing account with this version\n const existingAccounts = await this.storage.getAccounts();\n const existing = existingAccounts.find(\n a => a.userId === userId && a.entryPointVersion === versionStr\n );\n if (existing) return existing;\n\n const factory = this.ethereum.getFactoryContract(version);\n const validatorAddress =\n (this.ethereum.getValidatorContract(version).address as string) ||\n this.ethereum.getValidatorAddress(version);\n\n // Ensure signer wallet exists\n const { address: signerAddress } = await this.signer.ensureSigner(userId);\n const salt = options?.salt ?? Math.floor(Math.random() * 1000000);\n\n // Predict account address using M5 factory (createAccount with minimal config).\n // When dailyLimit > 0, write it into the config so the account is guard-enabled at deployment.\n const dailyLimitValue = options?.dailyLimit ?? 0n;\n const minimalConfig = [\n [zeroAddress, zeroAddress, zeroAddress], // guardians (address[3])\n EMPTY_P256, // guardianP256X (bytes32[3]) — v0.20.0\n EMPTY_P256, // guardianP256Y (bytes32[3]) — v0.20.0\n dailyLimitValue, // dailyLimit (0 = no guard)\n [], // approvedAlgIds\n 0n, // minDailyLimit\n [], // initialTokens\n [], // initialTokenConfigs\n ];\n // uint256 `salt` coerced to bigint via the typed wrapper. The predicted\n // address is the fund-custody address; the bigint encoding is byte-identical\n // to the JS-number `salt` reused in the deploy-time initCode, so the\n // counterfactual address is unchanged.\n const accountAddress = await readPredictedAddress(\n factory,\n signerAddress,\n BigInt(salt),\n minimalConfig\n );\n\n // Check deployment status\n let deployed = false;\n try {\n const code = await this.ethereum.getProvider().getCode({ address: accountAddress as Address });\n deployed = !!code && code !== \"0x\";\n } catch {\n // Assume not deployed\n }\n\n const account: AccountRecord = {\n userId,\n address: accountAddress,\n signerAddress,\n salt,\n deployed,\n deploymentTxHash: null,\n validatorAddress,\n entryPointVersion: versionStr,\n factoryAddress: (factory.address as string) || this.ethereum.getFactoryAddress(version),\n createdAt: new Date().toISOString(),\n // Persist dailyLimit so buildUserOperation can reconstruct identical initCode at deploy time.\n ...(dailyLimitValue > 0n ? { dailyLimit: dailyLimitValue.toString() } : {}),\n };\n\n await this.storage.saveAccount(account);\n return account;\n }\n\n async getAccount(\n userId: string\n ): Promise<(AccountRecord & { balance: string; nonce: string }) | null> {\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) return null;\n\n let balance = \"0\";\n try {\n balance = await this.ethereum.getBalance(account.address);\n } catch {\n // Use default\n }\n\n const version = (account.entryPointVersion || \"0.6\") as unknown as EntryPointVersion;\n const nonce = await this.ethereum.getNonce(account.address, 0, version);\n\n return { ...account, balance, nonce: nonce.toString() };\n }\n\n async getAccountAddress(userId: string): Promise<string> {\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) throw new Error(\"Account not found\");\n return account.address;\n }\n\n async getAccountBalance(\n userId: string\n ): Promise<{ address: string; balance: string; balanceInWei: string }> {\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) throw new Error(\"Account not found\");\n const balance = await this.ethereum.getBalance(account.address);\n return {\n address: account.address,\n balance,\n balanceInWei: parseEther(balance).toString(),\n };\n }\n\n async getAccountNonce(userId: string): Promise<{ address: string; nonce: string }> {\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) throw new Error(\"Account not found\");\n const nonce = await this.ethereum.getNonce(account.address);\n return { address: account.address, nonce: nonce.toString() };\n }\n\n async getAccountByUserId(userId: string): Promise<AccountRecord | null> {\n return this.storage.findAccountByUserId(userId);\n }\n\n /**\n * Build the acceptance hash that guardian devices must sign before account creation.\n *\n * Encoding: keccak256(solidityPacked(\n * [\"string\",\"uint256\",\"address\",\"address\",\"uint256\",\"uint256\"],\n * [\"ACCEPT_GUARDIAN\", chainId, factoryAddress, owner, salt, dailyLimit]\n * ))\n *\n * dailyLimit is bound in the hash (PR #47 / C-3) to prevent a front-runner from\n * replaying guardian sigs with a weaker limit on the same counterfactual address.\n *\n * Returns the RAW keccak256 hash (no EIP-191 prefix).\n * Guardians MUST sign via personal_sign / ethers.signMessage(ethers.getBytes(hash)).\n * Do NOT use eth_sign — the EIP-191 \"\\x19Ethereum Signed Message:\\n32\" prefix\n * is applied inside the contract (toEthSignedMessageHash) before ecrecover, not here.\n *\n * @returns raw hex keccak256 hash — encode this into the QR code shown to guardian devices\n */\n buildGuardianAcceptanceHash(\n owner: string,\n salt: number | bigint,\n factoryAddress: string,\n chainId: number,\n dailyLimit: bigint\n ): string {\n if (typeof salt === \"number\" && !Number.isSafeInteger(salt)) {\n throw new Error(\n `salt value ${salt} exceeds Number.MAX_SAFE_INTEGER; pass as bigint to avoid precision loss`\n );\n }\n // viem's encodePacked rejects plain `number` for uint256 — coerce to bigint.\n return keccak256(\n solidityPacked(\n [\"string\", \"uint256\", \"address\", \"address\", \"uint256\", \"uint256\"],\n [\"ACCEPT_GUARDIAN\", BigInt(chainId), factoryAddress, owner, BigInt(salt), dailyLimit]\n )\n );\n }\n\n /**\n * Encode calldata for modifyTierLimitsWithGuardians() — guardian-gated tier-limit change (PR #43).\n *\n * Both tier1 and tier2 can be raised or lowered, subject to guardian approval.\n * Caller is responsible for building and submitting the resulting UserOp.\n *\n * @param tier1 New Tier-1 ceiling in wei (ECDSA-only spending; 0 = no limit)\n * @param tier2 New Tier-2 ceiling in wei (dual-factor; 0 = no limit)\n * @param deadline Unix timestamp — guardian sigs rejected after this\n * @param guardianSigs 65-byte EIP-191 hex signatures from required guardians\n */\n encodeModifyTierLimits(\n tier1: bigint,\n tier2: bigint,\n deadline: bigint,\n guardianSigs: string[]\n ): string {\n return encodeFunctionData({\n abi: parseAbi(AIRACCOUNT_ABI),\n functionName: \"modifyTierLimitsWithGuardians\",\n args: [tier1, tier2, deadline, guardianSigs as `0x${string}`[]],\n });\n }\n\n /**\n * Create an AirAccount with 3 on-chain guardians:\n * - guardian1 and guardian2: user's own devices (passkeys on phone 1 and phone 2)\n * - guardian3: team Safe multisig (defaultCommunityGuardian, set in factory at deploy time)\n *\n * Both guardian1 and guardian2 must sign the acceptance hash produced by\n * buildGuardianAcceptanceHash() before this method is called.\n *\n * Recovery: any 2-of-3 guardians can initiate social recovery after a 48h timelock.\n */\n async createAccountWithGuardians(\n userId: string,\n params: {\n guardian1: string;\n guardian1Sig: string;\n guardian2: string;\n guardian2Sig: string;\n dailyLimit: bigint;\n salt?: number | bigint;\n entryPointVersion?: EntryPointVersion;\n }\n ): Promise<AccountRecord> {\n if (params.guardian1.toLowerCase() === params.guardian2.toLowerCase()) {\n throw new Error(\"guardian1 and guardian2 must be different addresses\");\n }\n if (params.dailyLimit <= 0n) {\n throw new Error(\"Guardian accounts require dailyLimit > 0 (on-chain enforcement)\");\n }\n\n const version = params.entryPointVersion ?? this.ethereum.getDefaultVersion();\n if (version === EntryPointVersion.V0_6) {\n throw new Error(\n \"createAccountWithGuardians requires EntryPoint v0.7 or v0.8; \" +\n \"v0.6 factory does not support getAddressWithDefaults\"\n );\n }\n const versionStr = version as string;\n\n const existingAccounts = await this.storage.getAccounts();\n const existing = existingAccounts.find(\n a => a.userId === userId && a.entryPointVersion === versionStr && a.guardian1\n );\n if (existing) return existing;\n\n const { address: signerAddress } = await this.signer.ensureSigner(userId);\n const salt = params.salt ?? Math.floor(Math.random() * 1000000);\n\n const factory = this.ethereum.getFactoryContract(version);\n const factoryAddress = (factory.address as string) ?? this.ethereum.getFactoryAddress(version);\n\n // uint256 `salt` and `dailyLimit` are enforced as bigint by the typed wrapper.\n const accountAddress = await readPredictedAddressWithDefaults(\n factory,\n signerAddress,\n BigInt(salt),\n params.guardian1,\n params.guardian2,\n params.dailyLimit\n );\n\n let deployed = false;\n try {\n const code = await this.ethereum.getProvider().getCode({ address: accountAddress as Address });\n deployed = !!code && code !== \"0x\";\n } catch {\n // Assume not deployed\n }\n\n const validatorAddress = this.ethereum.getValidatorAddress(version);\n const account: AccountRecord = {\n userId,\n address: accountAddress,\n signerAddress,\n salt,\n deployed,\n deploymentTxHash: null,\n validatorAddress,\n entryPointVersion: versionStr,\n factoryAddress,\n createdAt: new Date().toISOString(),\n // Persist dailyLimit so transfer-manager can reconstruct identical initCode at deploy time.\n ...(params.dailyLimit > 0n ? { dailyLimit: params.dailyLimit.toString() } : {}),\n // Persist guardian addresses and sigs so transfer-manager can use createAccountWithDefaults\n // to reconstruct the correct initCode on first UserOp deployment.\n guardian1: params.guardian1,\n guardian1Sig: params.guardian1Sig,\n guardian2: params.guardian2,\n guardian2Sig: params.guardian2Sig,\n };\n\n await this.storage.saveAccount(account);\n this.logger.log(`[AccountManager] account created with guardians: ${accountAddress}`);\n return account;\n }\n\n /**\n * Create an AirAccount with one or more P-256 (WebAuthn passkey) guardians installed at\n * DEPLOY time — the server-client path #118 adds for KMS-custodied / counterfactual accounts\n * (e.g. YAA) that cannot drive the viem extension layer for account creation.\n *\n * Uses the factory's full-config `createAccount(owner, salt, config)` path because it is the\n * ONLY entrypoint that accepts an 8-field `InitConfig` (and therefore `guardianP256X/Y`). The\n * 8-field config is built by the core `buildInitConfig` (0.22.0) — never hand-rolled — and the\n * address is predicted via the factory's full-config `getAddress(owner, salt, config)` (NOT\n * `getAddressWithDefaults`), binding the address to `keccak256(config)`.\n *\n * ### Acceptance-signature semantics (verified against AAStarAirAccountFactoryV7.sol)\n * On this path the contract performs NO guardian-acceptance signature check — for P-256 OR ECDSA\n * guardians. Front-run protection comes from `_getSalt(owner, salt, _getConfigHash(config))`:\n * any change to the guardian set (or any other config field) yields a different CREATE2 address,\n * so an attacker cannot collide on the victim's counterfactual address with a weaker config.\n * P-256 guardians are an owner-bootstrap (single guardian can't form a recovery quorum), so no\n * acceptance ceremony exists for them by design (#110④). This is why optional ECDSA guardians may\n * also be passed here WITHOUT signatures — distinct from createAccountWithGuardians(), which uses\n * the owner-only-salt `createAccountWithDefaults` path and DOES require ECDSA acceptance sigs.\n *\n * The deploy UserOp is still signed by the existing KMS owner-key path (unchanged): this method\n * only predicts the address and persists the full config; transfer-manager rebuilds the\n * byte-identical initCode (via {@link initConfigFromRecord}) at first-UserOp deploy time.\n *\n * @throws if no P-256 guardian is supplied, dailyLimit <= 0, or EntryPoint is v0.6.\n */\n async createAccountWithP256Guardians(\n userId: string,\n params: {\n /** P-256 (passkey) guardian public keys to install at deploy time (at least one required). */\n p256Guardians: P256GuardianKey[];\n /** Optional ECDSA guardians installed via the same full-config path (no acceptance sig). */\n ecdsaGuardians?: Address[];\n /** Daily spend limit in wei. MUST be > 0 — a guardian set enables the on-chain guard. */\n dailyLimit: bigint;\n /** Validator algorithm ids approved at init. Defaults to ECDSA (+P-256 when a passkey is present). */\n approvedAlgIds?: number[];\n /** Floor the daily limit may be lowered to via the guard. Defaults to 0. */\n minDailyLimit?: bigint;\n salt?: number | bigint;\n entryPointVersion?: EntryPointVersion;\n }\n ): Promise<AccountRecord> {\n if (!params.p256Guardians || params.p256Guardians.length === 0) {\n throw new Error(\"createAccountWithP256Guardians requires at least one P-256 guardian\");\n }\n if (params.dailyLimit <= 0n) {\n throw new Error(\n \"P-256 guardian accounts require dailyLimit > 0 (a guardian set enables the on-chain guard)\"\n );\n }\n\n const version = params.entryPointVersion ?? this.ethereum.getDefaultVersion();\n if (version === EntryPointVersion.V0_6) {\n throw new Error(\n \"createAccountWithP256Guardians requires EntryPoint v0.7 or v0.8; \" +\n \"the v0.6 factory does not support the full-config createAccount(InitConfig) path\"\n );\n }\n const versionStr = version as string;\n\n // Build the FULL 8-field InitConfig (incl. guardianP256X/Y) via the core builder. This also\n // validates: <= 3 guardians, P-256 coords all-or-nothing + non-zero, sentinel misuse, dailyLimit > 0.\n const fullParams: FullConfigGuardianParams = {\n p256Guardians: params.p256Guardians,\n ecdsaGuardians: params.ecdsaGuardians,\n dailyLimit: params.dailyLimit,\n approvedAlgIds: params.approvedAlgIds,\n minDailyLimit: params.minDailyLimit,\n };\n const specs = toGuardianSpecs(fullParams);\n const config = buildFullInitConfig(fullParams);\n\n // One full-config (P-256) account per (user, version) — idempotent like the other create paths.\n const existingAccounts = await this.storage.getAccounts();\n const existing = existingAccounts.find(\n a =>\n a.userId === userId &&\n a.entryPointVersion === versionStr &&\n !!a.guardianSpecs &&\n a.guardianSpecs.length > 0\n );\n if (existing) return existing;\n\n const { address: signerAddress } = await this.signer.ensureSigner(userId);\n // #118 M2: a JS-number salt outside the 53-bit safe range silently truncates, so the predicted\n // and deploy-time salts would diverge -> different CREATE2 address -> stranded funds. Reject it\n // (pass a bigint for large salts) and persist a lossless DECIMAL STRING below.\n if (typeof params.salt === \"number\" && !Number.isSafeInteger(params.salt)) {\n throw new Error(\n `salt value ${params.salt} exceeds Number.MAX_SAFE_INTEGER; pass it as a bigint to avoid precision loss`\n );\n }\n const saltBig = BigInt(params.salt ?? Math.floor(Math.random() * 1000000));\n\n const factory = this.ethereum.getFactoryContract(version);\n const factoryAddress = (factory.address as string) ?? this.ethereum.getFactoryAddress(version);\n\n // Predict via the FULL-config getAddress(owner, salt, config). The address is bound to\n // keccak256(config), so the deploy-time initCode MUST embed the byte-identical config AND the\n // identical salt (transfer-manager rebuilds both from the persisted record fields below).\n const accountAddress = await readPredictedAddress(\n factory,\n signerAddress,\n saltBig,\n initConfigToTuple(config)\n );\n\n let deployed = false;\n try {\n const code = await this.ethereum.getProvider().getCode({ address: accountAddress as Address });\n deployed = !!code && code !== \"0x\";\n } catch {\n // Assume not deployed\n }\n\n const validatorAddress = this.ethereum.getValidatorAddress(version);\n const account: AccountRecord = {\n userId,\n address: accountAddress,\n signerAddress,\n // Persist as a lossless decimal string (#118 M2); transfer-manager rebuilds via BigInt(account.salt).\n salt: saltBig.toString(),\n deployed,\n deploymentTxHash: null,\n validatorAddress,\n entryPointVersion: versionStr,\n factoryAddress,\n createdAt: new Date().toISOString(),\n dailyLimit: params.dailyLimit.toString(),\n // Persist the RESOLVED config so transfer-manager rebuilds byte-identical initCode at deploy.\n guardianSpecs: serializeGuardianSpecs(specs),\n approvedAlgIds: [...config.approvedAlgIds],\n minDailyLimit: config.minDailyLimit.toString(),\n };\n\n await this.storage.saveAccount(account);\n this.logger.log(\n `[AccountManager] account created with ${params.p256Guardians.length} P-256 guardian(s): ${accountAddress}`\n );\n // Gap B: a router-delegated algId (BLS/T2/T3/weighted/session/...) cannot validate until the\n // account's validator router is wired via setValidator(). The factory does NOT auto-wire it, and\n // setValidator is onlyOwner + needs deployed code — so it CANNOT run at predict-time here (the\n // account is still counterfactual). Flag the explicit post-deploy step rather than attempting it now.\n if (needsValidatorRouter(config.approvedAlgIds)) {\n this.logger.log(\n `[AccountManager] account ${accountAddress} approved a router-delegated algorithm ` +\n `(approvedAlgIds=[${config.approvedAlgIds.join(\", \")}]); use deployAndWireValidator(userId, ` +\n `{ walletClient }) to deploy + setValidator(router) in one call (or ensureValidatorRouter(userId) ` +\n `after a manual deploy) — required for those algIds to validate.`\n );\n }\n return account;\n }\n\n /**\n * Gap B — wire the validator router for an account that approved a ROUTER-DELEGATED signature\n * algorithm (BLS 0x01, cumulative T2 0x04, T3 0x05, weighted 0x07, session 0x08, ...). Such an\n * account's `_validateTripleSignature` / `_callBLSValidator` return `1` (FAIL) while\n * `validator() == address(0)`, so the algorithm is non-functional until the owner calls\n * `setValidator(router)` (onlyOwner, SET-ONCE). Inline algIds (ECDSA 0x02, P256 0x03, COMBINED_T1\n * 0x06) need no router and are a no-op here.\n *\n * MUST be called AFTER the account is deployed (setValidator is onlyOwner and needs code) — the\n * lazy/counterfactual deploy path cannot setValidator at predict-time. Idempotent: re-running after\n * the validator is set is a no-op (`reason: 'validator already set'`).\n *\n * On-chain access matches the rest of this package: reads via the EthereumProvider's PublicClient\n * (`getAccountContract(...).read.validator()` and `getProvider().getCode()`); the state-changing\n * `setValidator` is sent through a caller-supplied `WalletClient` whose account is the owner —\n * the same convention used by `PaymasterManager.updatePrice` / `ForceExitService` (this manager's\n * narrow `ISignerAdapter` only EIP-191 personal-signs and cannot send transactions).\n *\n * @param userId the account owner's user id (storage key)\n * @param opts.router override the router address (defaults to the chain's canonical\n * `aaStarValidator`); pass to target a non-canonical router\n * @param opts.walletClient viem WalletClient signing as the account OWNER — REQUIRED to send the tx\n */\n async ensureValidatorRouter(\n userId: string,\n opts?: { router?: Address; walletClient?: WalletClient }\n ): Promise<EnsureValidatorRouterResult> {\n // (1) Load the record + resolve approvedAlgIds. Absent => ECDSA-only legacy record => no router.\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) throw new Error(\"Account not found\");\n const approvedAlgIds = account.approvedAlgIds;\n if (!approvedAlgIds || approvedAlgIds.length === 0) {\n return { set: false, reason: \"no approvedAlgIds / not router-delegated\" };\n }\n\n // (2) All approved algIds are inline => nothing to route.\n if (!needsValidatorRouter(approvedAlgIds)) {\n return { set: false, reason: \"no router-delegated algorithm\" };\n }\n\n // (3) Resolve the router: explicit override, else the chain's canonical aaStarValidator.\n const chainId = this.ethereum.getChainId();\n const canonicalRouter = getCanonicalAddresses(chainId)?.aaStarValidator as Address | undefined;\n const router = opts?.router ?? canonicalRouter;\n if (!router || router.toLowerCase() === zeroAddress) {\n return { set: false, reason: `no canonical validator router for chain ${chainId}` };\n }\n\n // (4) Check deployment FIRST. setValidator is onlyOwner and needs deployed code; and reading\n // validator() on a counterfactual (not-yet-deployed) account reverts (eth_call returns 0x),\n // so the deploy check MUST precede the validator() read — otherwise a pre-deploy call throws\n // instead of returning the clean \"not deployed yet\" reason.\n let deployed = false;\n try {\n const code = await this.ethereum.getProvider().getCode({ address: account.address as Address });\n deployed = !!code && code !== \"0x\";\n } catch {\n // Treat an RPC failure as \"not deployed\" — never attempt setValidator on an unknown-code account.\n }\n if (!deployed) {\n return { set: false, reason: \"account not deployed yet — call after deploy\" };\n }\n\n // (5) Read the account's current validator(). Non-zero => already wired (SET-ONCE) => no-op.\n const current = (await this.ethereum\n .getAccountContract(account.address)\n .read.validator([])) as Address;\n if (current && current.toLowerCase() !== zeroAddress) {\n return { set: false, reason: \"validator already set\" };\n }\n\n // (6) Send setValidator(router) signed by the owner. The write goes through a caller-supplied\n // WalletClient (this manager has no signer that can send transactions). Use the core setValidator\n // action so the encoding stays the single-source-of-truth ABI from @aastar/core.\n const walletClient = opts?.walletClient;\n if (!walletClient || !walletClient.account) {\n return {\n set: false,\n reason: \"walletClient (account owner) required to send setValidator\",\n router,\n };\n }\n const tx = (await airAccountActions(account.address as Address)(walletClient).setValidator({\n validator: router,\n account: walletClient.account,\n })) as Hash;\n this.logger.log(\n `[AccountManager] setValidator(${router}) sent for account ${account.address} (tx ${tx})`\n );\n return { set: true, tx, router };\n }\n\n /**\n * Gap B (complete auto-wiring): deploy a router-delegated account AND set its validator router in\n * ONE call, so a BLS / cumulative / session-key account is immediately functional — no separate\n * manual `ensureValidatorRouter` step. The factory's lazy first-UserOp deploy cannot bootstrap such\n * an account (its own algorithm can't validate until the router is wired), so this performs an\n * explicit `factory.createAccount(owner, salt, config)` deploy (if the account has no code yet),\n * waits for it, then wires `setValidator(router)`. Both txs go through the caller-supplied owner/\n * deployer `WalletClient` (this manager holds no transaction signer). For inline algIds (ECDSA/P256/\n * COMBINED_T1) the validator step is a documented no-op.\n *\n * @returns `{ deployTx?, validator }` — `deployTx` is undefined if the account was already deployed.\n */\n async deployAndWireValidator(\n userId: string,\n opts: { walletClient: WalletClient; router?: Address }\n ): Promise<{ deployTx?: Hash; validator: EnsureValidatorRouterResult }> {\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) throw new Error(\"Account not found\");\n const walletClient = opts.walletClient;\n if (!walletClient || !walletClient.account) {\n throw new Error(\"deployAndWireValidator: a walletClient (deployer/owner) is required\");\n }\n\n // (1) Deploy via the FULL-config createAccount(owner, salt, config) if the account has no code yet.\n let deployTx: Hash | undefined;\n let code = \"0x\";\n try {\n code = (await this.ethereum.getProvider().getCode({ address: account.address as Address })) ?? \"0x\";\n } catch {\n // Treat an RPC failure as \"not deployed\" — the createAccount below is idempotent (CREATE2).\n }\n if (!code || code === \"0x\") {\n // Rebuild the byte-identical InitConfig the account was predicted against (same owner/salt/config\n // ⇒ same CREATE2 address as the persisted record).\n const config = initConfigFromRecord(account);\n deployTx = (await airAccountFactoryActions(account.factoryAddress as Address)(walletClient).createAccount({\n owner: account.signerAddress as Address,\n salt: BigInt(account.salt),\n config,\n account: walletClient.account,\n })) as Hash;\n // setValidator (step 2) is onlyOwner + needs deployed code — wait for the deploy to land first.\n await this.ethereum.getProvider().waitForTransactionReceipt({ hash: deployTx });\n account.deployed = true;\n account.deploymentTxHash = deployTx;\n await this.storage.saveAccount(account);\n this.logger.log(`[AccountManager] deployed account ${account.address} (tx ${deployTx})`);\n }\n\n // (2) Wire the validator router. No-op when the account uses only inline algIds or it's already set.\n const validator = await this.ensureValidatorRouter(userId, {\n walletClient,\n router: opts.router,\n });\n // Wait for the setValidator tx to land so the account is on-chain-READY when this call returns\n // (ensureValidatorRouter itself fires-and-returns the hash without waiting).\n if (validator.set && validator.tx) {\n await this.ethereum.getProvider().waitForTransactionReceipt({ hash: validator.tx });\n }\n return { deployTx, validator };\n }\n}\n","import { concat, type Hex } from \"viem\";\n\nimport { selectorFromId } from \"../../migration/viem/hashing\";\n\n// AAStarAirAccountV7 v0.17.2-beta.4 bundler-compat entrypoint.\n//\n// The EntryPoint v0.7 routes a UserOp whose callData begins with the executeUserOp\n// selector to `account.executeUserOp(userOp, userOpHash)`, which re-derives the\n// signature algId in-frame. This eliminates the cross-`eth_call` transient dependency\n// that previously made guard-enabled accounts fail bundler gas estimation\n// (`AlgorithmNotApproved(0)`).\n\n/** 4-byte selector of `executeUserOp((PackedUserOperation),bytes32)`. */\nexport const EXECUTE_USER_OP_SELECTOR = selectorFromId(\n \"executeUserOp((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes),bytes32)\"\n);\n\n/** 4-byte selector of `execute(address,uint256,bytes)`. */\nexport const EXECUTE_SELECTOR = selectorFromId(\"execute(address,uint256,bytes)\");\n\n/** 4-byte selector of `executeBatch(address[],uint256[],bytes[])`. */\nexport const EXECUTE_BATCH_SELECTOR = selectorFromId(\n \"executeBatch(address[],uint256[],bytes[])\"\n);\n\n/**\n * Wrap inner `execute()` / `executeBatch()` callData with the `executeUserOp` selector so a\n * guard-enabled (v0.17.2-beta.4) account routes the bundler UserOp through `executeUserOp`.\n *\n * Only `execute` / `executeBatch` may be wrapped — the account reverts\n * `UnsupportedInnerSelector` for anything else (including a nested `executeUserOp`).\n *\n * Owner-direct (non-bundler) `execute()` does NOT need this; no-guard accounts can submit\n * bare callData. Use this only when building a bundler UserOp for a guard-enabled account.\n *\n * @param innerCallData ABI-encoded `execute`/`executeBatch` calldata (0x-prefixed)\n * @returns `executeUserOp.selector ++ innerCallData`\n * @throws if `innerCallData` is not an `execute`/`executeBatch` call\n */\nexport function wrapExecuteUserOp(innerCallData: string): string {\n if (!/^0x[0-9a-fA-F]*$/.test(innerCallData) || innerCallData.length < 10) {\n throw new Error(\"wrapExecuteUserOp: innerCallData must be 0x-prefixed calldata with a 4-byte selector\");\n }\n const sel = innerCallData.slice(0, 10).toLowerCase();\n if (sel !== EXECUTE_SELECTOR && sel !== EXECUTE_BATCH_SELECTOR) {\n throw new Error(\n `wrapExecuteUserOp: only execute()/executeBatch() may be wrapped (got selector ${sel}); ` +\n \"the account reverts UnsupportedInnerSelector otherwise\"\n );\n }\n return concat([EXECUTE_USER_OP_SELECTOR, innerCallData as Hex]);\n}\n\n/** True if callData is already wrapped with the executeUserOp selector. */\nexport function isExecuteUserOpWrapped(callData: string): boolean {\n return callData.slice(0, 10).toLowerCase() === EXECUTE_USER_OP_SELECTOR;\n}\n","import { concat, getContract, numberToHex, zeroAddress, type Address, type Hex, type WalletClient } from \"viem\";\n// PAYMASTER_PRICE_ABI / the SuperPaymaster-detection ABI are local human-readable\n// signature arrays (not in @aastar/core); parseAbi is required to feed them to\n// viem's getContract / writeContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport { IStorageAdapter, PaymasterRecord } from \"../interfaces/storage-adapter\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\n\n/**\n * Thrown when a paymaster's on-chain price cache is stale.\n * Caller should invoke `paymasterManager.updatePrice(paymasterAddress)` before retrying.\n */\nexport class PaymasterPriceStalenessError extends Error {\n constructor(\n public readonly paymasterAddress: string,\n public readonly ageSeconds: number,\n public readonly thresholdSeconds: number\n ) {\n super(\n `Paymaster ${paymasterAddress} price is stale ` +\n `(age: ${Math.floor(ageSeconds / 60)}min, threshold: ${Math.floor(thresholdSeconds / 60)}min). ` +\n `Call updatePrice() on the paymaster contract before retrying.`\n );\n this.name = \"PaymasterPriceStalenessError\";\n }\n}\n\nconst PAYMASTER_PRICE_ABI = parseAbi([\n \"function token() view returns (address)\",\n \"function cachedPriceTimestamp() view returns (uint256)\",\n \"function priceStalenessThreshold() view returns (uint256)\",\n \"function updatePrice() external\",\n]);\n\nconst SUPER_PAYMASTER_DETECT_ABI = parseAbi([\n \"function owner() view returns (address)\",\n \"function operators(address) view returns (bool,uint256,address,uint256)\",\n]);\n\n/**\n * Paymaster manager — extracted from NestJS PaymasterService.\n * Storage via IStorageAdapter instead of filesystem JSON files.\n */\nexport class PaymasterManager {\n private readonly logger: ILogger;\n\n constructor(\n private readonly ethereum: EthereumProvider,\n private readonly storage: IStorageAdapter,\n logger?: ILogger\n ) {\n this.logger = logger ?? new ConsoleLogger(\"[PaymasterManager]\");\n }\n\n async getAvailablePaymasters(\n userId: string\n ): Promise<{ name: string; address: string; configured: boolean }[]> {\n const paymasters = await this.storage.getPaymasters(userId);\n return paymasters.map(config => ({\n name: config.name,\n address: config.address,\n configured: !!config.address && config.address !== \"0x\",\n }));\n }\n\n async addCustomPaymaster(\n userId: string,\n name: string,\n address: string,\n type: \"pimlico\" | \"stackup\" | \"alchemy\" | \"custom\" = \"custom\",\n apiKey?: string,\n endpoint?: string\n ): Promise<void> {\n const paymaster: PaymasterRecord = {\n id: `${userId}-${name}-${Date.now()}`,\n name,\n address,\n type,\n apiKey,\n endpoint,\n createdAt: new Date().toISOString(),\n };\n await this.storage.savePaymaster(userId, paymaster);\n }\n\n async removeCustomPaymaster(userId: string, name: string): Promise<boolean> {\n return this.storage.removePaymaster(userId, name);\n }\n\n /**\n * Check whether a paymaster's on-chain price cache is still fresh.\n * Returns `{ fresh, ageSeconds, thresholdSeconds }`.\n * Throws if the contract does not implement `cachedPriceTimestamp()` / `priceStalenessThreshold()`.\n */\n async checkPriceFreshness(paymasterAddress: string): Promise<{\n fresh: boolean;\n ageSeconds: number;\n thresholdSeconds: number;\n }> {\n const provider = this.ethereum.getProvider();\n const contract = getContract({\n address: paymasterAddress as Address,\n abi: PAYMASTER_PRICE_ABI,\n client: provider,\n });\n const [timestamp, threshold] = await Promise.all([\n contract.read.cachedPriceTimestamp() as Promise<bigint>,\n contract.read.priceStalenessThreshold() as Promise<bigint>,\n ]);\n const nowSeconds = Math.floor(Date.now() / 1000);\n const ageSeconds = nowSeconds - Number(timestamp);\n const thresholdSeconds = Number(threshold);\n return {\n fresh: ageSeconds <= thresholdSeconds,\n ageSeconds,\n thresholdSeconds,\n };\n }\n\n /**\n * Call `updatePrice()` on a paymaster contract (permissionless).\n * Useful when `checkPriceFreshness()` reports stale price.\n *\n * @param walletClient - A viem WalletClient (with an account) that will send\n * the transaction (must have gas). Replaces the former ethers Signer param.\n */\n async updatePrice(paymasterAddress: string, walletClient: WalletClient): Promise<string> {\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"updatePrice requires a WalletClient with a configured account\");\n }\n const hash = await walletClient.writeContract({\n address: paymasterAddress as Address,\n abi: PAYMASTER_PRICE_ABI,\n functionName: \"updatePrice\",\n args: [],\n gas: BigInt(300_000),\n account,\n chain: walletClient.chain,\n });\n await this.ethereum.getProvider().waitForTransactionReceipt({ hash });\n this.logger.log(`Paymaster ${paymasterAddress} price updated, tx: ${hash}`);\n return hash;\n }\n\n async getPaymasterData(\n userId: string,\n paymasterName: string,\n userOp: unknown,\n entryPoint: string,\n customAddress?: string,\n options?: { tokenAddress?: string }\n ): Promise<string> {\n // Handle custom user-provided paymaster addresses\n if (paymasterName === \"custom-user-provided\" && customAddress) {\n const formattedAddress = customAddress.toLowerCase().startsWith(\"0x\")\n ? customAddress\n : `0x${customAddress}`;\n\n if (!/^0x[a-fA-F0-9]{40}$/.test(formattedAddress)) {\n throw new Error(`Invalid paymaster address format: ${customAddress}`);\n }\n\n const isV07OrV08 =\n entryPoint.toLowerCase() === \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\".toLowerCase() ||\n entryPoint.toLowerCase() === \"0x0576a174D229E3cFA37253523E645A78A0C91B57\".toLowerCase();\n\n if (isV07OrV08) {\n const provider = this.ethereum.getProvider();\n\n // Detect SuperPaymaster vs PaymasterV4\n let isSuperPaymaster = false;\n let operatorAddress = \"0x\";\n try {\n const spContract = getContract({\n address: formattedAddress as Address,\n abi: SUPER_PAYMASTER_DETECT_ABI,\n client: provider,\n });\n const owner = (await spContract.read.owner()) as Address;\n const opInfo = (await spContract.read.operators([owner])) as readonly [\n boolean,\n bigint,\n Address,\n bigint,\n ];\n if (opInfo && opInfo[0] === true) {\n isSuperPaymaster = true;\n operatorAddress = owner;\n this.logger.log(`SuperPaymaster detected, operator: ${operatorAddress}`);\n }\n } catch {\n /* not SuperPaymaster */\n }\n\n if (isSuperPaymaster) {\n const verGas = BigInt(80000);\n // recordXPNTsDebt + event emit in postOp observed ~117k gas on Sepolia; 300k gives safe headroom.\n const postGas = BigInt(300_000);\n const maxRate = (BigInt(1) << BigInt(256)) - BigInt(1);\n return concat([\n formattedAddress as Hex,\n numberToHex(verGas, { size: 16 }),\n numberToHex(postGas, { size: 16 }),\n operatorAddress as Hex,\n numberToHex(maxRate, { size: 32 }),\n ]);\n }\n\n // PaymasterV4 deposit model: paymasterData contains the ERC-20 token address\n // that the user pays gas with (20 bytes appended after the gas limits).\n // Auto-detect via token() on the contract; fall back to empty if not available.\n const paymasterVerificationGasLimit = BigInt(0x30000);\n const paymasterPostOpGasLimit = BigInt(0x30000);\n\n let tokenAddress: string | null = options?.tokenAddress ?? null;\n if (tokenAddress) {\n this.logger.log(`PaymasterV4 token from options: ${tokenAddress}`);\n } else {\n try {\n const pmContract = getContract({\n address: formattedAddress as Address,\n abi: PAYMASTER_PRICE_ABI,\n client: provider,\n });\n tokenAddress = (await pmContract.read.token()) as string;\n if (tokenAddress === zeroAddress) tokenAddress = null;\n if (tokenAddress) {\n this.logger.log(`PaymasterV4 token auto-detected: ${tokenAddress}`);\n }\n } catch {\n this.logger.log(`PaymasterV4 token() not available, paymasterData will have no token`);\n }\n }\n\n const parts: Hex[] = [\n formattedAddress as Hex,\n numberToHex(paymasterVerificationGasLimit, { size: 16 }),\n numberToHex(paymasterPostOpGasLimit, { size: 16 }),\n ];\n if (tokenAddress) {\n parts.push(tokenAddress as Hex);\n }\n return concat(parts);\n }\n\n return formattedAddress;\n }\n\n const paymasters = await this.storage.getPaymasters(userId);\n const config = paymasters.find(p => p.name === paymasterName);\n if (!config) {\n throw new Error(`Paymaster ${paymasterName} not found`);\n }\n\n switch (config.type) {\n case \"pimlico\":\n if (!config.apiKey) return \"0x\";\n return this.getPimlicoPaymasterData(config, userOp, entryPoint);\n case \"stackup\":\n if (!config.apiKey) return \"0x\";\n return this.getStackUpPaymasterData(config, userOp, entryPoint);\n case \"alchemy\":\n if (!config.apiKey) return \"0x\";\n return this.getAlchemyPaymasterData(config, userOp, entryPoint);\n case \"custom\":\n if (\n config.address.toLowerCase() ===\n \"0x0000000000325602a77416A16136FDafd04b299f\".toLowerCase() &&\n config.apiKey\n ) {\n return this.getPimlicoPaymasterData(\n { ...config, type: \"pimlico\", endpoint: \"https://api.pimlico.io/v2/11155111/rpc\" },\n userOp,\n entryPoint\n );\n }\n return config.address;\n default:\n return \"0x\";\n }\n }\n\n private async getPimlicoPaymasterData(\n config: PaymasterRecord,\n userOp: unknown,\n entryPoint: string\n ): Promise<string> {\n const url = `${config.endpoint}?apikey=${config.apiKey}`;\n const response = await globalThis.fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n method: \"pm_sponsorUserOperation\",\n params: [userOp, entryPoint, {}],\n id: 1,\n }),\n });\n\n const result = (await response.json()) as {\n error?: { message?: string };\n result?: {\n paymasterAndData?: string;\n paymaster?: string;\n paymasterVerificationGasLimit?: string;\n paymasterPostOpGasLimit?: string;\n paymasterData?: string;\n };\n };\n\n if (result.error) {\n throw new Error(\n `Pimlico sponsorship failed: ${result.error.message || JSON.stringify(result.error)}`\n );\n }\n\n if (result.result) {\n if (result.result.paymasterAndData) {\n return result.result.paymasterAndData;\n }\n if (result.result.paymaster) {\n return concat([\n result.result.paymaster as Hex,\n numberToHex(BigInt(result.result.paymasterVerificationGasLimit || \"0x30000\"), {\n size: 16,\n }),\n numberToHex(BigInt(result.result.paymasterPostOpGasLimit || \"0x30000\"), { size: 16 }),\n (result.result.paymasterData || \"0x\") as Hex,\n ]);\n }\n }\n\n throw new Error(\"Pimlico API did not return valid paymaster data\");\n }\n\n private async getStackUpPaymasterData(\n config: PaymasterRecord,\n userOp: unknown,\n entryPoint: string\n ): Promise<string> {\n try {\n const response = await globalThis.fetch(`${config.endpoint}/${config.apiKey}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n method: \"pm_sponsorUserOperation\",\n params: { userOperation: userOp, entryPoint, context: { type: \"payg\" } },\n id: 1,\n }),\n });\n const result = (await response.json()) as { error?: unknown; result?: string };\n if (result.error) return \"0x\";\n return result.result || \"0x\";\n } catch {\n return \"0x\";\n }\n }\n\n private async getAlchemyPaymasterData(\n config: PaymasterRecord,\n userOp: unknown,\n entryPoint: string\n ): Promise<string> {\n try {\n const response = await globalThis.fetch(`${config.endpoint}/${config.apiKey}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n method: \"alchemy_requestGasAndPaymasterAndData\",\n params: [{ policyId: \"default\", entryPoint, userOperation: userOp }],\n id: 1,\n }),\n });\n const result = (await response.json()) as {\n error?: unknown;\n result?: { paymasterAndData?: string };\n };\n if (result.error) return \"0x\";\n return result.result?.paymasterAndData || \"0x\";\n } catch {\n return \"0x\";\n }\n }\n}\n","import {\n hexToBytes,\n concat,\n numberToHex,\n parseEther,\n zeroAddress,\n type PublicClient,\n type Address,\n type Abi,\n} from \"viem\";\n// Local human-readable ABIs (not in @aastar/core); parseAbi is required to feed\n// them to viem's readContract / encodeFunctionData during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi, encodeFunctionData } from \"viem\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport { readValidatorGasEstimate } from \"../providers/typed-reads\";\nimport { AccountManager } from \"./account-manager\";\nimport { BLSSignatureService, GuardianSigner } from \"./bls-signature-service\";\nimport { GuardChecker } from \"./guard-checker\";\nimport { wrapExecuteUserOp } from \"../utils/execute-user-op\";\nimport { PaymasterManager } from \"./paymaster-manager\";\nimport { TokenService } from \"./token-service\";\nimport { IStorageAdapter } from \"../interfaces/storage-adapter\";\nimport { ISignerAdapter, PasskeyAssertionContext } from \"../interfaces/signer-adapter\";\nimport { LegacyPasskeyAssertion } from \"./kms-signer\";\nimport {\n EntryPointVersion,\n ALG_ID,\n AIRACCOUNT_ABI,\n AIRACCOUNT_FACTORY_ABI,\n FACTORY_ABI_V6,\n} from \"../constants/entrypoint\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\nimport { initConfigFromRecord, initConfigToTuple } from \"./account-init-config\";\n\n// v0.20.0 (#120): InitConfig gained bytes32[3] guardianP256X / guardianP256Y after `guardians`.\n// ECDSA-only deploy initCode passes three zero words for each.\nconst ZERO32 = (\"0x\" + \"0\".repeat(64)) as `0x${string}`;\nconst EMPTY_P256: readonly [`0x${string}`, `0x${string}`, `0x${string}`] = [ZERO32, ZERO32, ZERO32];\nimport { PaymasterPriceStalenessError } from \"./paymaster-manager\";\nimport { UserOperation, PackedUserOperation } from \"../../core/types\";\nimport { ERC4337Utils } from \"../../core/erc4337\";\nimport { TierLevel } from \"../../core/tier\";\n\n// ── Parsed local ABIs ─────────────────────────────────────────────\n// Widened to the loose `Abi` type so encodeFunctionData accepts dynamic\n// function names + loosely-typed args (mirrors the old ethers.Interface surface).\nconst AIRACCOUNT_ABI_PARSED: Abi = parseAbi(AIRACCOUNT_ABI);\nconst AIRACCOUNT_FACTORY_ABI_PARSED: Abi = parseAbi(AIRACCOUNT_FACTORY_ABI);\nconst FACTORY_ABI_V6_PARSED: Abi = parseAbi(FACTORY_ABI_V6);\nconst VALIDATOR_GETTER_ABI: Abi = parseAbi([\"function validator() view returns (address)\"]);\n\n/** encodeFunctionData over a loosely-typed Abi (was `iface.encodeFunctionData`). */\nfunction encodeFn(abi: Abi, functionName: string, args: readonly unknown[]): `0x${string}` {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return encodeFunctionData({ abi, functionName, args } as any);\n}\n\n// ── Signature strategy detection ─────────────────────────────────\n\n/**\n * Determines whether to use plain ECDSA and whether the account is a compositeValidator.\n * Exported for unit testing.\n */\nexport async function detectSignatureStrategy(\n provider: PublicClient,\n accountAddress: string\n): Promise<{ useECDSA: boolean; isCompositeValidator: boolean }> {\n try {\n const accountCode = await provider.getCode({ address: accountAddress as Address });\n if (!accountCode || accountCode === \"0x\") {\n // AirAccount factory invariant: all counterfactual addresses are compositeValidator deployments.\n return { useECDSA: true, isCompositeValidator: true };\n }\n const v = (await provider.readContract({\n address: accountAddress as Address,\n abi: VALIDATOR_GETTER_ABI,\n functionName: \"validator\",\n })) as string;\n // validator() exists → confirmed compositeValidator account.\n return { useECDSA: v === zeroAddress, isCompositeValidator: true };\n } catch {\n // Covers both getCode() and validator() failures (network error or non-compositeValidator account).\n // Use raw ECDSA (no algId prefix) to avoid AA24 on non-compositeValidator accounts.\n return { useECDSA: true, isCompositeValidator: false };\n }\n}\n\n// ── Public DTOs ───────────────────────────────────────────────────\n\nexport interface ExecuteTransferParams {\n to: string;\n amount: string;\n data?: string;\n tokenAddress?: string;\n usePaymaster?: boolean;\n paymasterAddress?: string;\n paymasterData?: string;\n /** ERC-20 token address for deposit-pull paymasters (e.g. PMv4) that require\n * the gas token address appended to paymasterData. Used when the paymaster\n * contract does not expose a public token() getter for auto-detection. */\n paymasterTokenAddress?: string;\n passkeyAssertion?: LegacyPasskeyAssertion;\n /** P256 passkey signature (64 bytes hex). Required for AirAccount Tier 2/3. */\n p256Signature?: string;\n /** Guardian signer instance. Required for AirAccount Tier 3. */\n guardianSigner?: GuardianSigner;\n /** Enable AirAccount tiered signature routing. Default: false (legacy BLS-only). */\n useAirAccountTiering?: boolean;\n /**\n * Wrap the execute()/executeBatch() callData with the `executeUserOp` selector\n * (v0.17.2-beta.4 bundler-compat). REQUIRED for guard-enabled accounts submitted\n * through a standard ERC-4337 bundler; the account re-derives the signature algId\n * in-frame. Default: false. No-guard accounts and owner-direct calls leave it off.\n */\n wrapExecuteUserOp?: boolean;\n}\n\nexport interface EstimateGasParams {\n to: string;\n amount: string;\n data?: string;\n tokenAddress?: string;\n /** Match the executeUserOp wrapping used at submission so gas estimation is accurate (v0.17.2-beta.4). */\n wrapExecuteUserOp?: boolean;\n}\n\nexport interface TransferResult {\n success: boolean;\n transferId: string;\n userOpHash: string;\n status: string;\n message: string;\n from: string;\n to: string;\n amount: string;\n}\n\n// ── Helper to generate UUID-like IDs without external dependency ──\n\nfunction generateId(): string {\n const hex = () => Math.random().toString(16).slice(2, 10);\n return `${hex()}${hex()}-${hex()}-${hex()}-${hex()}-${hex()}${hex()}${hex()}`;\n}\n\n/**\n * Transfer manager — extracted from NestJS TransferService.\n * No passkey verification: callers are responsible for their own auth.\n */\nexport class TransferManager {\n private readonly logger: ILogger;\n\n private readonly guardChecker: GuardChecker | null;\n\n constructor(\n private readonly ethereum: EthereumProvider,\n private readonly accountManager: AccountManager,\n private readonly blsService: BLSSignatureService,\n private readonly paymasterManager: PaymasterManager,\n private readonly tokenService: TokenService,\n private readonly storage: IStorageAdapter,\n private readonly signer: ISignerAdapter,\n logger?: ILogger,\n guardChecker?: GuardChecker\n ) {\n this.logger = logger ?? new ConsoleLogger(\"[TransferManager]\");\n this.guardChecker = guardChecker ?? null;\n }\n\n async executeTransfer(userId: string, params: ExecuteTransferParams): Promise<TransferResult> {\n // Get user's account\n const account = await this.accountManager.getAccountByUserId(userId);\n if (!account) throw new Error(\"User account not found\");\n\n // Check deployment\n const code = await this.ethereum.getProvider().getCode({ address: account.address as Address });\n const needsDeployment = !code || code === \"0x\";\n if (needsDeployment) {\n this.logger.log(\"Account needs deployment, will deploy with first transaction\");\n }\n\n // Balance validation\n const smartAccountBalance = parseFloat(await this.ethereum.getBalance(account.address));\n const isTokenTransfer = !!params.tokenAddress;\n const transferAmount = isTokenTransfer ? 0 : parseFloat(params.amount);\n\n if (!params.usePaymaster) {\n const minRequiredBalance = 0.0002;\n const totalNeeded = transferAmount + minRequiredBalance;\n if (smartAccountBalance < totalNeeded) {\n throw new Error(\n `Insufficient balance: Account has ${smartAccountBalance} ETH but needs ${totalNeeded} ETH`\n );\n }\n } else if (!isTokenTransfer && transferAmount > smartAccountBalance) {\n throw new Error(\n `Insufficient balance: Account has ${smartAccountBalance} ETH but trying to send ${transferAmount} ETH`\n );\n }\n\n const version = (account.entryPointVersion || \"0.6\") as unknown as EntryPointVersion;\n\n // Build UserOperation\n const userOp = await this.buildUserOperation(\n userId,\n account.address,\n params.to,\n params.amount,\n params.data || \"0x\",\n params.usePaymaster,\n params.paymasterAddress,\n params.paymasterData,\n params.tokenAddress,\n version,\n params.paymasterTokenAddress,\n params.wrapExecuteUserOp ?? false\n );\n\n // Get hash\n const userOpHash = await this.ethereum.getUserOpHash(userOp, version);\n\n // Ensure wallet exists\n await this.signer.ensureSigner(userId);\n\n // BLS signature (pass assertion context for KMS-backed signing)\n const assertionCtx: PasskeyAssertionContext | undefined = params.passkeyAssertion\n ? { assertion: params.passkeyAssertion }\n : undefined;\n\n // Detect whether this is a compositeValidator account (has validator() fn) or plain ECDSA.\n // Only compositeValidator accounts expect the algId prefix in the signature.\n let useECDSA = false;\n let isCompositeValidator = false;\n if (version === EntryPointVersion.V0_7 || version === EntryPointVersion.V0_8) {\n const provider = this.ethereum.getProvider();\n ({ useECDSA, isCompositeValidator } = await detectSignatureStrategy(\n provider,\n account.address\n ));\n }\n\n if (useECDSA) {\n const ecdsaSig = await this.signer.signMessage(\n userId,\n hexToBytes(userOpHash as `0x${string}`),\n assertionCtx\n );\n if (isCompositeValidator) {\n this.logger.log(\"ECDSA path for compositeValidator: prepending algId prefix\");\n userOp.signature = concat([\n numberToHex(ALG_ID.ECDSA, { size: 1 }),\n ecdsaSig as `0x${string}`,\n ]);\n } else {\n this.logger.log(\"ECDSA path for non-compositeValidator: raw signature\");\n userOp.signature = ecdsaSig;\n }\n } else if (params.useAirAccountTiering && this.guardChecker) {\n // AirAccount tiered signature routing\n const transferValue = params.tokenAddress ? 0n : parseEther(params.amount);\n const preCheck = await this.guardChecker.preCheck(account.address, transferValue);\n\n if (!preCheck.ok) {\n throw new Error(`Guard pre-check failed: ${preCheck.errors.join(\"; \")}`);\n }\n\n this.logger.log(\n `Tier ${preCheck.tier} selected (algId=0x${preCheck.algId.toString(16).padStart(2, \"0\")})`\n );\n\n userOp.signature = await this.blsService.generateTieredSignature({\n tier: preCheck.tier as TierLevel,\n userId,\n userOpHash,\n p256Signature: params.p256Signature,\n guardianSigner: params.guardianSigner,\n ctx: assertionCtx,\n });\n } else {\n // BLS accounts are always compositeValidator by design — algId prefix applied unconditionally.\n const blsData = await this.blsService.generateBLSSignature(userId, userOpHash, assertionCtx);\n const packedBls = await this.blsService.packSignature(blsData);\n userOp.signature = concat([\n numberToHex(ALG_ID.BLS, { size: 1 }),\n packedBls as `0x${string}`,\n ]);\n }\n\n // Create transfer record\n const transferId = generateId();\n let tokenSymbol = \"ETH\";\n if (params.tokenAddress) {\n try {\n const tokenInfo = await this.tokenService.getTokenInfo(params.tokenAddress);\n tokenSymbol = tokenInfo.symbol;\n } catch {\n tokenSymbol = `${params.tokenAddress.slice(0, 6)}...${params.tokenAddress.slice(-4)}`;\n }\n }\n\n await this.storage.saveTransfer({\n id: transferId,\n userId,\n from: account.address,\n to: params.to,\n amount: params.amount,\n data: params.data,\n userOpHash,\n status: \"pending\",\n nodeIndices: [],\n createdAt: new Date().toISOString(),\n tokenAddress: params.tokenAddress,\n tokenSymbol,\n });\n\n // Process asynchronously\n this.processTransferAsync(transferId, userOp, account.address, version);\n\n return {\n success: true,\n transferId,\n userOpHash,\n status: \"pending\",\n message: \"Transfer submitted successfully. Use transferId to check status.\",\n from: account.address,\n to: params.to,\n amount: params.amount,\n };\n }\n\n private async processTransferAsync(\n transferId: string,\n userOp: UserOperation | PackedUserOperation,\n from: string,\n version: EntryPointVersion\n ): Promise<void> {\n try {\n const formatted = this.formatUserOpForBundler(userOp, version);\n const bundlerUserOpHash = await this.ethereum.sendUserOperation(formatted, version);\n\n await this.storage.updateTransfer(transferId, {\n bundlerUserOpHash,\n status: \"submitted\",\n submittedAt: new Date().toISOString(),\n } as Partial<import(\"../interfaces/storage-adapter\").TransferRecord>);\n\n const txHash = await this.ethereum.waitForUserOp(bundlerUserOpHash);\n\n await this.storage.updateTransfer(transferId, {\n transactionHash: txHash,\n status: \"completed\",\n completedAt: new Date().toISOString(),\n } as Partial<import(\"../interfaces/storage-adapter\").TransferRecord>);\n\n // Update deployment status if first tx\n const code = await this.ethereum.getProvider().getCode({ address: from as Address });\n if (code && code !== \"0x\") {\n const account = (await this.storage.getAccounts()).find(a => a.address === from);\n if (account && !account.deployed) {\n await this.storage.updateAccount(account.userId, {\n deployed: true,\n deploymentTxHash: txHash,\n });\n }\n }\n } catch (error: unknown) {\n let message = error instanceof Error ? error.message : String(error);\n\n // Translate bundler \"expires too soon\" into a structured PaymasterPriceStalenessError\n // so callers can detect and handle stale paymaster price without string-matching.\n if (\n message.includes(\"expires too soon\") ||\n message.includes(\"AA32\") ||\n message.includes(\"paymaster deposit not locked\")\n ) {\n const validUntilMatch = message.match(/validUntil=(\\d+)/);\n const hint = validUntilMatch\n ? ` (validUntil=${validUntilMatch[1]}, expired ${Math.floor(Date.now() / 1000) - Number(validUntilMatch[1])}s ago)`\n : \"\";\n message =\n `Paymaster price is stale${hint}. ` +\n `Call paymasterManager.checkPriceFreshness(paymasterAddress) to diagnose, ` +\n `then paymasterManager.updatePrice(paymasterAddress, signer) to refresh. ` +\n `Original error: ${message}`;\n error = new PaymasterPriceStalenessError(\n \"unknown\" /* paymasterAddress not available here */,\n 0,\n 0\n );\n (error as PaymasterPriceStalenessError & { message: string }).message = message;\n }\n\n await this.storage.updateTransfer(transferId, {\n status: \"failed\",\n error: message,\n failedAt: new Date().toISOString(),\n } as Partial<import(\"../interfaces/storage-adapter\").TransferRecord>);\n this.logger.error(`Transfer ${transferId} failed: ${message}`);\n }\n }\n\n async estimateGas(userId: string, params: EstimateGasParams) {\n const account = await this.accountManager.getAccountByUserId(userId);\n if (!account) throw new Error(\"User account not found\");\n\n const version = (account.entryPointVersion || \"0.6\") as unknown as EntryPointVersion;\n\n const userOp = await this.buildUserOperation(\n userId,\n account.address,\n params.to,\n params.amount,\n params.data || \"0x\",\n false,\n undefined,\n undefined,\n params.tokenAddress,\n version,\n undefined,\n params.wrapExecuteUserOp ?? false\n );\n\n const formatted = this.formatUserOpForBundler(userOp, version);\n const gasEstimates = await this.ethereum.estimateUserOperationGas(formatted, version);\n const gasPrices = await this.ethereum.getUserOperationGasPrice();\n\n const validatorContract = this.ethereum.getValidatorContract(version);\n // Typed wrapper enforces the uint256 `nodeCount` as bigint (a JS number would\n // risk silent truncation outside the 53-bit safe range on the loose surface).\n const validatorGasEstimate = await readValidatorGasEstimate(validatorContract, 3n);\n\n return {\n callGasLimit: gasEstimates.callGasLimit,\n verificationGasLimit: gasEstimates.verificationGasLimit,\n preVerificationGas: gasEstimates.preVerificationGas,\n validatorGasEstimate: validatorGasEstimate.toString(),\n totalGasEstimate: (\n BigInt(gasEstimates.callGasLimit) +\n BigInt(gasEstimates.verificationGasLimit) +\n BigInt(gasEstimates.preVerificationGas)\n ).toString(),\n maxFeePerGas: gasPrices.maxFeePerGas,\n maxPriorityFeePerGas: gasPrices.maxPriorityFeePerGas,\n };\n }\n\n async getTransferStatus(userId: string, transferId: string) {\n const transfer = await this.storage.findTransferById(transferId);\n if (!transfer || transfer.userId !== userId) {\n throw new Error(\"Transfer not found\");\n }\n\n const response: Record<string, unknown> = { ...transfer };\n\n if (transfer.status === \"pending\" || transfer.status === \"submitted\") {\n const elapsed = Math.floor((Date.now() - new Date(transfer.createdAt).getTime()) / 1000);\n response.elapsedSeconds = elapsed;\n }\n\n if (transfer.transactionHash) {\n response.explorerUrl = `https://sepolia.etherscan.io/tx/${transfer.transactionHash}`;\n }\n\n const statusDescriptions: Record<string, string> = {\n pending: \"Preparing transaction and generating signatures\",\n submitted: \"Transaction submitted to bundler, waiting for confirmation\",\n completed: \"Transaction confirmed on chain\",\n failed: \"Transaction failed\",\n };\n response.statusDescription = statusDescriptions[transfer.status] || transfer.status;\n\n return response;\n }\n\n async getTransferHistory(userId: string, page = 1, limit = 10) {\n const transfers = await this.storage.findTransfersByUserId(userId);\n if (!transfers || transfers.length === 0) {\n return { transfers: [], total: 0, page, limit, totalPages: 0 };\n }\n\n transfers.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());\n\n const start = (page - 1) * limit;\n const paginated = transfers.slice(start, start + limit);\n\n return {\n transfers: paginated,\n total: transfers.length,\n page,\n limit,\n totalPages: Math.ceil(transfers.length / limit),\n };\n }\n\n // ── Private helpers ─────────────────────────────────────────────\n\n private async buildUserOperation(\n userId: string,\n sender: string,\n to: string,\n amount: string,\n data: string,\n usePaymaster?: boolean,\n paymasterAddress?: string,\n _paymasterData?: string,\n tokenAddress?: string,\n version: EntryPointVersion = EntryPointVersion.V0_6,\n paymasterTokenAddress?: string,\n wrapExecuteUserOpFlag: boolean = false\n ): Promise<UserOperation | PackedUserOperation> {\n const nonce = await this.ethereum.getNonce(sender, 0, version);\n\n // initCode for deployment\n const provider = this.ethereum.getProvider();\n const code = await provider.getCode({ address: sender as Address });\n const needsDeployment = !code || code === \"0x\";\n\n let initCode = \"0x\";\n if (needsDeployment) {\n const accounts = await this.storage.getAccounts();\n const account = accounts.find(a => a.address === sender);\n if (account) {\n const factory = this.ethereum.getFactoryContract(version);\n const factoryAddress = factory.address;\n\n let deployCalldata: string;\n if (version === EntryPointVersion.V0_7 || version === EntryPointVersion.V0_8) {\n const storedDailyLimit = account.dailyLimit ? BigInt(account.dailyLimit) : 0n;\n if (account.guardianSpecs && account.guardianSpecs.length > 0) {\n // Full-config (P-256 / mixed-guardian) account (#118): rebuild the BYTE-IDENTICAL\n // 8-field InitConfig from the persisted record so the deploy CREATE2 address matches\n // the create-time prediction (the factory binds the address to keccak256(config)).\n const rebuilt = initConfigFromRecord(account);\n deployCalldata = encodeFn(AIRACCOUNT_FACTORY_ABI_PARSED, \"createAccount\", [\n account.signerAddress,\n BigInt(account.salt),\n initConfigToTuple(rebuilt),\n ]);\n } else if (account.guardian1 && account.guardian2 && account.guardian1Sig && account.guardian2Sig) {\n // Guardian account: use createAccountWithDefaults so the factory-computed address\n // matches the stored sender (which was predicted via getAddressWithDefaults).\n // bytes params require 0x-prefixed hex — guard against missing prefix.\n const sig1 = account.guardian1Sig.startsWith(\"0x\")\n ? account.guardian1Sig\n : `0x${account.guardian1Sig}`;\n const sig2 = account.guardian2Sig.startsWith(\"0x\")\n ? account.guardian2Sig\n : `0x${account.guardian2Sig}`;\n deployCalldata = encodeFn(AIRACCOUNT_FACTORY_ABI_PARSED, \"createAccountWithDefaults\", [\n account.signerAddress,\n BigInt(account.salt),\n account.guardian1,\n sig1,\n account.guardian2,\n sig2,\n storedDailyLimit,\n ]);\n } else {\n // Standard account: createAccount with zero guardians and stored dailyLimit.\n const minimalConfig = [\n [zeroAddress, zeroAddress, zeroAddress], // guardians (address[3])\n EMPTY_P256, // guardianP256X (bytes32[3]) — v0.20.0\n EMPTY_P256, // guardianP256Y (bytes32[3]) — v0.20.0\n storedDailyLimit,\n [], // approvedAlgIds\n 0n, // minDailyLimit\n [], // initialTokens\n [], // initialTokenConfigs\n ];\n deployCalldata = encodeFn(AIRACCOUNT_FACTORY_ABI_PARSED, \"createAccount\", [\n account.signerAddress,\n BigInt(account.salt),\n minimalConfig,\n ]);\n }\n } else {\n deployCalldata = encodeFn(FACTORY_ABI_V6_PARSED, \"createAccountWithAAStarValidator\", [\n account.signerAddress,\n account.signerAddress,\n account.validatorAddress,\n true,\n BigInt(account.salt),\n ]);\n }\n\n initCode = concat([factoryAddress as `0x${string}`, deployCalldata as `0x${string}`]);\n }\n }\n\n // callData\n let callData: string;\n if (tokenAddress) {\n const tokenInfo = await this.tokenService.getTokenInfo(tokenAddress);\n const transferCalldata = this.tokenService.generateTransferCalldata(\n to,\n amount,\n tokenInfo.decimals\n );\n callData = encodeFn(AIRACCOUNT_ABI_PARSED, \"execute\", [tokenAddress, 0n, transferCalldata]);\n } else {\n callData = encodeFn(AIRACCOUNT_ABI_PARSED, \"execute\", [to, parseEther(amount), data]);\n }\n\n // v0.17.2-beta.4: guard-enabled accounts must route bundler UserOps through\n // executeUserOp so the account re-derives the signature algId in-frame.\n if (wrapExecuteUserOpFlag) {\n callData = wrapExecuteUserOp(callData);\n }\n\n const gasPrices = await this.ethereum.getUserOperationGasPrice();\n\n const isV07 = version === EntryPointVersion.V0_7 || version === EntryPointVersion.V0_8;\n\n let baseUserOp: Record<string, unknown>;\n if (isV07) {\n // v0.7/v0.8: use factory/factoryData and separate paymaster fields\n let factory: string | undefined;\n let factoryData: string | undefined;\n if (initCode && initCode !== \"0x\" && initCode.length > 2) {\n factory = initCode.slice(0, 42);\n factoryData = initCode.length > 42 ? \"0x\" + initCode.slice(42) : \"0x\";\n }\n baseUserOp = {\n sender,\n nonce: \"0x\" + nonce.toString(16),\n ...(factory ? { factory, factoryData } : {}),\n callData,\n callGasLimit: \"0x0\",\n verificationGasLimit: \"0x0\",\n preVerificationGas: \"0x0\",\n maxFeePerGas: gasPrices.maxFeePerGas,\n maxPriorityFeePerGas: gasPrices.maxPriorityFeePerGas,\n signature: \"0x\",\n };\n } else {\n // v0.6: use initCode and paymasterAndData\n baseUserOp = {\n sender,\n nonce: \"0x\" + nonce.toString(16),\n initCode,\n callData,\n callGasLimit: \"0x0\",\n verificationGasLimit: \"0x0\",\n preVerificationGas: \"0x0\",\n maxFeePerGas: gasPrices.maxFeePerGas,\n maxPriorityFeePerGas: gasPrices.maxPriorityFeePerGas,\n paymasterAndData: \"0x\",\n signature: \"0x\",\n };\n }\n\n // Paymaster\n let paymasterAndData = \"0x\";\n if (usePaymaster) {\n if (paymasterAddress) {\n const entryPoint = this.ethereum.getEntryPointAddress(version);\n paymasterAndData = await this.paymasterManager.getPaymasterData(\n userId,\n \"custom-user-provided\",\n baseUserOp,\n entryPoint,\n paymasterAddress,\n paymasterTokenAddress ? { tokenAddress: paymasterTokenAddress } : undefined\n );\n } else {\n const available = await this.paymasterManager.getAvailablePaymasters(userId);\n const configured = available.find(pm => pm.configured);\n if (configured) {\n const entryPoint = this.ethereum.getEntryPointAddress(version);\n paymasterAndData = await this.paymasterManager.getPaymasterData(\n userId,\n configured.name,\n baseUserOp,\n entryPoint\n );\n } else {\n throw new Error(\"No paymaster configured and no paymaster address provided\");\n }\n }\n\n if (!paymasterAndData || paymasterAndData === \"0x\") {\n throw new Error(\n `Paymaster failed to provide sponsorship data. The paymaster at ${paymasterAddress} may not be configured correctly.`\n );\n }\n\n if (isV07) {\n // For v0.7, split paymasterAndData into separate fields on the baseUserOp\n baseUserOp.paymaster = paymasterAndData.slice(0, 42);\n if (paymasterAndData.length >= 74) {\n baseUserOp.paymasterVerificationGasLimit =\n \"0x\" + BigInt(\"0x\" + paymasterAndData.slice(42, 74)).toString(16);\n }\n if (paymasterAndData.length >= 106) {\n baseUserOp.paymasterPostOpGasLimit =\n \"0x\" + BigInt(\"0x\" + paymasterAndData.slice(74, 106)).toString(16);\n }\n if (paymasterAndData.length > 106) {\n baseUserOp.paymasterData = \"0x\" + paymasterAndData.slice(106);\n }\n } else {\n baseUserOp.paymasterAndData = paymasterAndData;\n }\n }\n\n // Gas estimation\n const gasEstimates = await this.ethereum.estimateUserOperationGas(baseUserOp, version);\n\n const standardUserOp: UserOperation = {\n sender,\n nonce,\n initCode,\n callData,\n callGasLimit: BigInt(gasEstimates.callGasLimit),\n verificationGasLimit: BigInt(gasEstimates.verificationGasLimit),\n preVerificationGas: BigInt(gasEstimates.preVerificationGas),\n maxFeePerGas: BigInt(gasPrices.maxFeePerGas),\n maxPriorityFeePerGas: BigInt(gasPrices.maxPriorityFeePerGas),\n paymasterAndData,\n signature: \"0x\",\n };\n\n if (version === EntryPointVersion.V0_7 || version === EntryPointVersion.V0_8) {\n return ERC4337Utils.packUserOperation(standardUserOp);\n }\n\n return standardUserOp;\n }\n\n private formatUserOpForBundler(\n userOp: UserOperation | PackedUserOperation,\n version: EntryPointVersion = EntryPointVersion.V0_6\n ): Record<string, unknown> {\n if (version === EntryPointVersion.V0_7 || version === EntryPointVersion.V0_8) {\n const packedOp = userOp as PackedUserOperation;\n const gasLimits = ERC4337Utils.unpackAccountGasLimits(packedOp.accountGasLimits);\n const gasFees = ERC4337Utils.unpackGasFees(packedOp.gasFees);\n\n let factory: string | undefined;\n let factoryData: string | undefined;\n if (packedOp.initCode && packedOp.initCode !== \"0x\" && packedOp.initCode.length > 2) {\n factory = packedOp.initCode.slice(0, 42);\n if (packedOp.initCode.length > 42) {\n factoryData = \"0x\" + packedOp.initCode.slice(42);\n }\n }\n\n let paymaster: string | undefined;\n let paymasterVerificationGasLimit: string | undefined;\n let paymasterPostOpGasLimit: string | undefined;\n let paymasterData: string | undefined;\n\n if (\n packedOp.paymasterAndData &&\n packedOp.paymasterAndData !== \"0x\" &&\n packedOp.paymasterAndData.length > 2\n ) {\n paymaster = packedOp.paymasterAndData.slice(0, 42);\n if (packedOp.paymasterAndData.length >= 74) {\n paymasterVerificationGasLimit =\n \"0x\" + BigInt(\"0x\" + packedOp.paymasterAndData.slice(42, 74)).toString(16);\n }\n if (packedOp.paymasterAndData.length >= 106) {\n paymasterPostOpGasLimit =\n \"0x\" + BigInt(\"0x\" + packedOp.paymasterAndData.slice(74, 106)).toString(16);\n }\n if (packedOp.paymasterAndData.length > 106) {\n paymasterData = \"0x\" + packedOp.paymasterAndData.slice(106);\n }\n }\n\n const result: Record<string, unknown> = {\n sender: packedOp.sender,\n nonce:\n typeof packedOp.nonce === \"bigint\"\n ? \"0x\" + packedOp.nonce.toString(16)\n : packedOp.nonce.toString().startsWith(\"0x\")\n ? packedOp.nonce.toString()\n : \"0x\" + BigInt(packedOp.nonce).toString(16),\n callData: packedOp.callData,\n callGasLimit: \"0x\" + gasLimits.callGasLimit.toString(16),\n verificationGasLimit: \"0x\" + gasLimits.verificationGasLimit.toString(16),\n preVerificationGas:\n typeof packedOp.preVerificationGas === \"bigint\"\n ? \"0x\" + packedOp.preVerificationGas.toString(16)\n : packedOp.preVerificationGas.toString().startsWith(\"0x\")\n ? packedOp.preVerificationGas.toString()\n : \"0x\" + BigInt(packedOp.preVerificationGas).toString(16),\n maxFeePerGas: \"0x\" + gasFees.maxFeePerGas.toString(16),\n maxPriorityFeePerGas: \"0x\" + gasFees.maxPriorityFeePerGas.toString(16),\n signature: packedOp.signature || \"0x\",\n };\n\n if (factory) result.factory = factory;\n if (factoryData) result.factoryData = factoryData;\n\n if (paymaster) {\n result.paymaster = paymaster;\n result.paymasterVerificationGasLimit = paymasterVerificationGasLimit || \"0x30000\";\n result.paymasterPostOpGasLimit = paymasterPostOpGasLimit || \"0x30000\";\n if (paymasterData && paymasterData !== \"0x\") {\n result.paymasterData = paymasterData;\n }\n }\n\n return result;\n }\n\n // v0.6 format\n const op = userOp as UserOperation;\n return {\n sender: op.sender,\n nonce: \"0x\" + op.nonce.toString(16),\n initCode: op.initCode,\n callData: op.callData,\n callGasLimit: \"0x\" + op.callGasLimit.toString(16),\n verificationGasLimit: \"0x\" + op.verificationGasLimit.toString(16),\n preVerificationGas: \"0x\" + op.preVerificationGas.toString(16),\n maxFeePerGas: \"0x\" + op.maxFeePerGas.toString(16),\n maxPriorityFeePerGas: \"0x\" + op.maxPriorityFeePerGas.toString(16),\n paymasterAndData: op.paymasterAndData,\n signature: op.signature,\n };\n }\n}\n","import { hexToBytes } from \"viem\";\nimport { keccak256 } from \"../../migration/viem/hashing\";\nimport axios from \"axios\";\n\n/**\n * Minimal guardian signer surface (was `ethers.Signer`): an external signer that\n * performs an EIP-191 personal-sign over raw bytes and returns a 0x-prefixed\n * 65-byte hex signature. Structural — any ethers/viem signer with this method fits.\n */\nexport interface GuardianSigner {\n signMessage(message: Uint8Array): Promise<string>;\n}\nimport {\n BLSManager,\n BLSSignatureData,\n CumulativeT2SignatureData,\n CumulativeT3SignatureData,\n} from \"../../core/bls\";\nimport { TierLevel } from \"../../core/tier\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport { IStorageAdapter } from \"../interfaces/storage-adapter\";\nimport { ISignerAdapter, PasskeyAssertionContext } from \"../interfaces/signer-adapter\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\nimport { ServerConfig } from \"../config\";\n\n/**\n * Raised when a DVT node (aNode YetAnotherAA-Validator ≥ v1.3.0, running with\n * `CONFIRM_ENABLED=true`) withholds its co-signature on a high-value op pending\n * out-of-band approval. The node returns `{ status: \"pending_confirmation\",\n * userOpHash }` instead of a signature; the withheld co-sign is released by\n * `POST /signature/confirm { userOpHash, token }` once the user approves over an\n * independent channel (single-use token, TTL, fail-closed). The SDK surfaces this\n * as a typed error rather than silently dropping the node so callers can drive the\n * confirm flow. Default-off nodes never emit this (behaviour == v1.2.0).\n */\nexport class DvtPendingConfirmationError extends Error {\n constructor(\n public readonly userOpHash: string,\n public readonly nodeEndpoint: string\n ) {\n super(\n `DVT node ${nodeEndpoint} withheld its co-signature pending out-of-band ` +\n `confirmation for userOpHash ${userOpHash}; release it via POST /signature/confirm.`\n );\n this.name = \"DvtPendingConfirmationError\";\n }\n}\n\n/**\n * Type guard for a DVT v1.3.0 `/signature/sign` response that withheld its\n * co-signature pending out-of-band confirmation (`{ status: \"pending_confirmation\",\n * userOpHash }`). Used at every sign call site so a high-value-op withhold is\n * surfaced, not mistaken for a signature-less failure. Default-off nodes never\n * return this shape.\n */\nexport function isPendingConfirmation(\n data: unknown\n): data is { status: \"pending_confirmation\"; userOpHash?: string } {\n return (\n typeof data === \"object\" &&\n data !== null &&\n (data as { status?: unknown }).status === \"pending_confirmation\"\n );\n}\n\n/**\n * BLS signature service — extracted from NestJS BlsService.\n * Uses lazy initialization instead of onModuleInit.\n */\nexport class BLSSignatureService {\n private blsManager: BLSManager | null = null;\n private readonly logger: ILogger;\n\n constructor(\n private readonly config: ServerConfig,\n private readonly ethereum: EthereumProvider,\n private readonly storage: IStorageAdapter,\n private readonly signer: ISignerAdapter,\n logger?: ILogger\n ) {\n this.logger = logger ?? new ConsoleLogger(\"[BLSSignatureService]\");\n }\n\n /** Lazy-initialize BLSManager on first use. */\n private async ensureInitialized(): Promise<BLSManager> {\n if (this.blsManager) return this.blsManager;\n\n const blsConfig = await this.storage.getBlsConfig();\n const seedNodes =\n this.config.blsSeedNodes ?? blsConfig?.discovery?.seedNodes?.map(n => n.endpoint) ?? [];\n\n this.blsManager = new BLSManager({\n seedNodes,\n discoveryTimeout: this.config.blsDiscoveryTimeout ?? 10000,\n });\n\n return this.blsManager;\n }\n\n async getActiveSignerNodes(): Promise<unknown[]> {\n const manager = await this.ensureInitialized();\n const nodes = await manager.getAvailableNodes();\n\n if (nodes.length > 0) {\n try {\n await this.storage.updateSignerNodesCache(nodes);\n } catch {\n // Non-critical\n }\n }\n\n return nodes;\n }\n\n async generateBLSSignature(\n userId: string,\n userOpHash: string,\n ctx?: PasskeyAssertionContext\n ): Promise<BLSSignatureData> {\n const manager = await this.ensureInitialized();\n\n const activeNodes = await this.getActiveSignerNodes();\n if (activeNodes.length < 1) {\n throw new Error(\"No active BLS signer nodes available\");\n }\n\n const selectedNodes = activeNodes.slice(0, Math.min(3, activeNodes.length)) as Array<{\n apiEndpoint: string;\n }>;\n\n const signerNodeSignatures: string[] = [];\n const signerNodeIds: string[] = [];\n\n for (const node of selectedNodes) {\n try {\n const response = await axios.post(`${node.apiEndpoint}/signature/sign`, {\n message: userOpHash,\n });\n\n // DVT v1.3.0: a CONFIRM_ENABLED node withholds its co-sign on a high-value\n // op until out-of-band approval. Surface it instead of treating the\n // signature-less response as a node failure to be skipped.\n if (isPendingConfirmation(response.data)) {\n throw new DvtPendingConfirmationError(response.data.userOpHash ?? userOpHash, node.apiEndpoint);\n }\n\n const signatureForAggregation = response.data.signatureCompact || response.data.signature;\n const formatted = signatureForAggregation.startsWith(\"0x\")\n ? signatureForAggregation\n : `0x${signatureForAggregation}`;\n\n signerNodeSignatures.push(formatted);\n signerNodeIds.push(response.data.nodeId);\n } catch (err) {\n if (err instanceof DvtPendingConfirmationError) throw err;\n // Continue with other nodes\n }\n }\n\n if (signerNodeSignatures.length === 0) {\n throw new Error(\"Failed to get signatures from any BLS signer nodes\");\n }\n\n let aggregatedSignature: string;\n if (signerNodeSignatures.length > 1) {\n const aggregateResponse = await axios.post(\n `${selectedNodes[0].apiEndpoint}/signature/aggregate`,\n { signatures: signerNodeSignatures }\n );\n aggregatedSignature = aggregateResponse.data.signature.startsWith(\"0x\")\n ? aggregateResponse.data.signature\n : `0x${aggregateResponse.data.signature}`;\n } else {\n // Single signature — re-request in EIP format\n const singleSignResponse = await axios.post(\n `${selectedNodes[0].apiEndpoint}/signature/sign`,\n { message: userOpHash }\n );\n if (isPendingConfirmation(singleSignResponse.data)) {\n throw new DvtPendingConfirmationError(\n singleSignResponse.data.userOpHash ?? userOpHash,\n selectedNodes[0].apiEndpoint\n );\n }\n aggregatedSignature = singleSignResponse.data.signature.startsWith(\"0x\")\n ? singleSignResponse.data.signature\n : `0x${singleSignResponse.data.signature}`;\n }\n\n // Generate message point\n const messagePoint = await manager.generateMessagePoint(userOpHash);\n\n // Get user account and wallet for ECDSA signatures\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) {\n throw new Error(`User account not found for userId: ${userId}`);\n }\n\n const walletAddress = await this.signer.getAddress(userId);\n\n if (walletAddress.toLowerCase() !== account.signerAddress.toLowerCase()) {\n throw new Error(\n `Wallet address mismatch! Wallet: ${walletAddress}, Expected: ${account.signerAddress}`\n );\n }\n\n const aaSignature = await this.signer.signMessage(\n userId,\n hexToBytes(userOpHash as `0x${string}`),\n ctx\n );\n const messagePointHash = keccak256(messagePoint as `0x${string}`);\n const messagePointSignature = await this.signer.signMessage(\n userId,\n hexToBytes(messagePointHash as `0x${string}`),\n ctx\n );\n\n return {\n nodeIds: signerNodeIds,\n signature: aggregatedSignature,\n messagePoint,\n aaAddress: account.signerAddress,\n aaSignature,\n messagePointSignature,\n };\n }\n\n async packSignature(blsData: BLSSignatureData): Promise<string> {\n const manager = await this.ensureInitialized();\n return manager.packSignature(blsData);\n }\n\n // ── Tiered Signature Support (M4) ─────────────────────────────\n\n /**\n * Generate a tiered signature based on the required tier level.\n *\n * - Tier 1: raw 65-byte ECDSA (no algId prefix, backwards-compat)\n * - Tier 2: algId 0x04 — P256 + BLS aggregate + messagePoint ECDSA\n * - Tier 3: algId 0x05 — P256 + BLS + messagePoint ECDSA + Guardian ECDSA\n *\n * @param tier - Required tier level (1, 2, or 3)\n * @param userId - User ID for account lookup\n * @param userOpHash - The UserOp hash to sign\n * @param p256Signature - P256 passkey signature (64 bytes, required for tier 2/3)\n * @param guardianSigner - Guardian signer (required for tier 3)\n * @param ctx - Optional passkey assertion context for KMS signing\n */\n async generateTieredSignature(params: {\n tier: TierLevel;\n userId: string;\n userOpHash: string;\n p256Signature?: string;\n guardianSigner?: GuardianSigner;\n ctx?: PasskeyAssertionContext;\n }): Promise<string> {\n const { tier, userId, userOpHash, p256Signature, guardianSigner, ctx } = params;\n const manager = await this.ensureInitialized();\n\n if (tier === 1) {\n // Tier 1: raw ECDSA signature (65 bytes, no algId prefix)\n const account = await this.storage.findAccountByUserId(userId);\n if (!account) throw new Error(`User account not found for userId: ${userId}`);\n\n return this.signer.signMessage(userId, hexToBytes(userOpHash as `0x${string}`), ctx);\n }\n\n // Tier 2 and 3 both need BLS + P256\n if (!p256Signature) {\n throw new Error(`P256 signature required for Tier ${tier}`);\n }\n\n // Get BLS components (reuse existing generateBLSSignature for node signing + aggregation)\n const blsData = await this.generateBLSSignature(userId, userOpHash, ctx);\n\n if (tier === 2) {\n const t2Data: CumulativeT2SignatureData = {\n p256Signature,\n nodeIds: blsData.nodeIds,\n blsSignature: blsData.signature,\n messagePoint: blsData.messagePoint,\n messagePointSignature: blsData.messagePointSignature,\n };\n return manager.packCumulativeT2Signature(t2Data);\n }\n\n // Tier 3: also needs guardian signature\n if (!guardianSigner) {\n throw new Error(\"Guardian signer required for Tier 3\");\n }\n\n const guardianSignature = await guardianSigner.signMessage(\n hexToBytes(userOpHash as `0x${string}`)\n );\n\n const t3Data: CumulativeT3SignatureData = {\n p256Signature,\n nodeIds: blsData.nodeIds,\n blsSignature: blsData.signature,\n messagePoint: blsData.messagePoint,\n messagePointSignature: blsData.messagePointSignature,\n guardianSignature,\n };\n return manager.packCumulativeT3Signature(t3Data);\n }\n}\n","// eslint-disable-next-line no-restricted-imports\nimport { parseAbi, formatUnits, parseUnits, encodeFunctionData } from \"viem\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport { ERC20_ABI } from \"../constants/entrypoint\";\n\n// ERC20_ABI is a local human-readable `string[]` of signatures (not available in\n// @aastar/core), so parseAbi is required to feed it to viem read/encode helpers.\nconst ERC20_ABI_PARSED = parseAbi(ERC20_ABI);\n\nexport interface TokenInfo {\n address: string;\n symbol: string;\n name: string;\n decimals: number;\n}\n\nexport interface TokenBalance {\n token: TokenInfo;\n balance: string;\n formattedBalance: string;\n}\n\n/**\n * Token service — extracted from NestJS TokenService.\n * Only on-chain queries and calldata generation (no preset token list).\n */\nexport class TokenService {\n constructor(private readonly ethereum: EthereumProvider) {}\n\n async getTokenInfo(tokenAddress: string): Promise<TokenInfo> {\n const client = this.ethereum.getProvider();\n const address = tokenAddress as `0x${string}`;\n\n const [name, symbol, decimals] = await Promise.all([\n client.readContract({ address, abi: ERC20_ABI_PARSED, functionName: \"name\" }),\n client.readContract({ address, abi: ERC20_ABI_PARSED, functionName: \"symbol\" }),\n client.readContract({ address, abi: ERC20_ABI_PARSED, functionName: \"decimals\" }),\n ]);\n\n return {\n address: tokenAddress.toLowerCase(),\n name: name as string,\n symbol: symbol as string,\n decimals: Number(decimals),\n };\n }\n\n async getTokenBalance(tokenAddress: string, walletAddress: string): Promise<string> {\n const client = this.ethereum.getProvider();\n\n try {\n const balance = await client.readContract({\n address: tokenAddress as `0x${string}`,\n abi: ERC20_ABI_PARSED,\n functionName: \"balanceOf\",\n args: [walletAddress as `0x${string}`],\n });\n return (balance as bigint).toString();\n } catch {\n return \"0\";\n }\n }\n\n async getFormattedTokenBalance(\n tokenAddress: string,\n walletAddress: string\n ): Promise<TokenBalance> {\n const tokenInfo = await this.getTokenInfo(tokenAddress);\n const rawBalance = await this.getTokenBalance(tokenAddress, walletAddress);\n const formattedBalance = formatUnits(BigInt(rawBalance), tokenInfo.decimals);\n return { token: tokenInfo, balance: rawBalance, formattedBalance };\n }\n\n generateTransferCalldata(to: string, amount: string, decimals: number): string {\n // Calldata encoding does not depend on a contract address (the old ethers\n // call site passed ethers.ZeroAddress only to instantiate ethers.Contract).\n const parsedAmount = parseUnits(amount, decimals);\n return encodeFunctionData({\n abi: ERC20_ABI_PARSED,\n functionName: \"transfer\",\n args: [to as `0x${string}`, parsedAmount],\n });\n }\n\n async validateToken(tokenAddress: string): Promise<{\n isValid: boolean;\n token?: TokenInfo;\n error?: string;\n }> {\n try {\n const client = this.ethereum.getProvider();\n const address = tokenAddress as `0x${string}`;\n\n const [name, symbol, decimals] = (await Promise.race([\n Promise.all([\n client.readContract({ address, abi: ERC20_ABI_PARSED, functionName: \"name\" }),\n client.readContract({ address, abi: ERC20_ABI_PARSED, functionName: \"symbol\" }),\n client.readContract({ address, abi: ERC20_ABI_PARSED, functionName: \"decimals\" }),\n ]),\n new Promise((_, reject) => setTimeout(() => reject(new Error(\"Timeout\")), 10000)),\n ])) as [string, string, number];\n\n return {\n isValid: true,\n token: {\n address: tokenAddress.toLowerCase(),\n name,\n symbol,\n decimals: Number(decimals),\n },\n };\n } catch (error: unknown) {\n return {\n isValid: false,\n error: error instanceof Error ? error.message : \"Invalid ERC20 token\",\n };\n }\n }\n}\n","import { ISignerAdapter, PasskeyAssertionContext } from \"../interfaces/signer-adapter\";\n\n/**\n * Thin wrapper around ISignerAdapter for consistent wallet access.\n */\nexport class WalletManager {\n constructor(private readonly signer: ISignerAdapter) {}\n\n async getAddress(userId: string): Promise<`0x${string}`> {\n return this.signer.getAddress(userId);\n }\n\n async signMessage(\n userId: string,\n message: `0x${string}` | Uint8Array,\n ctx?: PasskeyAssertionContext\n ): Promise<`0x${string}`> {\n return this.signer.signMessage(userId, message, ctx);\n }\n\n async ensureSigner(userId: string): Promise<{ address: `0x${string}` }> {\n return this.signer.ensureSigner(userId);\n }\n}\n","import { ServerConfig, validateConfig } from \"./config\";\nimport { ConsoleLogger } from \"./interfaces/logger\";\nimport { EthereumProvider } from \"./providers/ethereum-provider\";\nimport { AccountManager } from \"./services/account-manager\";\nimport { TransferManager } from \"./services/transfer-manager\";\nimport { BLSSignatureService } from \"./services/bls-signature-service\";\nimport { PaymasterManager } from \"./services/paymaster-manager\";\nimport { TokenService } from \"./services/token-service\";\nimport { WalletManager } from \"./services/wallet-manager\";\n\n/**\n * Main facade for the YAAA Server SDK.\n * Wires all services together from a single config object.\n *\n * @example\n * ```ts\n * import { AirAccountServerClient, MemoryStorage, LocalWalletSigner } from '@aastar/airaccount/server';\n *\n * const client = new AirAccountServerClient({\n * rpcUrl: 'https://sepolia.infura.io/v3/...',\n * bundlerRpcUrl: 'https://api.pimlico.io/v2/11155111/rpc?apikey=...',\n * chainId: 11155111,\n * entryPoints: {\n * v06: {\n * entryPointAddress: '0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789',\n * factoryAddress: '0x...',\n * validatorAddress: '0x...',\n * },\n * },\n * storage: new MemoryStorage(),\n * signer: new LocalWalletSigner('0xPRIVATE_KEY'),\n * });\n *\n * const account = await client.accounts.createAccount('user-123');\n * ```\n */\nexport class AirAccountServerClient {\n readonly ethereum: EthereumProvider;\n readonly accounts: AccountManager;\n readonly transfers: TransferManager;\n readonly bls: BLSSignatureService;\n readonly paymaster: PaymasterManager;\n readonly tokens: TokenService;\n readonly wallets: WalletManager;\n\n constructor(config: ServerConfig) {\n validateConfig(config);\n\n const logger = config.logger ?? new ConsoleLogger(\"[YAAA]\");\n\n // Core provider\n this.ethereum = new EthereumProvider(config);\n\n // Service wiring (order matters: dependencies first)\n this.wallets = new WalletManager(config.signer);\n this.tokens = new TokenService(this.ethereum);\n this.paymaster = new PaymasterManager(this.ethereum, config.storage, logger);\n this.accounts = new AccountManager(this.ethereum, config.storage, config.signer, logger);\n this.bls = new BLSSignatureService(\n config,\n this.ethereum,\n config.storage,\n config.signer,\n logger\n );\n this.transfers = new TransferManager(\n this.ethereum,\n this.accounts,\n this.bls,\n this.paymaster,\n this.tokens,\n config.storage,\n config.signer,\n logger\n );\n }\n}\n\n/**\n * @deprecated Renamed to {@link AirAccountServerClient}. This alias is kept for\n * backward compatibility and will be removed in a future major version.\n */\nexport const YAAAServerClient = AirAccountServerClient;\n","/**\n * Viem reimplementation of the signature-normalization helpers that the\n * AirAccount KMS signer and EIP-7702 delegate service currently implement with\n * ethers.\n *\n * This is a NEW, parallel module written for the ethers -> viem migration. The\n * original ethers code (kms-signer.ts / eip7702-delegate-service.ts) is left\n * untouched; the differential parity test next to this file proves that, for\n * the same inputs, these viem helpers produce byte-identical results.\n *\n * The load-bearing invariant being migrated:\n * - The KMS and EIP-7702 paths assemble / consume a 65-byte signature laid\n * out as r(32) || s(32) || v(1), where the final byte v is the Ethereum\n * recovery id 27/28 (NOT the EIP-2098 yParity 0/1). viem's\n * parseSignature/serializeSignature must preserve this exact layout, and\n * must NOT emit the compact (64-byte) yParityAndS form.\n */\nimport {\n type Address,\n type Hex,\n type ByteArray,\n concatHex,\n hashMessage as viemHashMessage,\n keccak256,\n numberToHex,\n parseSignature,\n recoverAddress as viemRecoverAddress,\n recoverMessageAddress,\n serializeSignature,\n toRlp,\n} from \"viem\";\n\n/** The Ethereum personal-message hashable input (mirrors ethers.hashMessage). */\nexport type SignableMessage = string | ByteArray;\n\n/**\n * Normalize a 65-byte ECDSA signature to the canonical r(32)||s(32)||v(1)\n * serialization with v = 27/28.\n *\n * Equivalent to `ethers.Signature.from(sig).serialized`. Accepts a 65-byte\n * signature whose final byte is either the legacy recovery id (27/28) or the\n * raw yParity (0/1); both normalize to 27/28 in the output. The output is\n * ALWAYS 65 bytes — viem's compact yParityAndS variant is never produced.\n */\nexport function normalizeSignature(sig: Hex): Hex {\n const parsed = parseSignature(sig);\n // serializeSignature with a default `to: \"hex\"` and a v/yParity present\n // writes the 65-byte r||s||v form, mapping yParity 0 -> 0x1b, 1 -> 0x1c.\n return serializeSignature(parsed);\n}\n\n/**\n * Hash a personal message exactly like `ethers.hashMessage`.\n *\n * keccak256(\"\\x19Ethereum Signed Message:\\n\" + len + message). A `string` is\n * treated as UTF-8 text (NOT hex); a byte array is hashed as raw bytes.\n */\nexport function hashMessage(message: SignableMessage): Hex {\n if (typeof message === \"string\") return viemHashMessage(message);\n return viemHashMessage({ raw: message });\n}\n\n/**\n * Recover the signer address from a digest + 65-byte signature.\n *\n * Async equivalent of `ethers.recoverAddress(hash, sig)`. Returns a\n * checksummed address.\n */\nexport async function recoverAddress(hash: Hex, signature: Hex): Promise<Address> {\n return viemRecoverAddress({ hash, signature });\n}\n\n/**\n * Recover the signer address of a personal message.\n *\n * Async equivalent of `ethers.verifyMessage(message, sig)` (which returns the\n * recovered address). Returns a checksummed address.\n */\nexport async function verifyMessage(\n message: SignableMessage,\n signature: Hex\n): Promise<Address> {\n if (typeof message === \"string\") return recoverMessageAddress({ message, signature });\n return recoverMessageAddress({ message: { raw: message }, signature });\n}\n\n/**\n * Compute the EIP-7702 SET_CODE authorization hash that an EOA must sign.\n *\n * Hash = keccak256(0x05 || RLP([chainId, address, nonce]))\n *\n * Mirrors `EIP7702DelegateService.buildAuthorizationHash`. chainId and nonce\n * are RLP-encoded as minimal big-endian integers (0 -> empty byte string).\n */\nexport function buildAuthorizationHash(\n chainId: number,\n nonce: bigint,\n delegateAddress: Address\n): Hex {\n const encoded = toRlp([\n chainId === 0 ? \"0x\" : numberToHex(chainId),\n delegateAddress,\n nonce === 0n ? \"0x\" : numberToHex(nonce),\n ]);\n return keccak256(concatHex([\"0x05\", encoded]));\n}\n\n/**\n * Verify a 65-byte signature is a valid EIP-7702 authorization for `eoa`.\n *\n * Async equivalent of `EIP7702DelegateService.verifyAuthorization`. Recovers\n * the signer from the authorization hash and compares (case-insensitively)\n * against the expected EOA.\n */\nexport async function verifyAuthorization(\n eoa: Address,\n chainId: number,\n nonce: bigint,\n signature: Hex,\n delegateAddress: Address\n): Promise<boolean> {\n const hash = buildAuthorizationHash(chainId, nonce, delegateAddress);\n const recovered = await recoverAddress(hash, signature);\n return recovered.toLowerCase() === eoa.toLowerCase();\n}\n","import {\n concat,\n encodeFunctionData,\n hexToBytes,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\n// AIRACCOUNT_ABI is a local human-readable signature array (not in @aastar/core);\n// parseAbi is required to feed it to viem's readContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { MODULE_TYPE, AIRACCOUNT_ABI, AIRACCOUNT_ADDRESSES } from \"../constants/entrypoint\";\n// Byte-exact viem parity helpers (proven in migration/viem/*.parity.test.ts).\nimport { keccak256 } from \"../../migration/viem/hashing\";\nimport { solidityPacked } from \"../../migration/viem/abi-encoding\";\nimport { hashMessage } from \"../../migration/viem/signatures\";\n\nexport type ModuleTypeId = 1 | 2 | 3 | 4; // VALIDATOR | EXECUTOR | FALLBACK | HOOK\n\nexport interface InstallModuleParams {\n /** The deployed AirAccount address */\n account: string;\n /** ERC-7579 module type: 1=Validator, 2=Executor, 3=Fallback, 4=Hook */\n moduleTypeId: ModuleTypeId;\n /** Module contract address to install */\n module: string;\n /**\n * Guardian signatures + module init data, packed as:\n * bytes[0..65*sigsRequired] = guardian ECDSA sigs\n * bytes[65*sigsRequired..] = module onInstall() init data\n *\n * Sig hash (per guardian, r5 format):\n * keccak256(\"INSTALL_MODULE\" ‖ chainId ‖ account ‖ moduleTypeId ‖ module ‖ keccak256(moduleInitData)).toEthSignedMessageHash()\n *\n * sigsRequired: 0 if threshold<=40, 1 if <=70, 2 if =100\n */\n guardianSigs?: string[]; // 65-byte hex sigs from guardians\n /** Raw bytes passed to module.onInstall() after guardian sigs */\n moduleInitData?: string;\n}\n\nexport interface UninstallModuleParams {\n account: string;\n moduleTypeId: ModuleTypeId;\n module: string;\n /** Always requires 2 guardian sigs for uninstall */\n guardianSig1: string;\n guardianSig2: string;\n /** Passed to module.onUninstall() */\n moduleDeInitData?: string;\n}\n\n/**\n * Build the EIP-191 install hash that guardians must sign.\n *\n * r5 format: includes keccak256(moduleInitData) to prevent config-swap attacks.\n *\n * @example\n * const hash = buildInstallModuleHash(chainId, account, 1, moduleAddress, moduleInitData);\n * const sig = await guardian.signMessage(hexToBytes(hash));\n */\nexport function buildInstallModuleHash(\n chainId: number,\n account: string,\n moduleTypeId: ModuleTypeId,\n module: string,\n moduleInitData: string = \"0x\",\n): string {\n const moduleInitDataHash = keccak256(moduleInitData as Hex);\n const raw = keccak256(\n solidityPacked(\n [\"string\", \"uint256\", \"address\", \"uint256\", \"address\", \"bytes32\"],\n [\"INSTALL_MODULE\", BigInt(chainId), account, BigInt(moduleTypeId), module, moduleInitDataHash],\n ),\n );\n return hashMessage(hexToBytes(raw));\n}\n\n/**\n * Build the EIP-191 uninstall hash that guardians must sign.\n */\nexport function buildUninstallModuleHash(\n chainId: number,\n account: string,\n moduleTypeId: ModuleTypeId,\n module: string,\n): string {\n const raw = keccak256(\n solidityPacked(\n [\"string\", \"uint256\", \"address\", \"uint256\", \"address\"],\n [\"UNINSTALL_MODULE\", BigInt(chainId), account, BigInt(moduleTypeId), module],\n ),\n );\n return hashMessage(hexToBytes(raw));\n}\n\n/**\n * ModuleManager — ERC-7579 module install/uninstall helpers.\n *\n * Handles the guardian-sig packing required by AAStarAirAccountV7:\n * installModule(moduleTypeId, module, guardianSigs ‖ moduleInitData)\n * uninstallModule(moduleTypeId, module, guardianSig1 ‖ guardianSig2 ‖ deInitData)\n */\nexport class ModuleManager {\n private readonly provider: PublicClient;\n private readonly chainId: number;\n\n constructor(provider: PublicClient, chainId: number) {\n this.provider = provider;\n this.chainId = chainId;\n }\n\n /**\n * Encode calldata for installModule().\n * Caller is responsible for submitting via UserOp (EntryPoint) or direct tx.\n */\n encodeInstall(params: InstallModuleParams): string {\n const sigs = params.guardianSigs ?? [];\n const initData = (params.moduleInitData ?? \"0x\") as Hex;\n\n // Pack: guardian sigs (65 bytes each) concatenated with module init data.\n // viem `concat` over hex strings produces the same byte layout as\n // ethers.concat over getBytes(...) — the 0x prefixes are stripped per item.\n const packed: Hex =\n sigs.length > 0 ? concat([...(sigs as Hex[]), initData]) : initData;\n\n return encodeFunctionData({\n abi: parseAbi(AIRACCOUNT_ABI as readonly string[]),\n functionName: \"installModule\",\n args: [BigInt(params.moduleTypeId), params.module as Address, packed],\n });\n }\n\n /**\n * Encode calldata for uninstallModule().\n * Always requires 2 guardian signatures.\n */\n encodeUninstall(params: UninstallModuleParams): string {\n const deInitData = (params.moduleDeInitData ?? \"0x\") as Hex;\n const packed: Hex = concat([\n params.guardianSig1 as Hex,\n params.guardianSig2 as Hex,\n deInitData,\n ]);\n\n return encodeFunctionData({\n abi: parseAbi(AIRACCOUNT_ABI as readonly string[]),\n functionName: \"uninstallModule\",\n args: [BigInt(params.moduleTypeId), params.module as Address, packed],\n });\n }\n\n /** Check if a module is currently installed on the account. */\n async isInstalled(\n account: string,\n moduleTypeId: ModuleTypeId,\n module: string,\n ): Promise<boolean> {\n return (await this.provider.readContract({\n address: account as Address,\n abi: parseAbi(AIRACCOUNT_ABI as readonly string[]),\n functionName: \"isModuleInstalled\",\n args: [BigInt(moduleTypeId), module as Address, \"0x\"],\n })) as boolean;\n }\n\n /** Return the install hash for a guardian to sign (r5 format, includes moduleInitData hash). */\n installHash(account: string, moduleTypeId: ModuleTypeId, module: string, moduleInitData: string = \"0x\"): string {\n return buildInstallModuleHash(this.chainId, account, moduleTypeId, module, moduleInitData);\n }\n\n /** Return the uninstall hash for guardians to sign. */\n uninstallHash(account: string, moduleTypeId: ModuleTypeId, module: string): string {\n return buildUninstallModuleHash(this.chainId, account, moduleTypeId, module);\n }\n\n /**\n * Convenience: build install calldata for the standard M7 module set.\n * Uses pre-deployed Sepolia addresses (r4 audit-final). No guardian sigs required when\n * account threshold <= 40 (default for newly created accounts).\n *\n * Note: beta.3 unifies these into SessionKeyValidator. This helper retains the r4\n * addresses for accounts already deployed on r4; new accounts use SessionKeyValidator.\n */\n encodeInstallDefaultModules(account: string): {\n compositeValidator: string;\n tierGuardHook: string;\n } {\n const addresses = AIRACCOUNT_ADDRESSES.sepolia;\n return {\n compositeValidator: this.encodeInstall({\n account,\n moduleTypeId: MODULE_TYPE.VALIDATOR,\n module: addresses.compositeValidatorM7r4,\n }),\n tierGuardHook: this.encodeInstall({\n account,\n moduleTypeId: MODULE_TYPE.HOOK,\n module: addresses.tierGuardHookM7r4,\n }),\n };\n }\n}\n","import {\n getContract,\n encodeFunctionData,\n zeroAddress,\n type Abi,\n type PublicClient,\n} from \"viem\";\n// parseAbi is required to feed the local human-readable string[] ABIs to viem's\n// getContract / encodeFunctionData during the ethers->viem migration. These\n// validator ABIs are not available in @aastar/core.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport {\n SESSION_KEY_VALIDATOR_ABI,\n AGENT_SESSION_KEY_VALIDATOR_ABI,\n} from \"../constants/entrypoint\";\nimport { type ViemContract } from \"../providers/ethereum-provider\";\nimport { readBuildGrantHash, readBuildP256GrantHash } from \"../providers/typed-reads\";\n\n// Parse the local human-readable ABIs once. Widened to `Abi` so viem treats the\n// call args loosely (plain address strings / numbers) — matching the previous\n// ethers.Interface ergonomics without per-call `0x${string}` casts.\nconst SESSION_KEY_VALIDATOR_VIEM_ABI = parseAbi(SESSION_KEY_VALIDATOR_ABI) as Abi;\nconst AGENT_SESSION_KEY_VALIDATOR_VIEM_ABI = parseAbi(AGENT_SESSION_KEY_VALIDATOR_ABI) as Abi;\n\n// ─── M6 SessionKeyValidator ──────────────────────────────────────\n\nexport interface GrantSessionParams {\n /** Account that owns the session */\n account: string;\n /** The session key address (ephemeral EOA) */\n sessionKey: string;\n /** Expiry unix timestamp (max 7 days from now) */\n expiry: number;\n /** address(0) = any destination allowed */\n contractScope?: string;\n /** bytes4(0) = any selector allowed */\n selectorScope?: string;\n /** Max calls per velocityWindow (0 = unlimited). Session struct field. */\n velocityLimit?: number;\n /** Velocity window in seconds (0 = no window). Session struct field. */\n velocityWindow?: number;\n /** Allowed destination addresses ([] = any). Session struct field. */\n callTargets?: string[];\n /** Allowed selectors ([] = any). Session struct field. */\n selectorAllowlist?: string[];\n /** Owner signature over buildGrantHash() — omit if calling directly from account */\n ownerSig?: string;\n}\n\nexport interface SessionInfo {\n expiry: number;\n contractScope: string;\n selectorScope: string;\n revoked: boolean;\n velocityLimit: number;\n velocityWindow: number;\n callTargets: string[];\n selectorAllowlist: string[];\n active: boolean;\n}\n\nexport interface GrantP256SessionParams {\n /** Account that owns the session */\n account: string;\n /** P256 public key X coordinate (0x-prefixed 32-byte hex) */\n keyX: string;\n /** P256 public key Y coordinate (0x-prefixed 32-byte hex) */\n keyY: string;\n /** Expiry unix timestamp (max 7 days from now) */\n expiry: number;\n /** address(0) = any destination allowed */\n contractScope?: string;\n /** bytes4(0) = any selector allowed */\n selectorScope?: string;\n /** Max calls per velocityWindow (0 = unlimited). Session struct field. */\n velocityLimit?: number;\n /** Velocity window in seconds (0 = no window). Session struct field. */\n velocityWindow?: number;\n /** Allowed destination addresses ([] = any). Session struct field. */\n callTargets?: string[];\n /** Allowed selectors ([] = any). Session struct field. */\n selectorAllowlist?: string[];\n /** Owner signature over buildP256GrantHash() — omit if calling directly from the owner EOA */\n ownerSig?: string;\n}\n\n/**\n * The on-chain `Session` struct (8 fields), passed as a single tuple arg to the\n * grant/build functions and returned by getSession/getP256Session. Field order\n * MUST match SessionKeyValidator.sol and packages/core/src/abis/SessionKeyValidator.json:\n * (uint48 expiry, address contractScope, bytes4 selectorScope, bool revoked,\n * uint16 velocityLimit, uint32 velocityWindow, address[] callTargets, bytes4[] selectorAllowlist)\n */\ninterface SessionStruct {\n expiry: number;\n contractScope: string;\n selectorScope: string;\n revoked: boolean;\n velocityLimit: number;\n velocityWindow: number;\n callTargets: string[];\n selectorAllowlist: string[];\n}\n\n/** Build the Session tuple from grant params; `revoked` is always false on grant. */\nfunction buildSessionStruct(params: {\n expiry: number;\n contractScope?: string;\n selectorScope?: string;\n velocityLimit?: number;\n velocityWindow?: number;\n callTargets?: string[];\n selectorAllowlist?: string[];\n}): SessionStruct {\n return {\n expiry: params.expiry,\n contractScope: params.contractScope ?? zeroAddress,\n selectorScope: params.selectorScope ?? \"0x00000000\",\n revoked: false,\n velocityLimit: params.velocityLimit ?? 0,\n velocityWindow: params.velocityWindow ?? 0,\n callTargets: params.callTargets ?? [],\n selectorAllowlist: params.selectorAllowlist ?? [],\n };\n}\n\n/**\n * The raw 8-field Session tuple as decoded by viem. Because the on-chain return\n * type names every tuple component (uint48 expiry, address contractScope, ...),\n * viem returns a NAMED object (not an array), so we read by field name. uint\n * fields come back as `bigint`.\n */\ninterface RawSession {\n expiry: bigint | number;\n contractScope: string;\n selectorScope: string;\n revoked: boolean;\n velocityLimit: bigint | number;\n velocityWindow: bigint | number;\n callTargets: readonly string[];\n selectorAllowlist: readonly string[];\n}\n\n/**\n * Decode the 8-field Session tuple returned by getSession/getP256Session into\n * a SessionInfo, computing the derived `active` flag.\n */\nfunction decodeSessionInfo(session: unknown): SessionInfo {\n const s = session as RawSession;\n const expiry = Number(s.expiry);\n const now = Math.floor(Date.now() / 1000);\n return {\n expiry,\n contractScope: s.contractScope,\n selectorScope: s.selectorScope,\n revoked: s.revoked,\n velocityLimit: Number(s.velocityLimit),\n velocityWindow: Number(s.velocityWindow),\n callTargets: [...(s.callTargets ?? [])],\n selectorAllowlist: [...(s.selectorAllowlist ?? [])],\n active: expiry > now && !s.revoked,\n };\n}\n\n// ─── M7 AgentSessionKeyValidator ─────────────────────────────────\n\nexport interface AgentSessionConfig {\n expiry: number; // Unix timestamp\n velocityLimit: number; // Max calls per velocityWindow (0 = unlimited)\n velocityWindow: number; // Window in seconds\n callTargets: string[]; // Allowed dest addresses (empty = any)\n selectorAllowlist: string[]; // Allowed selectors (empty = any)\n}\n\nexport interface AgentSessionInfo extends AgentSessionConfig {\n revoked: boolean;\n callCount: bigint;\n windowStart: bigint;\n}\n\n/**\n * SessionKeyService — manage M6 (basic) and M7 (agent) session keys.\n *\n * M6 SessionKeyValidator (algId=0x08):\n * Simple time-limited ECDSA/P256 key with optional contract+selector scope.\n * Used for standard delegated actions (hot wallet, automated tasks).\n *\n * M7 AgentSessionKeyValidator (algId=0x09):\n * Rich session key for AI agents: velocity limits, spend caps, call allowlists,\n * hierarchical delegation (parent → sub-agent with scope narrowing).\n */\nexport class SessionKeyService {\n private readonly skValidator: ViemContract;\n private readonly askValidator: ViemContract;\n\n constructor(\n provider: PublicClient,\n sessionKeyValidatorAddress: string,\n agentSessionKeyValidatorAddress: string,\n ) {\n this.skValidator = getContract({\n address: sessionKeyValidatorAddress as `0x${string}`,\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n client: provider,\n }) as unknown as ViemContract;\n this.askValidator = getContract({\n address: agentSessionKeyValidatorAddress as `0x${string}`,\n abi: AGENT_SESSION_KEY_VALIDATOR_VIEM_ABI,\n client: provider,\n }) as unknown as ViemContract;\n }\n\n // ── M6: Basic Session Keys ────────────────────────────────────\n\n /**\n * Build the hash that the account owner must sign to grant a session key.\n * Use grantSession() with this sig, or grantSessionDirect() from the account itself.\n */\n async buildGrantHash(params: Omit<GrantSessionParams, \"ownerSig\">): Promise<string> {\n return readBuildGrantHash(\n this.skValidator,\n params.account,\n params.sessionKey,\n buildSessionStruct(params)\n );\n }\n\n /** Query an ECDSA session key state (decodes the 8-field Session tuple). */\n async getSession(account: string, sessionKey: string): Promise<SessionInfo> {\n const session = await this.skValidator.read.getSession([account, sessionKey]);\n return decodeSessionInfo(session);\n }\n\n /** Check if an ECDSA session is currently active. */\n async isSessionActive(account: string, sessionKey: string): Promise<boolean> {\n return this.skValidator.read.isSessionActive([account, sessionKey]) as Promise<boolean>;\n }\n\n /**\n * Encode calldata for session grant.\n *\n * - **With ownerSig** → `grantSession()` — for gasless/UserOp flows.\n * Owner signs the GRANT_SESSION_V2 typed hash via KMS `sign-grant-session`,\n * then the relayer calls `grantSession(account, key, cfg, ownerSig)` on-chain.\n * This is the ONLY path for ERC-4337 sponsored / gasless grant flows.\n *\n * - **Without ownerSig** → `grantSessionDirect()` — **owner EOA direct-send only**.\n * Since v0.17.2 round 3, `grantSessionDirect` requires `msg.sender == ownerOf(account)`.\n * It does NOT accept `msg.sender == account` (removed in round 3 — confused-deputy fix).\n * Do NOT encode this for a UserOp callData; the EntryPoint is not the owner EOA.\n */\n encodeGrantSession(params: GrantSessionParams): string {\n const cfg = buildSessionStruct(params);\n if (params.ownerSig) {\n return encodeFunctionData({\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"grantSession\",\n args: [params.account, params.sessionKey, cfg, params.ownerSig],\n });\n }\n // grantSessionDirect — owner EOA direct tx only (NOT for UserOp/gasless flows).\n return encodeFunctionData({\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"grantSessionDirect\",\n args: [params.account, params.sessionKey, cfg],\n });\n }\n\n /** Encode calldata for revokeSession(). */\n encodeRevokeSession(account: string, sessionKey: string): string {\n return encodeFunctionData({\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"revokeSession\",\n args: [account, sessionKey],\n });\n }\n\n // ── M6: P256 / Passkey Session Keys ───────────────────────────\n\n /**\n * Build the hash that the account owner must sign to grant a P256/passkey session key.\n * Use grantP256Session() with this sig, or grantP256SessionDirect() from the owner EOA itself.\n * The owner/KMS signs this hash to authorize a gasless grantP256Session().\n */\n async buildP256GrantHash(\n params: Omit<GrantP256SessionParams, \"ownerSig\">,\n ): Promise<string> {\n return readBuildP256GrantHash(\n this.skValidator,\n params.account,\n params.keyX,\n params.keyY,\n buildSessionStruct(params)\n );\n }\n\n /**\n * Query a P256 session key state (decodes the 8-field Session tuple).\n * @param keyHash The keccak256 hash of (keyX, keyY) used as the on-chain session id.\n */\n async getP256Session(account: string, keyHash: string): Promise<SessionInfo> {\n const session = await this.skValidator.read.getP256Session([account, keyHash]);\n return decodeSessionInfo(session);\n }\n\n /** Check if a P256 session is currently active. */\n async isP256SessionActive(account: string, keyX: string, keyY: string): Promise<boolean> {\n return this.skValidator.read.isP256SessionActive([account, keyX, keyY]) as Promise<boolean>;\n }\n\n /**\n * Encode calldata for a P256/passkey session grant.\n *\n * - **With ownerSig** → `grantP256Session()` — for gasless/UserOp flows.\n * Owner signs the buildP256GrantHash() digest via KMS `sign-p256-grant-session`,\n * then the relayer calls `grantP256Session(account, keyX, keyY, cfg, ownerSig)` on-chain.\n * This is the ONLY path for ERC-4337 sponsored / gasless P256 grant flows.\n *\n * - **Without ownerSig** → `grantP256SessionDirect()` — **owner EOA direct-send only**.\n * Since v0.17.2 round 3, `grantP256SessionDirect` requires `msg.sender == ownerOf(account)`.\n * It does NOT accept `msg.sender == account` (removed in round 3 — confused-deputy fix).\n * Do NOT encode this for a UserOp callData; the EntryPoint is not the owner EOA.\n */\n encodeGrantP256Session(params: GrantP256SessionParams): string {\n const cfg = buildSessionStruct(params);\n if (params.ownerSig) {\n return encodeFunctionData({\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"grantP256Session\",\n args: [params.account, params.keyX, params.keyY, cfg, params.ownerSig],\n });\n }\n // grantP256SessionDirect — owner EOA direct tx only (NOT for UserOp/gasless flows).\n return encodeFunctionData({\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"grantP256SessionDirect\",\n args: [params.account, params.keyX, params.keyY, cfg],\n });\n }\n\n /** Encode calldata for revokeP256Session(). */\n encodeRevokeP256Session(account: string, keyX: string, keyY: string): string {\n return encodeFunctionData({\n abi: SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"revokeP256Session\",\n args: [account, keyX, keyY],\n });\n }\n\n // ── M7: Agent Session Keys ────────────────────────────────────\n\n /**\n * Encode calldata for grantAgentSession().\n * Must be called from the account (via UserOp or direct execute).\n * The contract uses msg.sender as the account — no account param needed.\n */\n encodeGrantAgentSession(sessionKey: string, cfg: AgentSessionConfig): string {\n return encodeFunctionData({\n abi: AGENT_SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"grantAgentSession\",\n args: [\n sessionKey,\n {\n expiry: cfg.expiry,\n velocityLimit: cfg.velocityLimit,\n velocityWindow: cfg.velocityWindow,\n revoked: false,\n callTargets: cfg.callTargets,\n selectorAllowlist: cfg.selectorAllowlist,\n },\n ],\n });\n }\n\n /**\n * Encode calldata for delegateSession() — sub-agent delegation.\n * The sub-agent config must be a strict subset of the parent session's scope.\n * Called by the parent session key (not the account owner).\n * @param account The smart account under which the parent session was granted.\n */\n encodeDelegateSession(account: string, subKey: string, subCfg: AgentSessionConfig): string {\n return encodeFunctionData({\n abi: AGENT_SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"delegateSession\",\n args: [\n account,\n subKey,\n {\n expiry: subCfg.expiry,\n velocityLimit: subCfg.velocityLimit,\n velocityWindow: subCfg.velocityWindow,\n revoked: false,\n callTargets: subCfg.callTargets,\n selectorAllowlist: subCfg.selectorAllowlist,\n },\n ],\n });\n }\n\n /** Encode calldata for revokeAgentSession(). */\n encodeRevokeAgentSession(sessionKey: string): string {\n return encodeFunctionData({\n abi: AGENT_SESSION_KEY_VALIDATOR_VIEM_ABI,\n functionName: \"revokeAgentSession\",\n args: [sessionKey],\n });\n }\n\n /** Query agent session config + runtime state. */\n async getAgentSession(account: string, sessionKey: string): Promise<AgentSessionInfo> {\n // Multi-output view fns are returned by viem as a positional array.\n const [expiry, velocityLimit, velocityWindow, revoked, callTargets, selectorAllowlist] =\n (await this.askValidator.read.agentSessions([account, sessionKey])) as readonly unknown[];\n const [callCount, windowStart] =\n (await this.askValidator.read.sessionStates([account, sessionKey])) as readonly unknown[];\n return {\n expiry: Number(expiry),\n velocityLimit: Number(velocityLimit),\n velocityWindow: Number(velocityWindow),\n callTargets: callTargets as string[],\n selectorAllowlist: selectorAllowlist as string[],\n revoked: revoked as boolean,\n callCount: BigInt(callCount as bigint),\n windowStart: BigInt(windowStart as bigint),\n };\n }\n\n /** Check if an agent session is active (not expired, not revoked). */\n async isAgentSessionActive(account: string, sessionKey: string): Promise<boolean> {\n const session = await this.getAgentSession(account, sessionKey);\n return session.expiry > Math.floor(Date.now() / 1000) && !session.revoked;\n }\n\n /** Return the parent account of a delegated session key. */\n async getSessionKeyOwner(sessionKey: string): Promise<string> {\n return this.askValidator.read.sessionKeyOwner([sessionKey]) as Promise<string>;\n }\n\n /** Return the parent key that delegated to subKey, or ZeroAddress if not delegated. */\n async getDelegatedBy(account: string, subKey: string): Promise<string> {\n return this.askValidator.read.delegatedBy([account, subKey]) as Promise<string>;\n }\n}\n\n// ─── UserOp Signature Packing (v0.17.2+) ────────────────────────\n\n/**\n * Pack a secp256k1 session key signature into the 106-byte UserOp.signature format.\n *\n * Layout: [0x08][account(20)][sessionKey(20)][r(32)][s(32)][v(1)]\n *\n * @param account - The AirAccount address (20 bytes, with or without 0x)\n * @param sessionKey - The ephemeral EOA session key address (20 bytes)\n * @param signature - 65-byte hex signature from KMS sign-grant-session (R||S||V)\n * @returns 106-byte hex string (0x-prefixed) suitable as UserOp.signature\n */\nexport function packSecp256k1SessionSignature(\n account: string,\n sessionKey: string,\n signature: string\n): string {\n const acc = account.startsWith(\"0x\") ? account.slice(2) : account;\n const key = sessionKey.startsWith(\"0x\") ? sessionKey.slice(2) : sessionKey;\n const sig = signature.startsWith(\"0x\") ? signature.slice(2) : signature;\n\n if (acc.length !== 40) throw new Error(\"account must be 20 bytes (40 hex chars)\");\n if (key.length !== 40) throw new Error(\"sessionKey must be 20 bytes (40 hex chars)\");\n if (sig.length !== 130) throw new Error(\"signature must be 65 bytes (130 hex chars)\");\n\n // [0x08][account(20)][sessionKey(20)][r(32)][s(32)][v(1)] = 106 bytes\n return `0x08${acc}${key}${sig}`;\n}\n\n/**\n * Pack a P256 session key signature into the 149-byte UserOp.signature format.\n *\n * Layout: [0x08][account(20)][keyX(32)][keyY(32)][r(32)][s(32)]\n *\n * @param account - The AirAccount address (20 bytes)\n * @param keyX - P256 public key X coordinate (32 bytes hex, without 0x)\n * @param keyY - P256 public key Y coordinate (32 bytes hex, without 0x)\n * @param signature - 64-byte hex signature from KMS sign-p256-grant-session (R||S, no V)\n * @returns 149-byte hex string (0x-prefixed) suitable as UserOp.signature\n */\nexport function packP256SessionSignature(\n account: string,\n keyX: string,\n keyY: string,\n signature: string\n): string {\n const acc = account.startsWith(\"0x\") ? account.slice(2) : account;\n const x = keyX.startsWith(\"0x\") ? keyX.slice(2) : keyX;\n const y = keyY.startsWith(\"0x\") ? keyY.slice(2) : keyY;\n const sig = signature.startsWith(\"0x\") ? signature.slice(2) : signature;\n\n if (acc.length !== 40) throw new Error(\"account must be 20 bytes (40 hex chars)\");\n if (x.length !== 64) throw new Error(\"keyX must be 32 bytes (64 hex chars)\");\n if (y.length !== 64) throw new Error(\"keyY must be 32 bytes (64 hex chars)\");\n if (sig.length !== 128) throw new Error(\"P256 signature must be 64 bytes (128 hex chars, R||S)\");\n\n // [0x08][account(20)][keyX(32)][keyY(32)][r(32)][s(32)] = 149 bytes\n return `0x08${acc}${x}${y}${sig}`;\n}\n","import { getContract, zeroAddress, type Address, type PublicClient } from \"viem\";\n// EntryPoint/AirAccount/Guard ABIs are local human-readable signatures (not in @aastar/core);\n// parseAbi is required to feed them to viem's getContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { AIRACCOUNT_ABI, GLOBAL_GUARD_ABI } from \"../constants/entrypoint\";\n\nconst EXTENDED_GUARD_ABI = [\n ...GLOBAL_GUARD_ABI,\n \"function todaySpent() external view returns (uint256)\",\n \"function tokenTodaySpent(address token) external view returns (uint256)\",\n // approvedAlgorithms removed from the guard in v0.17.2-beta.4 — now read from the account.\n \"function tier1Limit() external view returns (uint256)\",\n \"function tier2Limit() external view returns (uint256)\",\n \"function minDailyLimit() external view returns (uint256)\",\n];\n\nexport type TierLevel = 1 | 2 | 3;\n\nexport interface GuardState {\n /** ETH daily limit in wei */\n dailyLimit: bigint;\n /** ETH already spent today in wei */\n todaySpent: bigint;\n /** ETH remaining for today in wei */\n remaining: bigint;\n /** Current tier based on spent amount */\n currentTier: TierLevel;\n /** Tier 1 max spend threshold in wei (single sig) */\n tier1Limit: bigint;\n /** Tier 2 max spend threshold in wei (dual sig) */\n tier2Limit: bigint;\n /** Minimum daily limit floor (cannot decrease below this) */\n minDailyLimit: bigint;\n /** Guard contract address */\n guardAddress: string;\n}\n\nexport interface TokenGuardState {\n token: string;\n todaySpent: bigint;\n dailyLimit: bigint;\n remaining: bigint;\n currentTier: TierLevel;\n tier1Limit: bigint;\n tier2Limit: bigint;\n}\n\n/** Loosely-typed read surface for viem contracts built from human-readable ABIs. */\ntype ReadMethods = Record<string, (args?: unknown[]) => Promise<unknown>>;\n\n/**\n * GuardStateReader — F6: read AAStarGlobalGuard spending state.\n *\n * Enables UI components to show:\n * - Daily spend progress bar\n * - Current required tier (T1/T2/T3) for next transaction\n * - Per-token limits and remaining allowances\n */\nexport class GuardStateReader {\n private readonly provider: PublicClient;\n\n constructor(provider: PublicClient) {\n this.provider = provider;\n }\n\n private accountContract(accountAddress: string) {\n return getContract({\n address: accountAddress as Address,\n abi: parseAbi(AIRACCOUNT_ABI as readonly string[]),\n client: this.provider,\n });\n }\n\n private guardContract(guardAddress: string) {\n return getContract({\n address: guardAddress as Address,\n abi: parseAbi(EXTENDED_GUARD_ABI as readonly string[]),\n client: this.provider,\n });\n }\n\n /**\n * Read the full ETH guard state for an account.\n * Returns null if the account has no guard (dailyLimit=0).\n */\n async getGuardState(accountAddress: string): Promise<GuardState | null> {\n const account = this.accountContract(accountAddress).read as ReadMethods;\n const guardAddress = (await account.guard([])) as string;\n if (guardAddress === zeroAddress) return null;\n\n const guard = this.guardContract(guardAddress).read as ReadMethods;\n const [dailyLimit, remaining, todaySpent, tier1Limit, tier2Limit, minDailyLimit] =\n await Promise.all([\n guard.dailyLimit([]),\n guard.remainingDailyAllowance([]),\n guard.todaySpent([]),\n guard.tier1Limit([]).catch(() => 0n),\n guard.tier2Limit([]).catch(() => 0n),\n guard.minDailyLimit([]).catch(() => 0n),\n ]);\n\n return {\n dailyLimit: BigInt(dailyLimit as bigint),\n todaySpent: BigInt(todaySpent as bigint),\n remaining: BigInt(remaining as bigint),\n currentTier: resolveTierFromSpend(\n BigInt(todaySpent as bigint),\n BigInt(tier1Limit as bigint),\n BigInt(tier2Limit as bigint),\n ),\n tier1Limit: BigInt(tier1Limit as bigint),\n tier2Limit: BigInt(tier2Limit as bigint),\n minDailyLimit: BigInt(minDailyLimit as bigint),\n guardAddress,\n };\n }\n\n /**\n * Read per-token guard state.\n * Returns null if the token is not configured on the guard.\n */\n async getTokenGuardState(\n accountAddress: string,\n token: string,\n ): Promise<TokenGuardState | null> {\n const account = this.accountContract(accountAddress).read as ReadMethods;\n const guardAddress = (await account.guard([])) as string;\n if (guardAddress === zeroAddress) return null;\n\n const guard = this.guardContract(guardAddress).read as ReadMethods;\n try {\n const todaySpent = await guard.tokenTodaySpent([token as Address]);\n // TokenConfig is not directly readable on-chain per token; limits are not fully implemented.\n return {\n token,\n todaySpent: BigInt(todaySpent as bigint),\n dailyLimit: 0n, // token daily limit not directly exposed\n remaining: 0n,\n currentTier: 1 as TierLevel,\n tier1Limit: 0n,\n tier2Limit: 0n,\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Determine the minimum tier required to send a given ETH amount.\n * Useful for showing \"this transfer needs 2 signatures\" before submission.\n */\n async requiredTierForAmount(\n accountAddress: string,\n amountWei: bigint,\n ): Promise<TierLevel> {\n const state = await this.getGuardState(accountAddress);\n if (!state) return 1; // No guard = no tier restriction\n\n const projectedSpend = state.todaySpent + amountWei;\n return resolveTierFromSpend(projectedSpend, state.tier1Limit, state.tier2Limit);\n }\n\n /**\n * Check if a given algorithm ID is approved on the guard.\n */\n async isAlgorithmApproved(accountAddress: string, algId: number): Promise<boolean> {\n // v0.17.2-beta.4: the algorithm whitelist lives on the ACCOUNT (single source of\n // truth, enforced in validateUserOp), not the guard.\n const account = this.accountContract(accountAddress).read as ReadMethods;\n // approvedAlgorithms(uint8 algId): viem requires uint args as bigint.\n return (await account.approvedAlgorithms([BigInt(algId)])) as boolean;\n }\n}\n\n/**\n * Resolve required tier from cumulative spend vs tier thresholds.\n *\n * tier1Limit=0 means no Tier-1 cap (everything is Tier 1).\n * tier2Limit=0 means no Tier-2 cap (anything above tier1 is Tier 2).\n */\nfunction resolveTierFromSpend(\n spent: bigint,\n tier1Limit: bigint,\n tier2Limit: bigint,\n): TierLevel {\n if (tier1Limit === 0n) return 1;\n if (spent < tier1Limit) return 1;\n if (tier2Limit === 0n || spent < tier2Limit) return 2;\n return 3;\n}\n","// eslint-disable-next-line no-restricted-imports -- AIRACCOUNT_FACTORY_ABI is a local human-readable string[] (not in @aastar/core); parseAbi is required to feed it to viem readContract.\nimport { parseAbi, type PublicClient } from \"viem\";\nimport { keccak256 } from \"../../migration/viem/hashing\";\nimport { solidityPacked } from \"../../migration/viem/abi-encoding\";\nimport { AIRACCOUNT_ADDRESSES, AIRACCOUNT_FACTORY_ABI } from \"../constants/entrypoint\";\n\n/**\n * OAPD — One Account Per DApp address derivation (F7).\n *\n * Each DApp gets a unique counterfactual AirAccount address derived from:\n * salt = keccak256(owner ‖ dappId)\n *\n * This prevents DApps from correlating user activity across sites while\n * sharing the same underlying owner key and guardians.\n *\n * The OAPD address is a standard AirAccount clone — it has its own guard,\n * its own daily limits, and can be funded independently.\n */\n\n// Parse the local human-readable factory ABI once so viem reads can consume it.\nconst FACTORY_ABI = parseAbi(AIRACCOUNT_FACTORY_ABI);\n\nexport interface OapdConfig {\n /** Account owner address */\n owner: string;\n /** DApp identifier — use the DApp's domain or contract address */\n dappId: string;\n /** Factory address (defaults to M7 Sepolia) */\n factoryAddress?: string;\n /**\n * InitConfig for the OAPD account.\n * Typically lower daily limits than the main account.\n */\n initConfig: {\n guardians: [string, string, string];\n // v0.20.0 (#120): P-256 guardian keys (bytes32[3] each), inserted after `guardians`.\n // ECDSA-only OAPD accounts pass three zero words for each.\n guardianP256X: [string, string, string];\n guardianP256Y: [string, string, string];\n dailyLimit: bigint;\n approvedAlgIds: number[];\n minDailyLimit: bigint;\n initialTokens: string[];\n initialTokenConfigs: Array<{\n tier1Limit: bigint;\n tier2Limit: bigint;\n dailyLimit: bigint;\n }>;\n };\n}\n\n/**\n * Compute the numeric salt for an OAPD address.\n * salt = uint256(keccak256(abi.encodePacked(owner, dappId)))\n */\nexport function computeOapdSalt(owner: string, dappId: string): bigint {\n const packed = solidityPacked([\"address\", \"string\"], [owner, dappId]);\n return BigInt(keccak256(packed));\n}\n\n/**\n * Predict the counterfactual OAPD address without deploying.\n * Uses the factory's getAddress() view function.\n */\nexport async function getOapdAddress(\n provider: PublicClient,\n config: OapdConfig,\n): Promise<string> {\n const factoryAddress = config.factoryAddress ?? AIRACCOUNT_ADDRESSES.sepolia.factory;\n const salt = computeOapdSalt(config.owner, config.dappId);\n\n return provider.readContract({\n address: factoryAddress as `0x${string}`,\n abi: FACTORY_ABI,\n functionName: \"getAddress\",\n args: [config.owner as `0x${string}`, salt, config.initConfig],\n }) as Promise<string>;\n}\n\n/**\n * Get the OAPD address and its ERC-7828 chain-qualified identifier.\n */\nexport async function getOapdAddressWithChainId(\n provider: PublicClient,\n config: OapdConfig,\n): Promise<{ address: string; chainQualified: string }> {\n const factoryAddress = config.factoryAddress ?? AIRACCOUNT_ADDRESSES.sepolia.factory;\n const salt = computeOapdSalt(config.owner, config.dappId);\n\n const result = (await provider.readContract({\n address: factoryAddress as `0x${string}`,\n abi: FACTORY_ABI,\n functionName: \"getAddressWithChainId\",\n args: [config.owner as `0x${string}`, salt, config.initConfig],\n })) as readonly [string, string];\n return { address: result[0], chainQualified: result[1] };\n}\n\n/**\n * Check if an OAPD account has been deployed yet.\n */\nexport async function isOapdDeployed(\n provider: PublicClient,\n config: OapdConfig,\n): Promise<boolean> {\n const address = await getOapdAddress(provider, config);\n // viem getCode returns the deployed bytecode, or `undefined` when the\n // address has no code (the ethers equivalent returned \"0x\").\n const code = await provider.getCode({ address: address as `0x${string}` });\n return code !== undefined && code !== \"0x\";\n}\n","import { getContract, zeroAddress } from \"viem\";\n// GLOBAL_GUARD_ABI is a local human-readable signature array (not in @aastar/core);\n// parseAbi is required to feed it to viem's getContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { EthereumProvider, type ViemContract } from \"../providers/ethereum-provider\";\nimport {\n readAccountTierLimits,\n readAccountGuardAddress,\n readGuardDailyAllowance,\n readAlgorithmApproved,\n} from \"../providers/typed-reads\";\nimport { GLOBAL_GUARD_ABI } from \"../constants/entrypoint\";\nimport {\n TierConfig,\n GuardStatus,\n PreCheckResult,\n ALG_ECDSA,\n ALG_P256,\n ALG_BLS,\n ALG_CUMULATIVE_T2,\n ALG_CUMULATIVE_T3,\n} from \"../../core/tier\";\nimport { resolveTier, algIdForTier } from \"../../core/tier\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\n\nconst ALG_NAMES: Record<number, string> = {\n [ALG_BLS]: \"BLS (0x01)\",\n [ALG_ECDSA]: \"ECDSA (0x02)\",\n [ALG_P256]: \"P256 (0x03)\",\n [ALG_CUMULATIVE_T2]: \"Cumulative T2 (0x04)\",\n [ALG_CUMULATIVE_T3]: \"Cumulative T3 (0x05)\",\n};\n\n/**\n * Pre-checks transactions against GlobalGuard before submitting on-chain.\n * Avoids wasted gas from predictable reverts.\n */\nexport class GuardChecker {\n private readonly logger: ILogger;\n\n constructor(\n private readonly ethereum: EthereumProvider,\n logger?: ILogger\n ) {\n this.logger = logger ?? new ConsoleLogger(\"[GuardChecker]\");\n }\n\n /**\n * Fetch tier limits from an AirAccount contract.\n */\n async fetchTierConfig(accountAddress: string): Promise<TierConfig> {\n const account = this.ethereum.getAccountContract(accountAddress);\n // Typed wrapper returns both uint256 tier limits as bigint.\n return readAccountTierLimits(account);\n }\n\n /**\n * Fetch guard status from the account's GlobalGuard.\n */\n async fetchGuardStatus(accountAddress: string): Promise<GuardStatus> {\n const account = this.ethereum.getAccountContract(accountAddress);\n\n // getConfigDescription returns a single tuple struct; the typed wrapper reads\n // the `guardAddress` field that decides whether the guard is enforced at all.\n const guardAddress = await readAccountGuardAddress(account);\n\n if (guardAddress === zeroAddress) {\n return {\n hasGuard: false,\n guardAddress: zeroAddress,\n dailyLimit: 0n,\n dailyRemaining: 0n,\n };\n }\n\n const guard = getContract({\n address: guardAddress,\n abi: parseAbi(GLOBAL_GUARD_ABI),\n client: this.ethereum.getProvider(),\n }) as unknown as ViemContract;\n // Typed wrapper returns both uint256 daily-allowance values as bigint.\n const { dailyLimit, dailyRemaining } = await readGuardDailyAllowance(guard);\n\n return {\n hasGuard: true,\n guardAddress,\n dailyLimit,\n dailyRemaining,\n };\n }\n\n /**\n * Pre-check a transaction: determine tier, check guard limits and algorithm approval.\n * Returns errors array (empty = OK to proceed).\n */\n async preCheck(accountAddress: string, value: bigint): Promise<PreCheckResult> {\n const errors: string[] = [];\n\n // Fetch tier config → resolve tier → get algId\n const tierConfig = await this.fetchTierConfig(accountAddress);\n const tier = resolveTier(value, tierConfig);\n const algId = algIdForTier(tier);\n\n // Fetch guard status\n const guard = await this.fetchGuardStatus(accountAddress);\n\n if (!guard.hasGuard) {\n return { ok: true, errors: [], tier, algId };\n }\n\n // Check daily allowance\n if (guard.dailyLimit > 0n && value > guard.dailyRemaining) {\n errors.push(\n `Daily limit exceeded: requesting ${value} wei but only ${guard.dailyRemaining} remaining (limit: ${guard.dailyLimit})`\n );\n }\n\n // Check algorithm approval. v0.17.2-beta.4: the algorithm whitelist is the single\n // source of truth on the ACCOUNT (enforced in validateUserOp), not the guard.\n const accountContract = this.ethereum.getAccountContract(accountAddress);\n const isApproved = await readAlgorithmApproved(accountContract, algId);\n\n if (!isApproved) {\n errors.push(\n `Algorithm ${ALG_NAMES[algId] ?? `0x${algId.toString(16)}`} is not approved by the account`\n );\n }\n\n if (errors.length > 0) {\n this.logger.warn(`Pre-check failed for ${accountAddress}: ${errors.join(\"; \")}`);\n }\n\n return { ok: errors.length === 0, errors, tier, algId };\n }\n}\n","import {\n getContract,\n encodeFunctionData,\n type Address,\n type Hex,\n type PublicClient,\n type WalletClient,\n} from \"viem\";\n// FORCE_EXIT_ABI is a local human-readable signature array (not in @aastar/core);\n// parseAbi is required to feed it to viem's getContract / encodeFunctionData during\n// the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { encodeAbiParams } from \"../../migration/viem/abi-encoding\";\nimport type { ViemContract } from \"../providers/ethereum-provider\";\n\n// ForceExitModule ABI — minimal subset for SDK use\nconst FORCE_EXIT_ABI = [\n // ERC-7579 module lifecycle\n \"function onInstall(bytes calldata data) external\",\n \"function onUninstall(bytes calldata data) external\",\n \"function isInitialized(address smartAccount) external view returns (bool)\",\n // Proposal lifecycle\n \"function proposeForceExit(address target, uint256 value, bytes calldata data) external\",\n \"function approveForceExit(address account, bytes calldata guardianSig) external\",\n \"function executeForceExit(address account) external\",\n \"function cancelForceExit(address account) external\",\n // State readers\n \"function getPendingExit(address account) external view returns (address target, uint256 value, bytes memory data, uint256 proposedAt, uint256 approvalBitmap, address[3] memory guardians)\",\n \"function accountL2Type(address account) external view returns (uint8)\",\n // Constants\n \"function APPROVAL_THRESHOLD() external view returns (uint8)\",\n \"function MODULE_VERSION() external view returns (string)\",\n // Errors (for decoding reverts)\n \"error AlreadyApproved()\",\n \"error AlreadyProposed()\",\n \"error ForceExitCallFailed()\",\n \"error IncompatibleAccount()\",\n \"error InvalidGuardianSig()\",\n \"error NoProposal()\",\n \"error NotEnoughApprovals()\",\n \"error NotInstalled()\",\n \"error NotOwner()\",\n \"error SignerNoLongerGuardian()\",\n \"error UnsupportedL2Type()\",\n];\n\n// Parsed once at module load — fed to getContract (reads/writes) and encodeFunctionData.\nconst FORCE_EXIT_PARSED_ABI = parseAbi(FORCE_EXIT_ABI as readonly string[]);\n\nexport const L2_TYPE = {\n OPTIMISM: 1,\n ARBITRUM: 2,\n} as const;\n\nexport type L2Type = (typeof L2_TYPE)[keyof typeof L2_TYPE];\n\nexport interface PendingExit {\n target: string;\n value: bigint;\n data: string;\n proposedAt: bigint;\n approvalBitmap: bigint;\n guardians: [string, string, string];\n}\n\n/**\n * A viem client capable of backing the ForceExit contract. A `PublicClient`\n * alone enables the on-chain reads; a `WalletClient` (or the `{ public, wallet }`\n * pair) is required for the state-changing `proposeForceExit`/`approveForceExit`/\n * etc. transactions. This replaces the old `ethers.Provider | ethers.Signer`\n * argument (provider = reads, signer = reads + writes).\n */\nexport type ForceExitClient =\n | PublicClient\n | WalletClient\n | { public: PublicClient; wallet: WalletClient };\n\n/**\n * ForceExitService — typed wrappers for ForceExitModule ERC-7579 emergency L2→L1 exit.\n *\n * Flow:\n * 1. Owner installs module via account.installModule(2, forceExitModuleAddr, encodeOnInstall(L2_TYPE.OPTIMISM))\n * 2. Any party calls proposeForceExit(target, value, data) to submit a bridge-out proposal\n * 3. 2-of-3 guardians each call approveForceExit(account, guardianSig) within their window\n * 4. Anyone calls executeForceExit(account) once threshold is met — triggers L2→L1 bridge call\n *\n * The module is an ERC-7579 Executor (moduleTypeId=2) — call installModule on the account, not here.\n */\nexport class ForceExitService {\n private readonly contract: ViemContract;\n\n constructor(\n private readonly moduleAddress: string,\n client: ForceExitClient\n ) {\n this.contract = getContract({\n address: moduleAddress as Address,\n abi: FORCE_EXIT_PARSED_ABI,\n // viem inspects the client's actions at runtime to expose read/write; the\n // cast only satisfies the static union — a wallet client still yields writes.\n client: client as unknown as PublicClient,\n }) as unknown as ViemContract;\n }\n\n // ── On-chain reads ──────────────────────────────────────────────\n\n async isInitialized(smartAccount: string): Promise<boolean> {\n return (await this.contract.read.isInitialized([smartAccount as Address])) as boolean;\n }\n\n async getPendingExit(account: string): Promise<PendingExit> {\n const [target, value, data, proposedAt, approvalBitmap, guardians] =\n (await this.contract.read.getPendingExit([account as Address])) as [\n string,\n bigint,\n string,\n bigint,\n bigint,\n [string, string, string],\n ];\n return {\n target,\n value: BigInt(value),\n data,\n proposedAt: BigInt(proposedAt),\n approvalBitmap: BigInt(approvalBitmap),\n guardians,\n };\n }\n\n async getAccountL2Type(account: string): Promise<number> {\n return Number(await this.contract.read.accountL2Type([account as Address]));\n }\n\n async getApprovalThreshold(): Promise<number> {\n return Number(await this.contract.read.APPROVAL_THRESHOLD([]));\n }\n\n async getModuleVersion(): Promise<string> {\n return (await this.contract.read.MODULE_VERSION([])) as string;\n }\n\n // ── Calldata encoders (for UserOp or direct tx submission) ─────\n\n /**\n * Encode onInstall calldata for installModule() call on the smart account.\n * Must be submitted by the account owner, with moduleTypeId=2 (EXECUTOR).\n *\n * @param l2Type - L2_TYPE.OPTIMISM (1) or L2_TYPE.ARBITRUM (2)\n * @example\n * const calldata = forceExit.encodeOnInstall(L2_TYPE.OPTIMISM);\n * // account.installModule(2, forceExitModuleAddress, calldata)\n */\n encodeOnInstall(l2Type: L2Type): string {\n return encodeFunctionData({\n abi: FORCE_EXIT_PARSED_ABI,\n functionName: \"onInstall\",\n args: [encodeAbiParams([\"uint8\"], [l2Type])],\n });\n }\n\n encodeOnUninstall(): string {\n return encodeFunctionData({\n abi: FORCE_EXIT_PARSED_ABI,\n functionName: \"onUninstall\",\n args: [\"0x\"],\n });\n }\n\n /**\n * Encode calldata for proposeForceExit — the exit payload to bridge out of L2.\n * `target` is the L2→L1 bridge contract; `data` is the bridge call payload.\n */\n encodeProposeForceExit(target: string, value: bigint, data: string): string {\n return encodeFunctionData({\n abi: FORCE_EXIT_PARSED_ABI,\n functionName: \"proposeForceExit\",\n args: [target as Address, value, data as Hex],\n });\n }\n\n /**\n * Encode calldata for approveForceExit — guardian signs off on the pending proposal.\n * `guardianSig` must be an EIP-191 personal_sign over the proposal hash.\n */\n encodeApproveForceExit(account: string, guardianSig: string): string {\n return encodeFunctionData({\n abi: FORCE_EXIT_PARSED_ABI,\n functionName: \"approveForceExit\",\n args: [account as Address, guardianSig as Hex],\n });\n }\n\n encodeExecuteForceExit(account: string): string {\n return encodeFunctionData({\n abi: FORCE_EXIT_PARSED_ABI,\n functionName: \"executeForceExit\",\n args: [account as Address],\n });\n }\n\n encodeCancelForceExit(account: string): string {\n return encodeFunctionData({\n abi: FORCE_EXIT_PARSED_ABI,\n functionName: \"cancelForceExit\",\n args: [account as Address],\n });\n }\n\n // ── Convenience: send transactions (requires a WalletClient) ──────────\n\n async proposeForceExit(target: string, value: bigint, data: string): Promise<Hex> {\n return (await this.contract.write.proposeForceExit([\n target as Address,\n value,\n data as Hex,\n ])) as Hex;\n }\n\n async approveForceExit(account: string, guardianSig: string): Promise<Hex> {\n return (await this.contract.write.approveForceExit([\n account as Address,\n guardianSig as Hex,\n ])) as Hex;\n }\n\n async executeForceExit(account: string): Promise<Hex> {\n return (await this.contract.write.executeForceExit([account as Address])) as Hex;\n }\n\n async cancelForceExit(account: string): Promise<Hex> {\n return (await this.contract.write.cancelForceExit([account as Address])) as Hex;\n }\n}\n","import {\n encodeAbiParameters,\n encodeFunctionData,\n keccak256,\n zeroAddress,\n type Abi,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\n// AIRACCOUNT_ABI is a local human-readable `string[]` signature set (not available\n// in @aastar/core), so parseAbi is required to feed it to viem's encode/read calls.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { AIRACCOUNT_ABI } from \"../constants/entrypoint\";\n\n/**\n * Parsed AirAccount ABI shared by the encoders and on-chain reads. Cast to the\n * loose `Abi` type so `encodeFunctionData`/`readContract` accept dynamic\n * function names and return `unknown` (mirrors the old `ethers.Interface` /\n * `ethers.Contract` dynamic surface).\n */\nconst AIRACCOUNT_ABI_PARSED = parseAbi(AIRACCOUNT_ABI) as Abi;\n\n/**\n * RECOVERY_THRESHOLD — number of distinct guardian approvals required to recover\n * (or to cancel a recovery). The contract hard-codes `RECOVERY_THRESHOLD = 2`\n * against a maximum of 3 guardians, i.e. a 2-of-3 social-recovery scheme.\n *\n * Source of truth: `AAStarAirAccountBase.RECOVERY_THRESHOLD` (internal constant).\n */\nexport const RECOVERY_THRESHOLD = 2;\n\n/**\n * MAX_GUARDIANS — the account stores at most 3 guardians (packed slots 12-14).\n * Source: `AAStarAirAccountBase.addGuardian` (`_guardianCount >= 3` reverts).\n */\nexport const MAX_GUARDIANS = 3;\n\n/**\n * RECOVERY_TIMELOCK_SECONDS — delay between `proposeRecovery` and the earliest\n * `executeRecovery`. The contract hard-codes `RECOVERY_TIMELOCK = 2 days`\n * (172800 seconds).\n *\n * NOTE: the prose in `docs/abi/capabilities.md` says \"72h\"; the deployed\n * contract uses 2 days (48h). The on-chain constant is authoritative.\n *\n * Source of truth: `AAStarAirAccountBase.RECOVERY_TIMELOCK` (internal constant).\n */\nexport const RECOVERY_TIMELOCK_SECONDS = 2n * 24n * 60n * 60n; // 2 days\n\n/**\n * GUARDIAN_SIG_VERSION — version byte folded into every guardian-signed challenge\n * (domain-separates signatures across contract versions). Source of truth:\n * `AAStarAirAccountBase.GUARDIAN_SIG_VERSION` (== 4 since v0.20.0).\n */\nexport const GUARDIAN_SIG_VERSION = 4;\n\n/**\n * P256_GUARDIAN_SENTINEL — the address stored in a guardian slot occupied by a\n * P-256 (WebAuthn) guardian; the real secp256r1 key lives in a side mapping. For\n * a plain ECDSA guardian the slot stores the guardian's own EOA address instead.\n * Source: `AAStarAirAccountBase.P256_GUARDIAN_SENTINEL` (`address(0x7026)`).\n */\nexport const P256_GUARDIAN_SENTINEL: Address = \"0x0000000000000000000000000000000000007026\";\n\n/**\n * Decoded view of the account's `activeRecovery()` struct (RecoveryProposal).\n *\n * On-chain layout (`AAStarAgentStorageLayout.RecoveryProposal`):\n * - newOwner : proposed new owner (address(0) ⇒ no active recovery)\n * - proposedAt : block.timestamp when the recovery was proposed\n * - approvalBitmap : bit i set ⇒ guardian[i] approved (2-of-3 to execute)\n * - cancellationBitmap : bit i set ⇒ guardian[i] voted to cancel (2-of-3 to cancel)\n *\n * The remaining fields are SDK-side conveniences derived from those values.\n */\nexport interface ActiveRecovery {\n /** Proposed new owner. `0x0000…0000` means there is no active recovery. */\n newOwner: string;\n /** `block.timestamp` at which the recovery was proposed (seconds). */\n proposedAt: bigint;\n /** Bitmap of guardian approvals (bit i ⇒ guardian[i] approved). */\n approvalBitmap: bigint;\n /** Bitmap of guardian cancel votes (bit i ⇒ guardian[i] voted to cancel). */\n cancellationBitmap: bigint;\n /** Number of distinct guardian approvals (popcount of `approvalBitmap`). */\n approvalCount: number;\n /** Number of distinct guardian cancel votes (popcount of `cancellationBitmap`). */\n cancellationCount: number;\n /** Earliest timestamp at which `executeRecovery` may succeed (`proposedAt + timelock`). */\n executeAfter: bigint;\n /** True when a recovery is currently active (`newOwner != address(0)`). */\n isActive: boolean;\n}\n\n/** Count the set bits of a non-negative bigint (guardian bitmap popcount). */\nfunction popcount(value: bigint): number {\n let v = value;\n let count = 0;\n while (v > 0n) {\n count += Number(v & 1n);\n v >>= 1n;\n }\n return count;\n}\n\n/**\n * RecoveryService — typed wrappers for AirAccount's on-chain social / guardian\n * recovery (capability F28). Unlike `ForceExitService` (an ERC-7579 module),\n * these functions live directly on the account contract, so every encoded\n * calldata below is meant to be submitted **to the account address itself**\n * (via a direct tx or a UserOp).\n *\n * ## Threshold & timelock\n * 2-of-3 guardians ({@link RECOVERY_THRESHOLD} of {@link MAX_GUARDIANS}), with a\n * {@link RECOVERY_TIMELOCK_SECONDS} (2-day) delay before execution.\n *\n * ## Lifecycle & who-can-call\n * 1. `addGuardian(guardian)` — **owner only**. Registers a guardian (max 3).\n * 2. `proposeRecovery(newOwner)` — **any guardian**. Starts the timelock and\n * records the proposer's approval bit (counts as the first of 2 approvals).\n * 3. `approveRecovery()` — **another guardian**. Sets its approval bit; once\n * 2-of-3 approvals are reached the threshold is satisfied.\n * 4. `executeRecovery()` — **anyone**, but only after the timelock has elapsed\n * AND the approval threshold is met. Rotates `owner` to `newOwner`.\n * 5. `cancelRecovery()` — **guardians only** (2-of-3 votes). The owner cannot\n * cancel: a thief who stole the owner key must not be able to block a\n * legitimate recovery. Each guardian votes independently.\n * 6. `removeGuardian(index, guardianSigs)` — **owner**, but additionally\n * requires >= {@link RECOVERY_THRESHOLD} guardian signatures over the\n * removal hash (and cannot drop below 2 guardians).\n *\n * Guardian signatures are domain-separated per operation (the contract hashes a\n * per-op label such as \"REMOVE_GUARDIAN\") to prevent cross-operation replay.\n *\n * ## Re-proposing\n * A new proposal reverts with `RecoveryAlreadyActive` while one is pending. The\n * docs reference a `clearStaleRecovery()` helper, but that function is NOT\n * present in the deployed V7 ABI/contract — a stale proposal must instead be\n * cleared via guardian `cancelRecovery()` votes before re-proposing.\n */\nexport class RecoveryService {\n /**\n * @param client viem read client (was `ethers.Provider | ethers.Signer`). Only\n * on-chain reads are performed here; calldata encoders are pure and never\n * touch the client.\n */\n constructor(private readonly client: PublicClient) {}\n\n // ── Calldata encoders (submit TO the account address) ─────────────\n\n /**\n * Encode `addGuardian(guardian)` calldata. **Owner only.**\n * Registers a recovery guardian; reverts once 3 guardians are set, or if the\n * guardian is `address(0)`, the owner, or already registered.\n */\n encodeAddGuardian(guardian: string): string {\n return encodeFunctionData({\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"addGuardian\",\n args: [guardian as Address],\n });\n }\n\n /**\n * Encode `removeGuardian(index, guardianSigs)` calldata. **Owner only**, and\n * requires >= {@link RECOVERY_THRESHOLD} guardian signatures over the removal\n * hash. Cannot remove while a recovery is active, nor drop below 2 guardians.\n *\n * @param index Guardian slot to remove (0-indexed).\n * @param guardianSigs EIP-191 guardian signatures over the removal hash.\n */\n encodeRemoveGuardian(index: number, guardianSigs: string[]): string {\n return encodeFunctionData({\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"removeGuardian\",\n args: [index, guardianSigs as Hex[]],\n });\n }\n\n /**\n * Build the RAW (un-prefixed) challenge hash that each guardian must sign to\n * authorize `removeGuardian(index, ...)` / `removeGuardianWithMixedSigs(...)`.\n *\n * ## v0.20.0 breaking change (#120 final-review [HIGH], spec §6.4)\n * The signed `opData` changed from `abi.encode(nonce, guardianToRemove)` to\n * `abi.encode(nonce, index, guardianToRemove, p256X, p256Y)` — it now binds the\n * SLOT INDEX and the slot's P-256 key. Because P-256 guardians all share the\n * sentinel address, the old 2-field payload was identical for every P-256 slot,\n * so a signature collected to remove slot A could be replayed to remove slot B\n * (or survive a key rotation). The new 5-field payload affects EVERY removal,\n * including the plain ECDSA path: for an ECDSA slot `p256X`/`p256Y` are both\n * `bytes32(0)`, but the payload STRUCTURE (extra `index` + two key words) still\n * changed, so the ECDSA `removeGuardian` signing payload MUST use this encoding.\n *\n * Hash construction (matches `AAStarAirAccountBase._guardianOpHash`):\n * ```\n * opData = abi.encode(uint256 nonce, uint8 index, address guardianToRemove,\n * bytes32 p256X, bytes32 p256Y)\n * challenge = keccak256(abi.encode(uint8 GUARDIAN_SIG_VERSION, uint256 chainId,\n * address account, \"REMOVE_GUARDIAN\", bytes opData))\n * ```\n * The contract additionally applies `toEthSignedMessageHash()` before\n * `ecrecover`, so this returns the RAW inner hash and each guardian signs it via\n * `personal_sign` / `signMessage({ raw: hash })` (which adds the EIP-191 prefix).\n * Do NOT pre-apply the prefix here (mirrors `buildGuardianAcceptanceHash`).\n *\n * @param account The AirAccount address whose guardian is being removed.\n * @param chainId EVM chain id (bound into the challenge).\n * @param removalNonce Current `_guardianRemovalNonce` — there is no on-chain\n * getter (internal storage slot 15), so the caller tracks\n * it (starts at 0, increments once per successful removal).\n * @param index Guardian slot being removed (0-indexed, < guardianCount).\n * @param guardianToRemove Address stored in that slot (a P-256 slot stores\n * {@link P256_GUARDIAN_SENTINEL}; an ECDSA slot stores the EOA).\n * @param p256X Slot's P-256 x coordinate; `bytes32(0)` for an ECDSA slot (default).\n * @param p256Y Slot's P-256 y coordinate; `bytes32(0)` for an ECDSA slot (default).\n * @returns raw hex keccak256 challenge — guardians sign it with `personal_sign`.\n */\n buildRemoveGuardianHash(args: {\n account: string;\n chainId: number | bigint;\n removalNonce: bigint;\n index: number;\n guardianToRemove: string;\n p256X?: Hex;\n p256Y?: Hex;\n }): Hex {\n const ZERO32: Hex =\n \"0x0000000000000000000000000000000000000000000000000000000000000000\";\n const opData = encodeAbiParameters(\n [\n { type: \"uint256\" }, // _guardianRemovalNonce\n { type: \"uint8\" }, // index\n { type: \"address\" }, // guardianToRemove\n { type: \"bytes32\" }, // p256X (0 for ECDSA slot)\n { type: \"bytes32\" }, // p256Y (0 for ECDSA slot)\n ],\n [\n args.removalNonce,\n args.index,\n args.guardianToRemove as Address,\n args.p256X ?? ZERO32,\n args.p256Y ?? ZERO32,\n ],\n );\n return keccak256(\n encodeAbiParameters(\n [\n { type: \"uint8\" }, // GUARDIAN_SIG_VERSION\n { type: \"uint256\" }, // chainId\n { type: \"address\" }, // address(this) — the account\n { type: \"string\" }, // opLabel\n { type: \"bytes\" }, // opData\n ],\n [\n GUARDIAN_SIG_VERSION,\n BigInt(args.chainId),\n args.account as Address,\n \"REMOVE_GUARDIAN\",\n opData,\n ],\n ),\n );\n }\n\n /**\n * Encode `proposeRecovery(newOwner)` calldata. **Any guardian** may call.\n * Starts the {@link RECOVERY_TIMELOCK_SECONDS} timelock and records the\n * proposer's approval (1 of {@link RECOVERY_THRESHOLD}).\n */\n encodeProposeRecovery(newOwner: string): string {\n return encodeFunctionData({\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"proposeRecovery\",\n args: [newOwner as Address],\n });\n }\n\n /**\n * Encode `approveRecovery()` calldata. **Another guardian** approves the\n * active proposal, setting its bit in `approvalBitmap`.\n */\n encodeApproveRecovery(): string {\n return encodeFunctionData({\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"approveRecovery\",\n args: [],\n });\n }\n\n /**\n * Encode `cancelRecovery()` calldata. **Guardians only** — each call is one\n * vote; recovery is dropped once {@link RECOVERY_THRESHOLD} cancel votes are\n * reached. The owner cannot cancel.\n */\n encodeCancelRecovery(): string {\n return encodeFunctionData({\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"cancelRecovery\",\n args: [],\n });\n }\n\n /**\n * Encode `executeRecovery()` calldata. **Anyone** may call, but it only\n * succeeds once the timelock has elapsed and the approval threshold is met.\n * Rotates the account owner to the proposed `newOwner`.\n */\n encodeExecuteRecovery(): string {\n return encodeFunctionData({\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"executeRecovery\",\n args: [],\n });\n }\n\n // ── On-chain reads (against the account address) ──────────────────\n\n /**\n * Read and decode the account's `activeRecovery()` struct.\n * Returns derived `approvalCount`, `cancellationCount`, `executeAfter`, and\n * `isActive` alongside the raw fields.\n *\n * @param account The AirAccount address to query.\n */\n async getActiveRecovery(account: string): Promise<ActiveRecovery> {\n const [newOwner, proposedAt, approvalBitmap, cancellationBitmap] =\n (await this.client.readContract({\n address: account as Address,\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"activeRecovery\",\n })) as readonly [Address, bigint, bigint, bigint];\n\n const proposedAtBn = BigInt(proposedAt);\n const approvalBitmapBn = BigInt(approvalBitmap);\n const cancellationBitmapBn = BigInt(cancellationBitmap);\n\n return {\n newOwner: newOwner as string,\n proposedAt: proposedAtBn,\n approvalBitmap: approvalBitmapBn,\n cancellationBitmap: cancellationBitmapBn,\n approvalCount: popcount(approvalBitmapBn),\n cancellationCount: popcount(cancellationBitmapBn),\n executeAfter: proposedAtBn + RECOVERY_TIMELOCK_SECONDS,\n isActive: (newOwner as string).toLowerCase() !== zeroAddress,\n };\n }\n\n /**\n * Read the number of registered guardians via `guardianCount()`.\n *\n * @param account The AirAccount address to query.\n */\n async getGuardianCount(account: string): Promise<number> {\n const count = (await this.client.readContract({\n address: account as Address,\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"guardianCount\",\n })) as number | bigint;\n return Number(count);\n }\n\n /**\n * Read the full guardian address list.\n *\n * The V7 account exposes positional `guardians(uint256 i)` (3 packed slots) plus\n * `guardianCount()` — there is no single `getGuardians()` getter on the account\n * (that exists only on `AirAccountDelegate`, the EIP-7702 path). This reads slots\n * `0..guardianCount-1` and returns the non-zero guardian addresses.\n *\n * @param account The AirAccount address to query.\n */\n async getGuardians(account: string): Promise<string[]> {\n const count = Number(\n (await this.client.readContract({\n address: account as Address,\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"guardianCount\",\n })) as number | bigint\n );\n const guardians: string[] = [];\n for (let i = 0; i < count; i++) {\n const g = (await this.client.readContract({\n address: account as Address,\n abi: AIRACCOUNT_ABI_PARSED,\n functionName: \"guardians\",\n args: [BigInt(i)],\n })) as string;\n if (g.toLowerCase() !== zeroAddress) guardians.push(g);\n }\n return guardians;\n }\n}\n","import { encodeFunctionData, type Abi, type Address, type Hex, type PublicClient } from \"viem\";\n// DELEGATE_ABI is a local human-readable signature array (not in @aastar/core);\n// parseAbi is required to feed it to viem encodeFunctionData / readContract during\n// the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport {\n buildAuthorizationHash as buildAuthorizationHashViem,\n verifyAuthorization as verifyAuthorizationViem,\n} from \"../../migration/viem/signatures\";\n\n// AirAccountDelegate ABI — subset for SDK use\nconst DELEGATE_ABI = [\n \"function initialize(address guardian1, bytes calldata g1Sig, address guardian2, bytes calldata g2Sig, uint256 dailyLimit) external\",\n \"function owner() external view returns (address)\",\n \"function isInitialized() external view returns (bool)\",\n \"function entryPoint() external view returns (address)\",\n \"function getGuardians() external view returns (address[3] memory)\",\n \"function getDeposit() external view returns (uint256)\",\n \"function execute(address dest, uint256 value, bytes calldata data) external\",\n \"function executeBatch(address[] calldata dest, uint256[] calldata value, bytes[] calldata data) external\",\n \"function validateUserOp((address sender, uint256 nonce, bytes initCode, bytes callData, bytes32 accountGasLimits, uint256 preVerificationGas, bytes32 gasFees, bytes paymasterAndData, bytes signature) calldata userOp, bytes32 userOpHash, uint256 missingFunds) external returns (uint256)\",\n \"function initiateRescue(address rescueTo) external\",\n \"function approveRescue() external\",\n \"function cancelRescue() external\",\n \"function executeRescue() external\",\n \"function addDeposit() external payable\",\n \"function withdrawDepositTo(address to, uint256 amount) external\",\n \"error AlreadyInitialized()\",\n \"error NotInitialized()\",\n \"error InvalidAddress()\",\n \"error InvalidGuardianSignature()\",\n];\n\n// Sepolia AirAccountDelegate singleton deployment (unchanged since beta.1)\nexport const AIR_ACCOUNT_DELEGATE_ADDRESS = \"0x8603AAF6C3f07fdae810B323c95a198D796EC52E\";\n\nexport interface DelegateInitParams {\n /** Guardian 1 address */\n guardian1: string;\n /** EIP-712 acceptance signature from guardian 1 */\n guardian1Sig: string;\n /** Guardian 2 address */\n guardian2: string;\n /** EIP-712 acceptance signature from guardian 2 */\n guardian2Sig: string;\n /** Daily ETH spend limit in wei */\n dailyLimit: bigint;\n}\n\nexport interface EIP7702Authorization {\n /** Chain ID (e.g. 11155111 for Sepolia) */\n chainId: number;\n /** The delegation target — AirAccountDelegate singleton address */\n address: string;\n /** EOA nonce at time of signing */\n nonce: bigint;\n /** Signature over the EIP-7702 authorization hash (65 bytes, R||S||V) */\n signature: string;\n}\n\n/**\n * EIP7702DelegateService — Path A: SDK payload construction for AirAccountDelegate.\n *\n * Path A applies when the integrator controls the private key (KMS, server-side signer,\n * embedded wallet). The EOA signs a SET_CODE authorization offline; the integrator's relay\n * submits a Type-4 transaction to activate the delegation.\n *\n * This service does NOT submit transactions — it produces signed payloads for relay.\n *\n * Deployed address: AirAccountDelegate singleton at AIR_ACCOUNT_DELEGATE_ADDRESS (Sepolia).\n * The user's EOA address does NOT change — only its bytecode pointer changes to 0xef0100||addr.\n *\n * Usage:\n * 1. Build SET_CODE authorization payload (call signer.signAuthorization externally — viem)\n * 2. Build initialize() calldata for the first UserOp / direct tx\n * 3. Submit both via integrator's relay\n */\nexport class EIP7702DelegateService {\n /** Parsed ABI (loose viem `Abi` shape) used for encoding calldata and on-chain reads. */\n private readonly abi: Abi;\n /** Optional viem read client (was `ethers.Provider | ethers.Signer`). Required only for on-chain reads. */\n private readonly client?: PublicClient;\n\n constructor(\n private readonly delegateAddress: string = AIR_ACCOUNT_DELEGATE_ADDRESS,\n client?: PublicClient\n ) {\n this.abi = parseAbi(DELEGATE_ABI);\n this.client = client;\n }\n\n // ── Calldata encoders ─────────────────────────────────────────\n\n /**\n * Encode initialize() calldata for the first post-delegation UserOp.\n * Must be the callData of a UserOp sent immediately after the SET_CODE delegation activates.\n * Guardian acceptance sigs follow the same EIP-712 scheme as AirAccountV7 createAccount.\n */\n encodeInitialize(params: DelegateInitParams): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"initialize\",\n args: [\n params.guardian1,\n params.guardian1Sig,\n params.guardian2,\n params.guardian2Sig,\n params.dailyLimit,\n ],\n });\n }\n\n encodeExecute(dest: string, value: bigint, data: string): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"execute\",\n args: [dest, value, data],\n });\n }\n\n encodeExecuteBatch(\n dests: string[],\n values: bigint[],\n datas: string[]\n ): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"executeBatch\",\n args: [dests, values, datas],\n });\n }\n\n // ── EIP-7702 authorization hash construction ──────────────────\n\n /**\n * Compute the EIP-7702 SET_CODE authorization hash that the EOA must sign.\n *\n * Hash = keccak256(0x05 || RLP([chainId, address, nonce]))\n *\n * This is the hash the private key signs to delegate code execution to\n * AirAccountDelegate. Use this hash with your KMS sign-hash endpoint or\n * local viem account.\n *\n * @param chainId - Target chain ID (11155111 for Sepolia)\n * @param nonce - EOA's current transaction nonce\n * @returns 32-byte hash (0x-prefixed) ready for signing\n */\n buildAuthorizationHash(chainId: number, nonce: bigint): string {\n return buildAuthorizationHashViem(chainId, nonce, this.delegateAddress as Address);\n }\n\n /**\n * Build the full EIP-7702 authorization object for relay submission.\n * The caller must sign `buildAuthorizationHash()` externally and pass the result here.\n *\n * @param chainId - Target chain ID\n * @param nonce - EOA's current nonce\n * @param signature - 65-byte ECDSA signature (R||S||V) over the authorization hash\n */\n buildAuthorization(\n chainId: number,\n nonce: bigint,\n signature: string\n ): EIP7702Authorization {\n return {\n chainId,\n address: this.delegateAddress,\n nonce,\n signature,\n };\n }\n\n /**\n * Verify that a signature is a valid EIP-7702 authorization for the given EOA address.\n * Recovers the signer from the authorization hash and checks it matches `eoa`.\n *\n * NOTE: now async — viem's `recoverAddress` is asynchronous (ethers' was sync).\n */\n verifyAuthorization(\n eoa: string,\n chainId: number,\n nonce: bigint,\n signature: string\n ): Promise<boolean> {\n return verifyAuthorizationViem(\n eoa as Address,\n chainId,\n nonce,\n signature as Hex,\n this.delegateAddress as Address\n );\n }\n\n // ── On-chain reads (requires provider) ───────────────────────\n\n async isInitialized(eoa: string): Promise<boolean> {\n if (!this.client) throw new Error(\"EIP7702DelegateService: provider required for on-chain reads\");\n return (await this.client.readContract({\n address: eoa as Address,\n abi: this.abi,\n functionName: \"isInitialized\",\n })) as boolean;\n }\n\n async getOwner(eoa: string): Promise<string> {\n if (!this.client) throw new Error(\"EIP7702DelegateService: provider required for on-chain reads\");\n return (await this.client.readContract({\n address: eoa as Address,\n abi: this.abi,\n functionName: \"owner\",\n })) as string;\n }\n\n async getGuardians(eoa: string): Promise<[string, string, string]> {\n if (!this.client) throw new Error(\"EIP7702DelegateService: provider required for on-chain reads\");\n return (await this.client.readContract({\n address: eoa as Address,\n abi: this.abi,\n functionName: \"getGuardians\",\n })) as [string, string, string];\n }\n}\n","import { encodeFunctionData, type Hex, type PublicClient } from \"viem\";\n// The weighted-signature ABI below is a local human-readable `string[]` signature set\n// (not available in @aastar/core), so parseAbi is required to feed it to viem's\n// encodeFunctionData/readContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\n\n// AAStarAirAccount weighted-signature governance ABI — minimal subset for SDK use.\n// These functions live on the ACCOUNT itself (algId 0x07 / AirAccountExtension),\n// NOT on a separate ERC-7579 module. The WeightConfig tuple field order is\n// authoritative and matches packages/core/src/abis/AAStarAirAccountV7.json exactly.\nconst WEIGHTED_SIGNATURE_ABI = [\n // Direct owner set (first-time / strengthening only)\n \"function setWeightConfig((uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold) config) external\",\n // Guardian-governed change flow (required for any weakening)\n \"function proposeWeightChange((uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold) proposed) external\",\n \"function approveWeightChange() external\",\n \"function cancelWeightChange() external\",\n \"function executeWeightChange() external\",\n // State readers\n \"function weightConfig() external view returns (uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold)\",\n \"function pendingWeightChange() external view returns ((uint8 passkeyWeight, uint8 ecdsaWeight, uint8 blsWeight, uint8 guardian0Weight, uint8 guardian1Weight, uint8 guardian2Weight, uint8 _padding, uint8 tier1Threshold, uint8 tier2Threshold, uint8 tier3Threshold) proposed, uint256 proposedAt, uint256 approvalBitmap)\",\n // Errors (for decoding reverts)\n \"error InsecureWeightConfig()\",\n \"error WeakeningRequiresProposal()\",\n \"error WeightChangePending()\",\n \"error NoWeightChangeProposal()\",\n \"error WeightChangeAlreadyApproved()\",\n \"error WeightChangeNotApproved()\",\n \"error WeightChangeTimelockNotExpired()\",\n];\n\n// Parsed (loosely-typed `Abi`) form for viem encodeFunctionData/readContract.\nconst WEIGHTED_SIGNATURE_ABI_PARSED = parseAbi(WEIGHTED_SIGNATURE_ABI as readonly string[]);\n\n/** Timelock that must elapse after a proposal before executeWeightChange() succeeds (WEIGHT_CHANGE_TIMELOCK = 2 days). */\nexport const WEIGHT_CHANGE_TIMELOCK_SECONDS = 2 * 24 * 60 * 60;\n/** Guardian approvals required to execute a pending weight change (WEIGHT_CHANGE_THRESHOLD = 2-of-3). */\nexport const WEIGHT_CHANGE_THRESHOLD = 2;\n/** A proposal expires this long after it is proposed; approvals/execution after expiry revert (WEIGHT_CHANGE_EXPIRY = 30 days). */\nexport const WEIGHT_CHANGE_EXPIRY_SECONDS = 30 * 24 * 60 * 60;\n\n/**\n * WeightConfig — the weighted multi-signature policy for an AAStarAirAccount (algId 0x07).\n *\n * Each signer type / guardian contributes its weight; a transaction is authorized when the\n * summed weight of present signatures meets the relevant tier threshold. tier1 is the base\n * (required, non-zero) threshold; tier2/tier3 gate higher-value operations and, when set,\n * must be monotonically non-decreasing (tier1 <= tier2 <= tier3).\n *\n * Field order MUST match the on-chain struct exactly (see AAStarAirAccountV7.json):\n * passkeyWeight, ecdsaWeight, blsWeight, guardian0Weight, guardian1Weight, guardian2Weight,\n * _padding, tier1Threshold, tier2Threshold, tier3Threshold.\n */\nexport interface WeightConfig {\n /** Weight granted by a valid passkey (P256/WebAuthn) signature. */\n passkeyWeight: number;\n /** Weight granted by a valid ECDSA (secp256k1 owner) signature. */\n ecdsaWeight: number;\n /** Weight granted by a valid BLS signature. */\n blsWeight: number;\n /** Weight granted by guardian slot 0. */\n guardian0Weight: number;\n /** Weight granted by guardian slot 1. */\n guardian1Weight: number;\n /** Weight granted by guardian slot 2. */\n guardian2Weight: number;\n /** Reserved padding byte (storage packing); keep 0. */\n _padding: number;\n /** Base threshold; must be non-zero and strictly greater than every individual weight. */\n tier1Threshold: number;\n /** Tier-2 threshold (0 = disabled); when set must be >= tier1Threshold. */\n tier2Threshold: number;\n /** Tier-3 threshold (0 = disabled); when set requires tier2 set and must be >= tier2Threshold. */\n tier3Threshold: number;\n}\n\n/** A pending weight-change proposal awaiting guardian approval + timelock. */\nexport interface PendingWeightChange {\n /** The proposed new WeightConfig. */\n proposed: WeightConfig;\n /** Unix timestamp when the proposal was created; 0 means no active proposal. */\n proposedAt: bigint;\n /** Bitmap of guardian indices that have approved (bit i set => guardian i approved). */\n approvalBitmap: bigint;\n}\n\n// Canonical field order of the WeightConfig tuple as encoded on-chain.\nconst WEIGHT_CONFIG_FIELDS = [\n \"passkeyWeight\",\n \"ecdsaWeight\",\n \"blsWeight\",\n \"guardian0Weight\",\n \"guardian1Weight\",\n \"guardian2Weight\",\n \"_padding\",\n \"tier1Threshold\",\n \"tier2Threshold\",\n \"tier3Threshold\",\n] as const;\n\nfunction toConfigTuple(config: WeightConfig): number[] {\n return WEIGHT_CONFIG_FIELDS.map((f) => config[f]);\n}\n\nfunction fromConfigResult(result: unknown): WeightConfig {\n const r = result as Record<string, unknown> & unknown[];\n // viem decodes a named-component tuple into an object (named access) while a\n // list of separate outputs decodes into an array (positional access); support both.\n const pick = (name: string, idx: number): number =>\n Number((r[name] ?? r[idx]) as number | bigint);\n return {\n passkeyWeight: pick(\"passkeyWeight\", 0),\n ecdsaWeight: pick(\"ecdsaWeight\", 1),\n blsWeight: pick(\"blsWeight\", 2),\n guardian0Weight: pick(\"guardian0Weight\", 3),\n guardian1Weight: pick(\"guardian1Weight\", 4),\n guardian2Weight: pick(\"guardian2Weight\", 5),\n _padding: pick(\"_padding\", 6),\n tier1Threshold: pick(\"tier1Threshold\", 7),\n tier2Threshold: pick(\"tier2Threshold\", 8),\n tier3Threshold: pick(\"tier3Threshold\", 9),\n };\n}\n\n/**\n * WeightedSignatureService — typed wrappers for AAStarAirAccount weighted-signature\n * governance (algId 0x07).\n *\n * Governance model:\n * - setWeightConfig(config): OWNER only. Used for the first-time config and for\n * *strengthening* changes (no individual weight or tier threshold decreased).\n * Reverts WeakeningRequiresProposal-equivalent path is enforced by the contract:\n * a weakening passed here reverts; route weakenings through proposeWeightChange.\n * Also reverts if a proposal is already pending (WeightChangePending).\n * - proposeWeightChange(config): OWNER only. Required when the new config *weakens*\n * security (lowers any weight or threshold). Opens a guardian-approved proposal.\n * - approveWeightChange(): GUARDIAN only (any of the 3 guardian slots). Each guardian\n * may approve once; approvals are tracked in approvalBitmap.\n * - executeWeightChange(): ANYONE, but only succeeds once BOTH conditions hold:\n * (1) approvals >= WEIGHT_CHANGE_THRESHOLD (2-of-3 guardians), and\n * (2) WEIGHT_CHANGE_TIMELOCK (2 days) has elapsed since proposedAt.\n * A proposal also expires after WEIGHT_CHANGE_EXPIRY (30 days).\n * - cancelWeightChange(): OWNER or any GUARDIAN may cancel a pending proposal.\n *\n * Unlike ForceExitService (an ERC-7579 module), these calls target the ACCOUNT itself.\n * Construct with the account address; encode* methods return calldata for a UserOp or\n * direct tx, and reads use the contract directly.\n */\nexport class WeightedSignatureService {\n private readonly address: `0x${string}`;\n\n constructor(\n private readonly accountAddress: string,\n private readonly client: PublicClient\n ) {\n this.address = accountAddress as `0x${string}`;\n }\n\n // ── On-chain reads ──────────────────────────────────────────────\n\n /** Read the account's current active WeightConfig. */\n async getWeightConfig(): Promise<WeightConfig> {\n const result = await this.client.readContract({\n address: this.address,\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"weightConfig\",\n });\n return fromConfigResult(result);\n }\n\n /**\n * Read the pending weight-change proposal. When `proposedAt === 0n` there is no\n * active proposal (the returned `proposed` config will be all zeros).\n */\n async getPendingWeightChange(): Promise<PendingWeightChange> {\n const [proposed, proposedAt, approvalBitmap] = (await this.client.readContract({\n address: this.address,\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"pendingWeightChange\",\n })) as [unknown, bigint, bigint];\n return {\n proposed: fromConfigResult(proposed),\n proposedAt: BigInt(proposedAt),\n approvalBitmap: BigInt(approvalBitmap),\n };\n }\n\n // ── Calldata encoders (for UserOp or direct tx submission) ─────\n\n /**\n * Encode setWeightConfig calldata. OWNER only; for first-time setup or strengthening.\n * Weakening an existing config must go through encodeProposeWeightChange instead.\n */\n encodeSetWeightConfig(config: WeightConfig): Hex {\n return encodeFunctionData({\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"setWeightConfig\",\n args: [toConfigTuple(config)],\n });\n }\n\n /**\n * Encode proposeWeightChange calldata. OWNER only; opens a guardian-governed proposal\n * (required for any weakening). Subject to 2-of-3 approval + 2-day timelock before execute.\n */\n encodeProposeWeightChange(config: WeightConfig): Hex {\n return encodeFunctionData({\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"proposeWeightChange\",\n args: [toConfigTuple(config)],\n });\n }\n\n /** Encode approveWeightChange calldata. GUARDIAN only; each guardian may approve once. */\n encodeApproveWeightChange(): Hex {\n return encodeFunctionData({\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"approveWeightChange\",\n });\n }\n\n /** Encode cancelWeightChange calldata. OWNER or any GUARDIAN may cancel a pending proposal. */\n encodeCancelWeightChange(): Hex {\n return encodeFunctionData({\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"cancelWeightChange\",\n });\n }\n\n /**\n * Encode executeWeightChange calldata. Callable by anyone, but only succeeds once the\n * threshold (2-of-3) and timelock (2 days) are both satisfied and the proposal has not expired.\n */\n encodeExecuteWeightChange(): Hex {\n return encodeFunctionData({\n abi: WEIGHTED_SIGNATURE_ABI_PARSED,\n functionName: \"executeWeightChange\",\n });\n }\n}\n","import { encodeFunctionData, type Abi, type Address, type Hex, type PublicClient } from \"viem\";\n// The AgentRegistry / EntryPoint / AirAccount ABIs are local human-readable `string[]`\n// signatures (not available in @aastar/core), so parseAbi is required to feed them to\n// viem's encodeFunctionData / readContract during the ethers->viem migration.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\nimport { AIRACCOUNT_FACTORY_ABI, AIRACCOUNT_ABI } from \"../constants/entrypoint\";\n\n// Minimal ABI covering the AAStar AgentRegistry contract (SuperPaymaster-facing).\n// Mirrors packages/core/src/abis/AgentRegistry.json. The registry maps agent wallets\n// to their human owner and exposes paginated enumeration of an owner's agents.\nconst AGENT_REGISTRY_ABI = [\n // ── Writes ──\n \"function registerAgent(address agentWallet, bytes agentWalletSig) external\",\n \"function revokeAgent(address agentWallet) external\",\n \"function deregisterAgent(address agentWallet) external\",\n // ── Reads ──\n \"function isRegisteredAgent(address agentWallet) external view returns (bool)\",\n \"function isValidAccount(address account) external view returns (bool)\",\n \"function getHumanOwner(address agentWallet) external view returns (address)\",\n \"function getAgentCount(address owner) external view returns (uint256)\",\n \"function getAgentByIndex(address owner, uint256 index) external view returns (address)\",\n \"function getAgents(address humanOwner) external view returns (address[])\",\n \"function getAgentsPage(address owner, uint256 start, uint256 count) external view returns (address[] page)\",\n \"function agentWalletOwner(address agentWallet) external view returns (address)\",\n \"function ownerAgents(address owner, uint256 index) external view returns (address)\",\n \"function balanceOf(address humanOwner) external view returns (uint256)\",\n // ── Errors (for decoding reverts) ──\n \"error AgentAlreadyRegistered()\",\n \"error CallerNotAirAccount()\",\n \"error InvalidAddress()\",\n \"error InvalidAgentSignature()\",\n \"error NotAgentOwner()\",\n \"error SelfRegistrationForbidden()\",\n];\n\n// Parsed viem ABIs (loosely typed as `Abi`) used for both calldata encoding and reads.\n// Widening to `Abi` mirrors the hub's ViemContract approach: function names are indexed\n// dynamically and read return values are cast at the call site.\nconst REGISTRY_ABI: Abi = parseAbi(AGENT_REGISTRY_ABI as readonly string[]);\nconst FACTORY_ABI: Abi = parseAbi(AIRACCOUNT_FACTORY_ABI as readonly string[]);\nconst ACCOUNT_ABI: Abi = parseAbi(AIRACCOUNT_ABI as readonly string[]);\n\n// ─── Parameter / result types ───────────────────────────────────────────────\n\nexport interface CreateAgentAccountParams {\n /** The agent's own signing key (EOA controlled by the agent runtime / KMS). */\n agentKey: string;\n /** ERC-8004-style agent identifier (bytes32) binding this account to an off-chain identity. */\n agentId: string;\n /** The human guardian (guardian2) co-owning the agent account for recovery. */\n guardian2: string;\n /** Guardian2's acceptance signature over the creation hash (EIP-191). */\n guardian2Sig: string;\n /** The agent key's acceptance signature over the creation hash (EIP-191). */\n agentKeySig: string;\n /** Unix timestamp (uint48) after which the signatures are rejected. */\n deadline: bigint | number;\n /** Daily transfer limit in wei (on-chain guard enforcement; V7 requires > 0). */\n dailyLimit: bigint;\n}\n\n// ─── Service ────────────────────────────────────────────────────────────────\n\n/**\n * AgentRegistryService — typed wrappers for the AAStar AgentRegistry contract plus the\n * AAStarAirAccountFactoryV7 agent-account creation helpers.\n *\n * **Two contracts, two responsibilities:**\n *\n * 1. AgentRegistry (constructor `registryAddress`) — the canonical map of agent wallet →\n * human owner used by SuperPaymaster to authorise gasless sponsorship. The factory calls\n * `markValid`/registers the agent at deployment; humans manage the binding afterwards via\n * `registerAgent` / `revokeAgent` / `deregisterAgent`.\n *\n * 2. AAStarAirAccountFactoryV7 — deploys an agent-owned AirAccount. `encodeCreateAgentAccount`\n * targets the factory (NOT the registry); `getAgentAccountAddress` predicts the CREATE2\n * address before deployment.\n *\n * All `encode*` methods return ABI-encoded calldata ready for a UserOp (gasless) or a direct\n * owner transaction. Read methods require a viem `PublicClient`.\n */\nexport class AgentRegistryService {\n private readonly client: PublicClient;\n\n /**\n * @param client viem PublicClient for on-chain reads (e.g. `ethereum.getProvider()`).\n * @param registryAddress deployed AgentRegistry contract address.\n */\n constructor(\n client: PublicClient,\n private readonly registryAddress: string\n ) {\n this.client = client;\n }\n\n // ── Composed register/revoke-via-account scenario encoders ──────────────────\n // registerAgent/revokeAgent require msg.sender == the agent account, so they are delivered\n // through the account's execute(registry, 0, calldata). These return the FULL execute\n // calldata to submit TO the agent account (owner-signed) — the scenario-level entry point.\n\n /** Encode `account.execute(registry, 0, registerAgent(agentWallet, agentWalletSig))`. */\n encodeRegisterAgentViaAccount(agentWallet: string, agentWalletSig: string): string {\n return encodeFunctionData({\n abi: ACCOUNT_ABI,\n functionName: \"execute\",\n args: [\n this.registryAddress as Address,\n 0n,\n this.encodeRegisterAgent(agentWallet, agentWalletSig) as Hex,\n ],\n });\n }\n\n /** Encode `account.execute(registry, 0, revokeAgent(agentWallet))`. */\n encodeRevokeAgentViaAccount(agentWallet: string): string {\n return encodeFunctionData({\n abi: ACCOUNT_ABI,\n functionName: \"execute\",\n args: [this.registryAddress as Address, 0n, this.encodeRevokeAgent(agentWallet) as Hex],\n });\n }\n\n // ── AgentRegistry calldata encoders ─────────────────────────────────────────\n\n /**\n * Encode calldata for `registerAgent(agentWallet, agentWalletSig)`.\n *\n * Binds `agentWallet` to the caller (the human owner). `agentWalletSig` must be the agent\n * wallet's EIP-191 signature proving control of the key. Reverts with\n * `SelfRegistrationForbidden` if the caller registers itself, or `AgentAlreadyRegistered`\n * if the wallet is already bound.\n */\n encodeRegisterAgent(agentWallet: string, agentWalletSig: string): string {\n return encodeFunctionData({\n abi: REGISTRY_ABI,\n functionName: \"registerAgent\",\n args: [agentWallet as Address, agentWalletSig as Hex],\n });\n }\n\n /**\n * Encode calldata for `revokeAgent(agentWallet)`.\n *\n * Owner-initiated revocation of a previously registered agent wallet. Caller must be the\n * agent's human owner (else `NotAgentOwner`).\n */\n encodeRevokeAgent(agentWallet: string): string {\n return encodeFunctionData({\n abi: REGISTRY_ABI,\n functionName: \"revokeAgent\",\n args: [agentWallet as Address],\n });\n }\n\n /**\n * Encode calldata for `deregisterAgent(agentWallet)`.\n *\n * Removes the agent wallet from the registry (full deregistration, distinct from the\n * lighter-weight `revokeAgent`). Caller must be the agent's human owner.\n */\n encodeDeregisterAgent(agentWallet: string): string {\n return encodeFunctionData({\n abi: REGISTRY_ABI,\n functionName: \"deregisterAgent\",\n args: [agentWallet as Address],\n });\n }\n\n // ── AgentRegistry on-chain reads ────────────────────────────────────────────\n\n /** Whether `agentWallet` is currently registered in the registry. */\n async isRegisteredAgent(agentWallet: string): Promise<boolean> {\n return (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"isRegisteredAgent\",\n args: [agentWallet as Address],\n })) as boolean;\n }\n\n /** Whether `account` has been marked valid (e.g. an AirAccount minted by the bound factory). */\n async isValidAccount(account: string): Promise<boolean> {\n return (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"isValidAccount\",\n args: [account as Address],\n })) as boolean;\n }\n\n /** The human owner bound to `agentWallet` (ZeroAddress if unregistered). */\n async getHumanOwner(agentWallet: string): Promise<string> {\n return (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"getHumanOwner\",\n args: [agentWallet as Address],\n })) as string;\n }\n\n /** Number of agents registered under `owner`. */\n async getAgentCount(owner: string): Promise<bigint> {\n return BigInt(\n (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"getAgentCount\",\n args: [owner as Address],\n })) as bigint\n );\n }\n\n /** The agent wallet at `index` in `owner`'s agent list. */\n async getAgentByIndex(owner: string, index: bigint | number): Promise<string> {\n return (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"getAgentByIndex\",\n args: [owner as Address, BigInt(index)],\n })) as string;\n }\n\n /** Full list of agent wallets registered under `humanOwner`. */\n async getAgents(humanOwner: string): Promise<string[]> {\n const result = (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"getAgents\",\n args: [humanOwner as Address],\n })) as readonly string[];\n // Normalise the (readonly) viem result into a plain mutable array.\n return Array.from(result);\n }\n\n /**\n * Paginated slice of `owner`'s agent wallets: `count` entries starting at `start`.\n * The contract clamps `count` to the remaining length, so the returned array may be shorter.\n */\n async getAgentsPage(\n owner: string,\n start: bigint | number,\n count: bigint | number\n ): Promise<string[]> {\n const result = (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"getAgentsPage\",\n args: [owner as Address, BigInt(start), BigInt(count)],\n })) as readonly string[];\n return Array.from(result);\n }\n\n /** Raw `agentWalletOwner` mapping read (agentWallet → owner). */\n async agentWalletOwner(agentWallet: string): Promise<string> {\n return (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"agentWalletOwner\",\n args: [agentWallet as Address],\n })) as string;\n }\n\n /** Raw `ownerAgents` array read (owner, index → agentWallet). */\n async ownerAgents(owner: string, index: bigint | number): Promise<string> {\n return (await this.client.readContract({\n address: this.registryAddress as Address,\n abi: REGISTRY_ABI,\n functionName: \"ownerAgents\",\n args: [owner as Address, BigInt(index)],\n })) as string;\n }\n\n // ── Factory agent-account helpers (AAStarAirAccountFactoryV7) ───────────────\n\n /**\n * Encode calldata for the factory's `createAgentAccount(...)`.\n *\n * Targets the AAStarAirAccountFactoryV7, NOT the AgentRegistry. The factory deploys the agent\n * AirAccount and registers it in the bound AgentRegistry in one transaction. Submit this\n * calldata to the factory address (direct tx or via a relayer).\n */\n encodeCreateAgentAccount(params: CreateAgentAccountParams): string {\n return encodeFunctionData({\n abi: FACTORY_ABI,\n functionName: \"createAgentAccount\",\n args: [\n params.agentKey as Address,\n params.agentId as Hex,\n params.guardian2 as Address,\n params.guardian2Sig as Hex,\n params.agentKeySig as Hex,\n BigInt(params.deadline),\n params.dailyLimit,\n ],\n });\n }\n\n /**\n * Encode calldata for the factory's `setAgentRegistry(_agentRegistry)` (factory-admin only).\n */\n encodeSetAgentRegistry(agentRegistry: string): string {\n return encodeFunctionData({\n abi: FACTORY_ABI,\n functionName: \"setAgentRegistry\",\n args: [agentRegistry as Address],\n });\n }\n\n /**\n * Predict the CREATE2 address of an agent account via the factory's `getAgentAddress(...)`.\n *\n * @param factoryAddress AAStarAirAccountFactoryV7 address.\n * @param humanOwner the human guardian/owner co-owning the agent account.\n * @param agentKey the agent's signing key.\n * @param agentId the bytes32 agent identifier.\n */\n async getAgentAccountAddress(\n factoryAddress: string,\n humanOwner: string,\n agentKey: string,\n agentId: string\n ): Promise<string> {\n return (await this.client.readContract({\n address: factoryAddress as Address,\n abi: FACTORY_ABI,\n functionName: \"getAgentAddress\",\n args: [humanOwner as Address, agentKey as Address, agentId as Hex],\n })) as string;\n }\n\n /** Read the AgentRegistry address currently bound to the factory. */\n async getFactoryAgentRegistry(factoryAddress: string): Promise<string> {\n return (await this.client.readContract({\n address: factoryAddress as Address,\n abi: FACTORY_ABI,\n functionName: \"agentRegistry\",\n args: [],\n })) as string;\n }\n}\n","import { encodeFunctionData, getContract, type Abi, type PublicClient } from \"viem\";\n// parseAbi is required: the ERC-8004 ABI is a local human-readable string[] of function\n// signatures (not available in @aastar/core), and viem needs a parsed Abi to encode/read.\n// eslint-disable-next-line no-restricted-imports\nimport { parseAbi } from \"viem\";\n\n// Minimal ABI covering only the ERC-8004 agent functions on AAStarAirAccountV7.\n// These are routed via fallback→delegatecall to AirAccountExtension on the deployed account.\nconst ERC8004_ABI = [\n \"function setAgentWallet(uint256 agentId, address agentWallet, address agentRegistry, bytes agentWalletSig) external\",\n \"function mintAgentIdentity(address identityRegistry, string agentURI) external returns (uint256 agentId)\",\n \"function bindERC8004AgentWallet(address identityRegistry, uint256 agentId, address agentWallet, uint256 deadline, bytes signature) external\",\n \"function submitAgentReputation(address reputationRegistry, uint256 agentId, int128 value, uint8 valueDecimals, string tag1, string tag2, string endpoint, string feedbackURI, bytes32 feedbackHash) external\",\n \"function queryAgentReputation(address reputationRegistry, uint256 agentId, address[] clientAddresses, string tag1, string tag2) external view returns (uint64 count, int128 summaryValue, uint8 summaryDecimals)\",\n \"function agentExtension() external view returns (address)\",\n];\n\n// ─── Official ERC-8004 \"Trustless Agents\" registry addresses ─────────────────\n// Deployed at deterministic CREATE2 addresses (SAFE Singleton Factory).\n// Source: ../airaccount-contract/src/config/ERC8004Addresses.sol\n\nexport const ERC8004_ADDRESSES = {\n mainnet: {\n identityRegistry: \"0x8004A169FB4a3325136EB29fA0ceB6D2e539a432\",\n reputationRegistry: \"0x8004BAa17C55a88189AE136b182e5fdA19dE9b63\",\n validationRegistry: \"0x8004Cc8439f36fd5F9F049D9fF86523Df6dAAB58\",\n },\n testnet: {\n identityRegistry: \"0x8004A818BFB912233c491871b3d84c89A494BD9e\",\n reputationRegistry: \"0x8004B663056A597Dffe9eCcC1965A193B7388713\",\n validationRegistry: \"0x8004Cb1BF31DAf7788923b405b754f57acEB4272\",\n },\n} as const;\n\n// Mainnet chain IDs that have official ERC-8004 deployments.\nconst MAINNET_CHAIN_IDS = new Set([1, 10, 137, 8453, 42161, 43114, 56, 534352, 100, 42220, 59144, 5000, 167000, 360]);\nconst TESTNET_CHAIN_IDS = new Set([11155111, 11155420, 84532, 421614, 80002]);\n\nexport function erc8004AddressesForChain(chainId: number): (typeof ERC8004_ADDRESSES)[\"mainnet\"] | (typeof ERC8004_ADDRESSES)[\"testnet\"] {\n if (MAINNET_CHAIN_IDS.has(chainId)) return ERC8004_ADDRESSES.mainnet;\n if (TESTNET_CHAIN_IDS.has(chainId)) return ERC8004_ADDRESSES.testnet;\n throw new Error(`ERC-8004: unsupported chain ${chainId}`);\n}\n\n// ─── Parameter types ──────────────────────────────────────────────────────────\n\nexport interface SetAgentWalletParams {\n agentId: bigint;\n agentWallet: string;\n /** AAStar AgentRegistry contract address (SuperPaymaster-facing, NOT the official ERC-8004 registry) */\n agentRegistry: string;\n /** Signature from the agent wallet proving ownership */\n agentWalletSig: string;\n}\n\nexport interface MintAgentIdentityParams {\n /** Must be the official ERC-8004 identity registry for this chain */\n identityRegistry: string;\n /** Agent metadata URI (ERC-721 tokenURI) */\n agentURI: string;\n}\n\nexport interface BindERC8004AgentWalletParams {\n /** Must be the official ERC-8004 identity registry for this chain */\n identityRegistry: string;\n agentId: bigint;\n agentWallet: string;\n /** Unix timestamp — signature becomes invalid after this deadline */\n deadline: bigint;\n /** Signature authorising the wallet binding, signed by the identity registry's expected signer */\n signature: string;\n}\n\nexport interface SubmitAgentReputationParams {\n /** Must be the official ERC-8004 reputation registry for this chain */\n reputationRegistry: string;\n agentId: bigint;\n value: bigint;\n valueDecimals: number;\n tag1: string;\n tag2: string;\n endpoint: string;\n feedbackURI: string;\n feedbackHash: string; // bytes32 hex\n}\n\nexport interface QueryAgentReputationParams {\n /** Must be the official ERC-8004 reputation registry for this chain */\n reputationRegistry: string;\n agentId: bigint;\n clientAddresses: string[];\n tag1: string;\n tag2: string;\n}\n\nexport interface AgentReputationSummary {\n count: bigint;\n summaryValue: bigint;\n summaryDecimals: number;\n}\n\n// ─── Service ──────────────────────────────────────────────────────────────────\n\n/**\n * ERC8004Service — TypeScript wrappers for AirAccount's ERC-8004 \"Trustless Agents\" functions.\n *\n * **Two distinct registration paths:**\n *\n * 1. `encodeSetAgentWallet` — AAStar/SuperPaymaster path.\n * Registers the agent wallet in the AAStar AgentRegistry contract. Use this when you want\n * SuperPaymaster to recognise the agent for gasless sponsorship. The `agentRegistry` argument\n * is the deployed AgentRegistry address, NOT the official ERC-8004 IdentityRegistry.\n *\n * 2. `encodeMintAgentIdentity` + `encodeBindERC8004AgentWallet` — official ERC-8004 path.\n * Mints an ERC-721 identity NFT in the official ERC-8004 IdentityRegistry and binds an\n * execution wallet to it. The registry address MUST be from `erc8004AddressesForChain()`.\n * These calls revert on-chain if the wrong registry address is supplied.\n *\n * All `encode*` methods return ABI-encoded calldata ready to be submitted via UserOp (gasless)\n * or a direct owner transaction. The calldata targets the AirAccount address — the account's\n * fallback delegates to AirAccountExtension for these selectors.\n */\nexport class ERC8004Service {\n private readonly abi: Abi;\n private readonly provider?: PublicClient;\n\n constructor(provider?: PublicClient) {\n this.abi = parseAbi(ERC8004_ABI);\n this.provider = provider;\n }\n\n /**\n * Build a read-only viem contract bound to the account address. The ABI is loaded from\n * human-readable signatures via `parseAbi` (loose `Abi`), so `read` methods are indexed by\n * name and return `unknown` — cast at the call site. Mirrors the dynamic surface that\n * `ethers.Contract` previously exposed. Caller must ensure `this.provider` is set.\n */\n private contractAt(accountAddress: string): {\n read: Record<string, (args: readonly unknown[]) => Promise<unknown>>;\n } {\n return getContract({\n address: accountAddress as `0x${string}`,\n abi: this.abi,\n client: this.provider as PublicClient,\n }) as unknown as { read: Record<string, (args: readonly unknown[]) => Promise<unknown>> };\n }\n\n // ── AAStar AgentRegistry path ─────────────────────────────────────────────\n\n /**\n * Encode calldata for `setAgentWallet`.\n *\n * Registers `agentWallet` in the AAStar AgentRegistry (SuperPaymaster-facing). This is the\n * correct path when the goal is SuperPaymaster gasless sponsorship for the agent.\n *\n * **Not** a call to the official ERC-8004 IdentityRegistry. Use `encodeMintAgentIdentity`\n * + `encodeBindERC8004AgentWallet` for the ERC-8004 standard path.\n *\n * Callable: owner EOA direct tx OR via UserOp (gasless).\n */\n encodeSetAgentWallet(params: SetAgentWalletParams): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"setAgentWallet\",\n args: [params.agentId, params.agentWallet, params.agentRegistry, params.agentWalletSig],\n });\n }\n\n // ── Official ERC-8004 identity path ──────────────────────────────────────\n\n /**\n * Encode calldata for `mintAgentIdentity`.\n *\n * Mints an ERC-721 agent identity NFT in the official ERC-8004 IdentityRegistry and returns\n * the new `agentId` (decoded from the tx receipt). The `identityRegistry` must be\n * `erc8004AddressesForChain(chainId).identityRegistry` — the contract reverts otherwise.\n *\n * Callable: owner EOA direct tx OR via UserOp (gasless).\n */\n encodeMintAgentIdentity(params: MintAgentIdentityParams): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"mintAgentIdentity\",\n args: [params.identityRegistry, params.agentURI],\n });\n }\n\n /**\n * Encode calldata for `bindERC8004AgentWallet`.\n *\n * Binds an execution wallet to an existing ERC-8004 agent identity NFT. Requires a\n * deadline-bounded signature from the expected signer (see the IdentityRegistry contract).\n * The `identityRegistry` must be the official chain-specific address.\n *\n * Callable: owner EOA direct tx OR via UserOp (gasless).\n */\n encodeBindERC8004AgentWallet(params: BindERC8004AgentWalletParams): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"bindERC8004AgentWallet\",\n args: [\n params.identityRegistry,\n params.agentId,\n params.agentWallet,\n params.deadline,\n params.signature,\n ],\n });\n }\n\n // ── Reputation ────────────────────────────────────────────────────────────\n\n /**\n * Encode calldata for `submitAgentReputation`.\n *\n * Submits a reputation feedback entry to the official ERC-8004 ReputationRegistry.\n * `reputationRegistry` must be `erc8004AddressesForChain(chainId).reputationRegistry`.\n *\n * Callable: owner EOA direct tx OR via UserOp (gasless).\n */\n encodeSubmitAgentReputation(params: SubmitAgentReputationParams): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"submitAgentReputation\",\n args: [\n params.reputationRegistry,\n params.agentId,\n params.value,\n params.valueDecimals,\n params.tag1,\n params.tag2,\n params.endpoint,\n params.feedbackURI,\n params.feedbackHash,\n ],\n });\n }\n\n /**\n * Query aggregated reputation for an agent from the official ERC-8004 ReputationRegistry.\n * Returns `null` when no provider was supplied at construction.\n */\n async queryAgentReputation(\n accountAddress: string,\n params: QueryAgentReputationParams,\n ): Promise<AgentReputationSummary> {\n if (!this.provider) throw new Error(\"ERC8004Service: provider required for on-chain reads\");\n const contract = this.contractAt(accountAddress);\n const [count, summaryValue, summaryDecimals] = (await contract.read.queryAgentReputation([\n params.reputationRegistry,\n params.agentId,\n params.clientAddresses,\n params.tag1,\n params.tag2,\n ])) as readonly [bigint, bigint, number];\n return { count: BigInt(count), summaryValue: BigInt(summaryValue), summaryDecimals: Number(summaryDecimals) };\n }\n\n /**\n * Encode calldata for `queryAgentReputation` (for static-call or eth_call without a signer).\n */\n encodeQueryAgentReputation(params: QueryAgentReputationParams): string {\n return encodeFunctionData({\n abi: this.abi,\n functionName: \"queryAgentReputation\",\n args: [\n params.reputationRegistry,\n params.agentId,\n params.clientAddresses,\n params.tag1,\n params.tag2,\n ],\n });\n }\n\n /**\n * Read the agentExtension implementation address from a deployed AirAccount.\n */\n async getAgentExtensionAddress(accountAddress: string): Promise<string> {\n if (!this.provider) throw new Error(\"ERC8004Service: provider required for on-chain reads\");\n const contract = this.contractAt(accountAddress);\n const extension = await contract.read.agentExtension([]);\n return extension as string;\n }\n}\n","import axios, { AxiosInstance, AxiosRequestConfig } from \"axios\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\n\n/**\n * Canonical production KMS endpoint (IMX93 TEE behind Cloudflare Tunnel).\n * v0.20.0 (Beta2) — see AirAccount/kms/CHANGELOG.md.\n */\nexport const DEFAULT_KMS_ENDPOINT = \"https://kms.aastar.io\";\n\nexport interface KmsHttpClientOptions {\n kmsEndpoint?: string;\n kmsEnabled?: boolean;\n kmsApiKey?: string;\n logger?: ILogger;\n}\n\n/**\n * Shared low-level HTTP transport for all KMS service classes.\n *\n * Centralises axios setup (baseURL, x-api-key), the `enabled` gate, and the three\n * request flavours the KMS uses:\n * - plain JSON → `post` / `get`\n * - AWS-KMS framed → `amzPost` (adds x-amz-target + x-amz-json-1.1 content type)\n * - agent/session JWT → `postWithBearer` (Authorization: Bearer <jwt>)\n *\n * KmsManager and the composed services (agent / session / payment / monitor) all share\n * one instance so they reuse the same connection config and auth headers.\n */\nexport class KmsHttpClient {\n readonly endpoint: string;\n readonly enabled: boolean;\n readonly logger: ILogger;\n private readonly apiKey?: string;\n private readonly http: AxiosInstance;\n\n constructor(options: KmsHttpClientOptions) {\n this.endpoint = options.kmsEndpoint ?? DEFAULT_KMS_ENDPOINT;\n this.enabled = options.kmsEnabled === true;\n this.apiKey = options.kmsApiKey;\n this.logger = options.logger ?? new ConsoleLogger(\"[KmsHttpClient]\");\n\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (this.apiKey) {\n headers[\"x-api-key\"] = this.apiKey;\n }\n\n this.http = axios.create({ baseURL: this.endpoint, headers });\n }\n\n /** Throw if KMS is not enabled — every operation must call this first. */\n ensureEnabled(): void {\n if (!this.enabled) {\n throw new Error(\"KMS service is not enabled\");\n }\n }\n\n /**\n * Plain JSON POST. The axios `config` arg is only forwarded when defined, so a\n * config-less call results in `http.post(path, body)` (2 args) — preserving the\n * exact call shape the existing unit tests assert against.\n */\n async post<T>(path: string, body?: unknown, config?: AxiosRequestConfig): Promise<T> {\n const response = config === undefined\n ? await this.http.post(path, body)\n : await this.http.post(path, body, config);\n return response.data as T;\n }\n\n /** Plain JSON GET. */\n async get<T>(path: string, config?: AxiosRequestConfig): Promise<T> {\n const response = config === undefined\n ? await this.http.get(path)\n : await this.http.get(path, config);\n return response.data as T;\n }\n\n /** POST with AWS-KMS framing (x-amz-target header) — required for wallet/signing ops. */\n async amzPost<T>(path: string, target: string, body: unknown): Promise<T> {\n return this.post<T>(path, body, {\n headers: {\n \"Content-Type\": \"application/x-amz-json-1.1\",\n \"x-amz-target\": target,\n },\n });\n }\n\n /** POST authenticated with a TEE-issued agent/session JWT (Authorization: Bearer). */\n async postWithBearer<T>(path: string, body: unknown, jwt: string): Promise<T> {\n return this.post<T>(path, body, {\n headers: { authorization: `Bearer ${jwt}` },\n });\n }\n}\n","/**\n * Internal module for NIST P256, P384, P521 curves.\n * Do not use for now.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';\nimport { createHasher, type H2CHasher } from './abstract/hash-to-curve.ts';\nimport { Field } from './abstract/modular.ts';\nimport { createORPF, type OPRF } from './abstract/oprf.ts';\nimport {\n ecdsa,\n mapToCurveSimpleSWU,\n weierstrass,\n type ECDSA,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\n\n// p = 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n - 1n\n// a = Fp256.create(BigInt('-3'));\nconst p256_CURVE: WeierstrassOpts<bigint> = /* @__PURE__ */ (() => ({\n p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n h: BigInt(1),\n a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),\n b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n}))();\n\n// p = 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n\nconst p384_CURVE: WeierstrassOpts<bigint> = /* @__PURE__ */ (() => ({\n p: BigInt(\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'\n ),\n n: BigInt(\n '0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'\n ),\n h: BigInt(1),\n a: BigInt(\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc'\n ),\n b: BigInt(\n '0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'\n ),\n Gx: BigInt(\n '0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'\n ),\n Gy: BigInt(\n '0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'\n ),\n}))();\n\n// p = 2n**521n - 1n\nconst p521_CURVE: WeierstrassOpts<bigint> = /* @__PURE__ */ (() => ({\n p: BigInt(\n '0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n ),\n n: BigInt(\n '0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'\n ),\n h: BigInt(1),\n a: BigInt(\n '0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'\n ),\n b: BigInt(\n '0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'\n ),\n Gx: BigInt(\n '0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'\n ),\n Gy: BigInt(\n '0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'\n ),\n}))();\n\ntype SwuOpts = {\n A: bigint;\n B: bigint;\n Z: bigint;\n};\n\nfunction createSWU(Point: WeierstrassPointCons<bigint>, opts: SwuOpts) {\n const map = mapToCurveSimpleSWU(Point.Fp, opts);\n return (scalars: bigint[]) => map(scalars[0]);\n}\n\n// NIST P256\nconst p256_Point = /* @__PURE__ */ weierstrass(p256_CURVE);\n/**\n * NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods.\n * Hashes inputs with sha256 by default.\n *\n * @example\n * ```js\n * import { p256 } from '@noble/curves/nist.js';\n * const { secretKey, publicKey } = p256.keygen();\n * // const publicKey = p256.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256.sign(msg, secretKey);\n * const isValid = p256.verify(sig, msg, publicKey);\n * // const sigKeccak = p256.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const p256: ECDSA = /* @__PURE__ */ ecdsa(p256_Point, sha256);\n/** Hashing / encoding to p256 points / field. RFC 9380 methods. */\nexport const p256_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() => {\n return createHasher(\n p256_Point,\n createSWU(p256_Point, {\n A: p256_CURVE.a,\n B: p256_CURVE.b,\n Z: p256_Point.Fp.create(BigInt('-10')),\n }),\n {\n DST: 'P256_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n p: p256_CURVE.p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n );\n})();\n/** p256 OPRF, defined in RFC 9497. */\nexport const p256_oprf: OPRF = /* @__PURE__ */ (() =>\n createORPF({\n name: 'P256-SHA256',\n Point: p256_Point,\n hash: sha256,\n hashToGroup: p256_hasher.hashToCurve,\n hashToScalar: p256_hasher.hashToScalar,\n }))();\n\n// NIST P384\nconst p384_Point = /* @__PURE__ */ weierstrass(p384_CURVE);\n/** NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. Hashes inputs with sha384 by default. */\nexport const p384: ECDSA = /* @__PURE__ */ ecdsa(p384_Point, sha384);\n/** Hashing / encoding to p384 points / field. RFC 9380 methods. */\nexport const p384_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() => {\n return createHasher(\n p384_Point,\n createSWU(p384_Point, {\n A: p384_CURVE.a,\n B: p384_CURVE.b,\n Z: p384_Point.Fp.create(BigInt('-12')),\n }),\n {\n DST: 'P384_XMD:SHA-384_SSWU_RO_',\n encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n p: p384_CURVE.p,\n m: 1,\n k: 192,\n expand: 'xmd',\n hash: sha384,\n }\n );\n})();\n/** p384 OPRF, defined in RFC 9497. */\nexport const p384_oprf: OPRF = /* @__PURE__ */ (() =>\n createORPF({\n name: 'P384-SHA384',\n Point: p384_Point,\n hash: sha384,\n hashToGroup: p384_hasher.hashToCurve,\n hashToScalar: p384_hasher.hashToScalar,\n }))();\n\n// NIST P521\nconst Fn521 = /* @__PURE__ */ (() => Field(p521_CURVE.n, { allowedLengths: [65, 66] }))();\nconst p521_Point = /* @__PURE__ */ weierstrass(p521_CURVE, { Fn: Fn521 });\n/** NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. Hashes inputs with sha512 by default. */\nexport const p521: ECDSA = /* @__PURE__ */ ecdsa(p521_Point, sha512);\n/** Hashing / encoding to p521 points / field. RFC 9380 methods. */\nexport const p521_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() => {\n return createHasher(\n p521_Point,\n createSWU(p521_Point, {\n A: p521_CURVE.a,\n B: p521_CURVE.b,\n Z: p521_Point.Fp.create(BigInt('-4')),\n }),\n {\n DST: 'P521_XMD:SHA-512_SSWU_RO_',\n encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n p: p521_CURVE.p,\n m: 1,\n k: 256,\n expand: 'xmd',\n hash: sha512,\n }\n );\n})();\n/** p521 OPRF, defined in RFC 9497. */\nexport const p521_oprf: OPRF = /* @__PURE__ */ (() =>\n createORPF({\n name: 'P521-SHA512',\n Point: p521_Point,\n hash: sha512,\n hashToGroup: p521_hasher.hashToCurve,\n hashToScalar: p521_hasher.hashToScalar, // produces L=98 just like in RFC\n }))();\n","import { createHash } from \"node:crypto\";\nimport { p256 } from \"@noble/curves/nist.js\";\nimport { KmsHttpClient } from \"./kms-http-client\";\nimport { WebAuthnAssertion } from \"./kms-signer\";\n\n// ─────────────────────────────────────────────────────────────────────────\n// WebAuthn challenge-binding ceremony (AirAccount KMS #49 / Beta3)\n//\n// The KMS now issues a one-time challenge (nonce) from a `begin` endpoint and\n// requires that nonce to be embedded in the WebAuthn `clientDataJSON` of the\n// assertion submitted to the signing endpoints. This binds each signature to a\n// fresh server-issued challenge → replay protection.\n//\n// Transition vs. strict mode (KMS-side `ENFORCE_TA_CHALLENGE`):\n// - transition (current): requests WITH clientDataJSON get strict nonce\n// validation; requests WITHOUT it fall back to legacy ECDSA-only.\n// - strict (pre-mainnet flip): requests WITHOUT clientDataJSON are REJECTED.\n// This module always produces the clientDataJSON-bound assertion, so it is\n// correct under both modes.\n//\n// Wire format mirrors the authoritative reference ceremony:\n// AirAccount/kms/test/run-full-e2e.sh (ceremony / ceremony_grant)\n// AirAccount/kms/test/p256_helper.py (make_ceremony_assertion)\n// ─────────────────────────────────────────────────────────────────────────\n\n/**\n * RP id the TA verifies against. The TA hardcodes\n * `EXPECTED_RP_ID_HASH = SHA-256(\"aastar.io\")` (AirAccount PR#44 / Issue #39);\n * any other rpId makes the TA reject the assertion with \"rpId hash mismatch\".\n */\nexport const DEFAULT_RP_ID = \"aastar.io\";\n\n/** Origin embedded in clientDataJSON — must be the RP origin the TA expects. */\nexport const DEFAULT_ORIGIN = \"https://aastar.io\";\n\n/**\n * Placeholder credential id (base64url of \"test-credential\") matching the\n * reference ceremony fixtures. Production callers SHOULD pass the credential id\n * returned by CompleteRegistration for the registered passkey.\n */\nexport const DEFAULT_CREDENTIAL_ID = \"dGVzdC1jcmVkZW50aWFs\";\n\n// ── base64url (no padding) — the WebAuthn wire encoding ───────────────────\n\nexport function base64UrlEncode(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString(\"base64url\");\n}\n\nexport function base64UrlDecode(value: string): Uint8Array {\n return new Uint8Array(Buffer.from(value, \"base64url\"));\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n if (clean.length % 2 !== 0) {\n throw new Error(\"hexToBytes: odd-length hex string\");\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\n// ── Types ─────────────────────────────────────────────────────────────────\n\n/**\n * WebAuthn AuthenticationResponseJSON (the subset the KMS verifies). This is the\n * value placed in `WebAuthnAssertion.Credential`.\n */\nexport interface WebAuthnAuthenticationCredential {\n id: string;\n rawId: string;\n type: \"public-key\";\n response: {\n clientDataJSON: string; // base64url(JSON embedding the TA challenge)\n authenticatorData: string; // base64url(rpIdHash || flags || signCount)\n signature: string; // base64url(DER ECDSA P-256 / ES256)\n userHandle?: string;\n };\n clientExtensionResults?: Record<string, unknown>;\n}\n\n/**\n * Pluggable passkey signer. The ceremony helper builds clientDataJSON +\n * authenticatorData and computes the WebAuthn message\n * (authenticatorData || SHA-256(clientDataJSON)); this signer turns that message\n * into an ES256 (ECDSA P-256 over SHA-256) DER signature.\n *\n * Browser callers back this with the platform authenticator; server/test callers\n * use {@link P256PasskeySigner}.\n */\nexport interface PasskeyCeremonySigner {\n /** base64url credential id registered with the KMS for this passkey. */\n readonly credentialId: string;\n /**\n * Sign the WebAuthn message (authenticatorData || SHA-256(clientDataJSON)).\n * MUST return a DER-encoded ES256 signature (ECDSA P-256 with SHA-256 applied\n * to the message), matching the WebAuthn wire format.\n */\n sign(message: Uint8Array): Uint8Array | Promise<Uint8Array>;\n}\n\n/**\n * Server/test {@link PasskeyCeremonySigner} backed by a raw P-256 private key\n * (the passkey bound to the KMS key). Mirrors `p256_helper.py`'s\n * `make_ceremony_assertion`: ES256 DER signature over the WebAuthn message.\n */\nexport class P256PasskeySigner implements PasskeyCeremonySigner {\n readonly credentialId: string;\n private readonly privateKey: Uint8Array;\n\n /**\n * @param privateKey raw 32-byte P-256 scalar (Uint8Array or hex, 0x optional).\n * @param credentialId base64url credential id (defaults to the reference fixture).\n */\n constructor(privateKey: Uint8Array | string, credentialId: string = DEFAULT_CREDENTIAL_ID) {\n this.privateKey = typeof privateKey === \"string\" ? hexToBytes(privateKey) : privateKey;\n this.credentialId = credentialId;\n }\n\n /**\n * Uncompressed (0x04…, 65-byte) P-256 public key hex. Register this with the\n * KMS via CreateKey `PasskeyPublicKey` (or ChangePasskey) so the TA can verify\n * assertions produced by this signer.\n */\n get publicKeyHex(): string {\n return \"0x\" + Buffer.from(p256.getPublicKey(this.privateKey, false)).toString(\"hex\");\n }\n\n sign(message: Uint8Array): Uint8Array {\n // prehash:true → noble applies SHA-256 to `message` (= ES256), DER output.\n return p256.sign(message, this.privateKey, { prehash: true, format: \"der\" });\n }\n}\n\n// ── Builders ────────────────────────────────────────────────────────────\n\n/**\n * Build the clientDataJSON bytes embedding the TA-issued one-time challenge.\n *\n * Compact JSON (no whitespace) with field order `type, challenge, origin`,\n * mirroring the reference ceremony. The KMS parses this and asserts the\n * `challenge` field equals the stored nonce before verifying the signature over\n * (authenticatorData || SHA-256(clientDataJSON)).\n */\nexport function buildClientDataJSON(challenge: string, origin: string = DEFAULT_ORIGIN): Uint8Array {\n const json = JSON.stringify({ type: \"webauthn.get\", challenge, origin });\n return new TextEncoder().encode(json);\n}\n\n/**\n * Build authenticatorData = rpIdHash(32) || flags(1) || signCount(4, big-endian).\n * flags = 0x05 (UP | UV). `signCount` must strictly increase across ceremonies\n * for the same wallet (anti-clone check); callers performing multiple sequential\n * signs should pass an incrementing value.\n */\nexport function buildAuthenticatorData(rpId: string = DEFAULT_RP_ID, signCount: number = 1): Uint8Array {\n const rpIdHash = createHash(\"sha256\").update(rpId).digest();\n const out = new Uint8Array(37);\n out.set(rpIdHash, 0);\n out[32] = 0x05; // UP | UV\n new DataView(out.buffer).setUint32(33, signCount >>> 0, false);\n return out;\n}\n\nexport interface BuildCredentialOptions {\n /** The base64url challenge returned by the begin endpoint. */\n challenge: string;\n signer: PasskeyCeremonySigner;\n rpId?: string;\n origin?: string;\n signCount?: number;\n}\n\n/**\n * Build a complete WebAuthn AuthenticationResponseJSON for a dynamic TA\n * challenge: construct clientDataJSON (embedding the challenge) + authenticatorData,\n * then sign (authenticatorData || SHA-256(clientDataJSON)).\n */\nexport async function buildAuthenticationCredential(\n opts: BuildCredentialOptions\n): Promise<WebAuthnAuthenticationCredential> {\n const origin = opts.origin ?? DEFAULT_ORIGIN;\n const rpId = opts.rpId ?? DEFAULT_RP_ID;\n const signCount = opts.signCount ?? 1;\n\n const clientDataJSON = buildClientDataJSON(opts.challenge, origin);\n const authenticatorData = buildAuthenticatorData(rpId, signCount);\n const clientDataHash = createHash(\"sha256\").update(clientDataJSON).digest();\n\n // WebAuthn message: authenticatorData || SHA-256(clientDataJSON).\n const message = new Uint8Array(authenticatorData.length + clientDataHash.length);\n message.set(authenticatorData, 0);\n message.set(clientDataHash, authenticatorData.length);\n\n const signature = await opts.signer.sign(message);\n\n return {\n id: opts.signer.credentialId,\n rawId: opts.signer.credentialId,\n type: \"public-key\",\n response: {\n clientDataJSON: base64UrlEncode(clientDataJSON),\n authenticatorData: base64UrlEncode(authenticatorData),\n signature: base64UrlEncode(signature),\n },\n };\n}\n\n// ── Orchestration: begin → embed → assert ─────────────────────────────────\n\n/** Minimal shape returned by BeginAuthentication / begin-grant-session-auth. */\nexport interface BeginCeremonyResponse {\n ChallengeId: string;\n Options: { challenge: string };\n}\n\nexport interface RunCeremonyOptions {\n signer: PasskeyCeremonySigner;\n rpId?: string;\n origin?: string;\n signCount?: number;\n}\n\n/**\n * Run a full WebAuthn challenge-binding ceremony (AirAccount #49):\n * 1. fetch a one-time TA challenge from the `begin` endpoint,\n * 2. embed it in clientDataJSON,\n * 3. build + sign the assertion,\n * 4. return `{ ChallengeId, Credential }` for the KMS `WebAuthn` /\n * `webAuthnAssertion` field.\n *\n * `begin` is injected so the same helper serves both the generic\n * (purpose=\"authentication\") and grant-session (purpose=\"grant-session\")\n * challenge endpoints.\n */\nexport async function runWebAuthnCeremony(\n begin: () => Promise<BeginCeremonyResponse>,\n options: RunCeremonyOptions\n): Promise<WebAuthnAssertion> {\n const begun = await begin();\n const challenge = begun?.Options?.challenge;\n if (!begun?.ChallengeId || !challenge) {\n throw new Error(\n \"WebAuthn ceremony: begin endpoint did not return a ChallengeId + Options.challenge\"\n );\n }\n const credential = await buildAuthenticationCredential({\n challenge,\n signer: options.signer,\n rpId: options.rpId,\n origin: options.origin,\n signCount: options.signCount,\n });\n return { ChallengeId: begun.ChallengeId, Credential: credential };\n}\n\n// ── Begin-endpoint fetchers (shared by KmsManager + the agent/session services) ──\n\n/** Fetch a generic authentication challenge (purpose=\"authentication\"). */\nexport function beginAuthenticationChallenge(\n http: KmsHttpClient,\n keyId: string\n): Promise<BeginCeremonyResponse> {\n return http.post<BeginCeremonyResponse>(\"/BeginAuthentication\", { KeyId: keyId });\n}\n\n/** Fetch a grant-session challenge (purpose=\"grant-session\"). */\nexport function beginGrantSessionChallenge(\n http: KmsHttpClient,\n keyId: string\n): Promise<BeginCeremonyResponse> {\n return http.get<BeginCeremonyResponse>(\"/kms/begin-grant-session-auth\", {\n params: { keyId },\n });\n}\n\n/**\n * Convenience: run a generic authentication ceremony over an {@link KmsHttpClient}.\n * Covers DeriveAddress / Sign / SignHash / SignTypedData / agent-key /\n * p256-session signing paths.\n */\nexport function runAuthenticationCeremony(\n http: KmsHttpClient,\n keyId: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n): Promise<WebAuthnAssertion> {\n return runWebAuthnCeremony(() => beginAuthenticationChallenge(http, keyId), {\n signer,\n ...options,\n });\n}\n\n/**\n * Convenience: run a grant-session ceremony over an {@link KmsHttpClient}.\n * Required by sign-grant-session / sign-p256-grant-session, which reject the\n * generic 'authentication' challenge for cross-op replay safety.\n */\nexport function runGrantSessionCeremony(\n http: KmsHttpClient,\n keyId: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n): Promise<WebAuthnAssertion> {\n return runWebAuthnCeremony(() => beginGrantSessionChallenge(http, keyId), {\n signer,\n ...options,\n });\n}\n","import { hashMessage } from \"../../migration/viem/signatures\";\nimport { ILogger } from \"../interfaces/logger\";\nimport { KmsHttpClient } from \"./kms-http-client\";\nimport {\n PasskeyCeremonySigner,\n RunCeremonyOptions,\n runAuthenticationCeremony,\n runGrantSessionCeremony,\n} from \"./webauthn-ceremony\";\n\n// ── Legacy Passkey Assertion (reusable for BLS dual-signing) ─────\n\nexport interface LegacyPasskeyAssertion {\n AuthenticatorData: string; // \"0x...\"\n ClientDataHash: string; // \"0x...\"\n Signature: string; // \"0x...\"\n}\n\n// ── WebAuthn Assertion (v0.19.0+, one-time use) ──────────────────\n\nexport interface WebAuthnAssertion {\n // PascalCase to match the KMS wire format: the server struct uses\n // #[serde(rename = \"ChallengeId\")] / #[serde(rename = \"Credential\")].\n ChallengeId: string;\n Credential: unknown; // AuthenticationResponseJSON from @simplewebauthn/browser\n}\n\n// ── CreateKey ────────────────────────────────────────────────────\n\nexport interface KmsCreateKeyRequest {\n Description: string;\n KeyUsage?: string;\n KeySpec?: string;\n Origin?: string;\n PasskeyPublicKey: string; // P-256 public key hex (required for new KMS)\n}\n\nexport interface KmsCreateKeyResponse {\n KeyMetadata: {\n KeyId: string;\n Arn: string;\n CreationDate: string;\n Enabled: boolean;\n Description: string;\n KeyUsage: string;\n KeySpec: string;\n Origin: string;\n Address?: string;\n };\n Mnemonic: string;\n Address?: string;\n Status?: string; // \"deriving\" — address is derived asynchronously\n}\n\n// ── SignHash ─────────────────────────────────────────────────────\n\nexport interface KmsSignHashResponse {\n Signature: string;\n}\n\n// ── WebAuthn Registration ────────────────────────────────────────\n\nexport interface KmsBeginRegistrationRequest {\n Description?: string;\n UserName?: string;\n UserDisplayName?: string;\n}\n\nexport interface KmsBeginRegistrationResponse {\n ChallengeId: string;\n Options: PublicKeyCredentialCreationOptions;\n}\n\nexport interface KmsCompleteRegistrationRequest {\n ChallengeId: string;\n Credential: unknown; // RegistrationResponseJSON from @simplewebauthn/browser\n Description?: string;\n}\n\nexport interface KmsCompleteRegistrationResponse {\n KeyId: string;\n CredentialId: string;\n Status: string;\n}\n\n// ── WebAuthn Authentication ──────────────────────────────────────\n\nexport interface KmsBeginAuthenticationRequest {\n Address?: string;\n KeyId?: string;\n}\n\nexport interface KmsBeginAuthenticationResponse {\n ChallengeId: string;\n Options: PublicKeyCredentialRequestOptions;\n}\n\n// ── Sign Typed Data (v0.20.0) ────────────────────────────────────\n// The KMS hashes the typed data host-side, so the full EIP-712 structure is sent\n// (NOT pre-computed domainSeparator/structHash — that was the pre-v0.19 contract).\n\nexport interface KmsEip712Domain {\n name?: string;\n version?: string;\n chainId?: number;\n verifyingContract?: string;\n}\n\n/** One entry in a `types` definition: a struct name and its ordered fields. */\nexport interface KmsEip712TypeDef {\n name: string; // e.g. \"Mail\", \"EIP712Domain\"\n fields: Array<{ name: string; type: string }>;\n}\n\n/** One field value for the primary type's message. */\nexport interface KmsEip712FieldValue {\n name: string;\n value: unknown;\n}\n\nexport interface KmsSignTypedDataRequest {\n keyId: string;\n hdPath?: string; // defaults to m/44'/60'/0'/0/0 server-side\n domain: KmsEip712Domain;\n primaryType: string;\n types: KmsEip712TypeDef[];\n message: KmsEip712FieldValue[];\n /** Required unless a Bearer agent JWT is supplied. Legacy passkeyAssertion is rejected. */\n webAuthnAssertion?: WebAuthnAssertion;\n}\n\nexport interface KmsSignTypedDataResponse {\n keyId: string;\n signature: string; // 65-byte hex (R||S||V)\n}\n\n// ── Grant Session Signing (v0.19.0+) ────────────────────────────\n\nexport interface KmsBeginGrantSessionAuthRequest {\n keyId: string;\n}\n\nexport interface KmsBeginGrantSessionAuthResponse {\n // PascalCase to match the KMS AuthenticationOptionsResponse wire format\n // (#[serde(rename = \"ChallengeId\" / \"Options\")]).\n ChallengeId: string;\n Options: PublicKeyCredentialRequestOptions;\n}\n\nexport interface KmsSignGrantSessionRequest {\n keyId: string;\n hdPath?: string;\n chainId: number;\n verifyingContract: string;\n account: string;\n sessionKey: string;\n expiry: number;\n contractScope: string; // server type is String (scope mode marker)\n selectorScope: string; // bytes4 hex — server type is String\n velocityLimit: number;\n velocityWindow: number;\n callTargets: string[];\n selectorAllowlist: string[];\n nonce: number;\n webAuthnAssertion: WebAuthnAssertion;\n}\n\nexport interface KmsSignGrantSessionResponse {\n keyId: string;\n signature: string; // 65-byte hex (R||S||V, V=27/28)\n}\n\nexport interface KmsSignP256GrantSessionRequest {\n keyId: string;\n hdPath?: string;\n chainId: number;\n verifyingContract: string;\n account: string;\n keyX: string; // 32-byte hex P256 public key X coordinate\n keyY: string; // 32-byte hex P256 public key Y coordinate\n expiry: number;\n contractScope: string; // server type is String (scope mode marker)\n selectorScope: string; // bytes4 hex — server type is String\n velocityLimit: number;\n velocityWindow: number;\n callTargets: string[];\n selectorAllowlist: string[];\n nonce: number;\n webAuthnAssertion: WebAuthnAssertion;\n}\n\n// ── Key Status ───────────────────────────────────────────────────\n\nexport interface KmsKeyStatusResponse {\n KeyId: string;\n Status: \"creating\" | \"deriving\" | \"ready\" | \"error\";\n Address?: string;\n PublicKey?: string;\n DerivationPath?: string;\n Error?: string;\n}\n\n// ── Describe Key ─────────────────────────────────────────────────\n\nexport interface KmsDescribeKeyResponse {\n KeyMetadata: {\n KeyId: string;\n Address?: string;\n PublicKey?: string;\n DerivationPath?: string;\n PasskeyPublicKey?: string;\n Arn?: string;\n CreationDate?: string;\n Enabled?: boolean;\n Description?: string;\n KeyUsage?: string;\n KeySpec?: string;\n Origin?: string;\n };\n}\n\n// ── EthereumTransaction (for POST /Sign) ─────────────────────────\n\nexport interface KmsEthereumTransaction {\n chainId: number;\n nonce: number;\n to: string;\n value: string; // uint256 (decimal or 0x…)\n gasPrice: string;\n gas: number;\n data: string;\n}\n\n// ── Sign (message or EIP-155 transaction) ────────────────────────\n\nexport interface KmsSignRequest {\n KeyId?: string;\n Address?: string;\n DerivationPath?: string;\n /** Provide exactly one of Message or Transaction. */\n Message?: string; // hex\n Transaction?: KmsEthereumTransaction;\n SigningAlgorithm?: string;\n WebAuthn?: WebAuthnAssertion;\n Passkey?: LegacyPasskeyAssertion;\n}\n\nexport interface KmsSignResponse {\n Signature: string;\n TransactionHash?: string;\n}\n\n// ── GetPublicKey ─────────────────────────────────────────────────\n\nexport interface KmsGetPublicKeyResponse {\n KeyId: string;\n PublicKey: string;\n Address?: string;\n KeyUsage?: string;\n KeySpec?: string;\n}\n\n// ── DeriveAddress ────────────────────────────────────────────────\n\nexport interface KmsDeriveAddressResponse {\n Address: string;\n PublicKey?: string;\n}\n\n// ── ListKeys ─────────────────────────────────────────────────────\n\nexport interface KmsListKeysResponse {\n Keys: Array<{ KeyId: string; KeyArn?: string }>;\n Truncated?: boolean;\n NextMarker?: string;\n}\n\n// ── DeleteKey ────────────────────────────────────────────────────\n\nexport interface KmsDeleteKeyResponse {\n KeyId: string;\n DeletionDate?: string;\n}\n\n// ── ChangePasskey ────────────────────────────────────────────────\n\nexport interface KmsChangePasskeyResponse {\n KeyId: string;\n Changed: boolean;\n}\n\n// ── UnfreezeKey ──────────────────────────────────────────────────\n\nexport interface KmsUnfreezeKeyResponse {\n KeyId: string;\n // \"active\" once unfrozen (or already active); mirrors the KMS LifecycleStatus enum.\n LifecycleStatus: string;\n}\n\n/**\n * KMS service for remote key management with WebAuthn/Passkey integration.\n *\n * Targets the AAStar TEE KMS (v0.20.0, kms.aastar.io). WebAuthn registration /\n * authentication ceremonies are handled by the KMS directly; signing operations\n * require a Passkey assertion (Legacy hex) or a one-time WebAuthn ceremony.\n *\n * Wraps a shared {@link KmsHttpClient}; the composed services (agent / session /\n * payment / monitor) reuse the same client via {@link KmsManager.httpClient}.\n */\nexport class KmsManager {\n private readonly client: KmsHttpClient;\n readonly logger: ILogger;\n\n constructor(options: {\n kmsEndpoint?: string;\n kmsEnabled?: boolean;\n kmsApiKey?: string;\n logger?: ILogger;\n }) {\n this.client = new KmsHttpClient(options);\n this.logger = this.client.logger;\n }\n\n isKmsEnabled(): boolean {\n return this.client.enabled;\n }\n\n /** Shared HTTP transport — pass to KmsAgentService / KmsSessionService / etc. */\n get httpClient(): KmsHttpClient {\n return this.client;\n }\n\n private ensureEnabled(): void {\n this.client.ensureEnabled();\n }\n\n /** POST with x-amz-target header (required for wallet/signing operations). */\n private async amzPost<T>(path: string, target: string, body: unknown): Promise<T> {\n return this.client.amzPost<T>(path, target, body);\n }\n\n // ── Key Management ──────────────────────────────────────────────\n\n async createKey(description: string, passkeyPublicKey: string): Promise<KmsCreateKeyResponse> {\n this.ensureEnabled();\n\n return this.amzPost(\"/CreateKey\", \"TrentService.CreateKey\", {\n Description: description,\n KeyUsage: \"SIGN_VERIFY\",\n KeySpec: \"ECC_SECG_P256K1\",\n Origin: \"EXTERNAL_KMS\",\n PasskeyPublicKey: passkeyPublicKey,\n });\n }\n\n async getKeyStatus(keyId: string): Promise<KmsKeyStatusResponse> {\n this.ensureEnabled();\n\n return this.client.get<KmsKeyStatusResponse>(\"/KeyStatus\", {\n params: { KeyId: keyId },\n });\n }\n\n async describeKey(keyId: string): Promise<KmsDescribeKeyResponse> {\n this.ensureEnabled();\n\n return this.amzPost(\"/DescribeKey\", \"TrentService.DescribeKey\", { KeyId: keyId });\n }\n\n /** Get a key's public key (uncompressed). Not WebAuthn-gated. */\n async getPublicKey(target: { KeyId?: string; Address?: string }): Promise<KmsGetPublicKeyResponse> {\n this.ensureEnabled();\n return this.amzPost(\"/GetPublicKey\", \"TrentService.GetPublicKey\", target);\n }\n\n /**\n * Derive an Ethereum address at a BIP-44 path (WebAuthn-gated).\n * Provide a WebAuthn ceremony assertion (preferred) or a Legacy passkey assertion.\n */\n async deriveAddress(params: {\n KeyId: string;\n DerivationPath: string;\n WebAuthn?: WebAuthnAssertion;\n Passkey?: LegacyPasskeyAssertion;\n }): Promise<KmsDeriveAddressResponse> {\n this.ensureEnabled();\n return this.amzPost(\"/DeriveAddress\", \"TrentService.DeriveAddress\", params);\n }\n\n /** List keys (paginated). Not WebAuthn-gated. */\n async listKeys(params: { Limit?: number; Marker?: string } = {}): Promise<KmsListKeysResponse> {\n this.ensureEnabled();\n return this.amzPost(\"/ListKeys\", \"TrentService.ListKeys\", params);\n }\n\n /**\n * Schedule key deletion (AWS-KMS action ScheduleKeyDeletion; WebAuthn-gated).\n * RPMB-bound on the TEE — requires a passkey/WebAuthn assertion on the normal path.\n */\n async deleteKey(params: {\n KeyId: string;\n PendingWindowInDays?: number;\n WebAuthn?: WebAuthnAssertion;\n Passkey?: LegacyPasskeyAssertion;\n }): Promise<KmsDeleteKeyResponse> {\n this.ensureEnabled();\n return this.amzPost(\"/DeleteKey\", \"TrentService.ScheduleKeyDeletion\", params);\n }\n\n /**\n * Unfreeze a dormant (frozen) key (issue #42; WebAuthn-gated).\n * A key auto-frozen by the dormant-key sweep rejects signing until unfrozen.\n * The TEE verifies the owner via the same strict WebAuthn ceremony as\n * {@link deleteKey}; ownership is checked even when the key is already active,\n * so this cannot be used as an unauthenticated key-state probe. Unlike DeleteKey\n * this endpoint takes no `x-amz-target` header — it authenticates via the default\n * API key plus the WebAuthn assertion in the body.\n */\n async unfreezeKey(params: {\n KeyId: string;\n WebAuthn?: WebAuthnAssertion;\n }): Promise<KmsUnfreezeKeyResponse> {\n this.ensureEnabled();\n return this.client.post<KmsUnfreezeKeyResponse>(\"/UnfreezeKey\", params);\n }\n\n /**\n * Rotate the WebAuthn passkey bound to a key (WebAuthn-gated, RPMB-bound).\n * `PasskeyPublicKey` is the NEW P-256 public key (0x04… 65-byte uncompressed).\n */\n async changePasskey(params: {\n KeyId: string;\n PasskeyPublicKey: string;\n WebAuthn?: WebAuthnAssertion;\n Passkey?: LegacyPasskeyAssertion;\n }): Promise<KmsChangePasskeyResponse> {\n this.ensureEnabled();\n return this.amzPost(\"/ChangePasskey\", \"TrentService.ChangePasskey\", params);\n }\n\n /**\n * Sign a message or an EIP-155 transaction (WebAuthn-gated).\n * Provide exactly one of `Message` (hex) or `Transaction`. For a raw 32-byte\n * digest use {@link signHash} / {@link signHashWithWebAuthn} instead.\n */\n async sign(params: KmsSignRequest): Promise<KmsSignResponse> {\n this.ensureEnabled();\n return this.amzPost(\"/Sign\", \"TrentService.Sign\", params);\n }\n\n /**\n * Poll KeyStatus until the key is ready (address derived) or timeout.\n * STM32 key derivation takes 60-75 seconds on first creation.\n */\n async pollUntilReady(\n keyId: string,\n timeoutMs: number = 120_000,\n intervalMs: number = 3_000\n ): Promise<KmsKeyStatusResponse> {\n this.ensureEnabled();\n\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n const status = await this.getKeyStatus(keyId);\n this.logger.debug(`Key ${keyId} status: ${status.Status}`);\n\n if (status.Status === \"ready\") {\n return status;\n }\n if (status.Status === \"error\") {\n throw new Error(`KMS key derivation failed: ${status.Error ?? \"unknown error\"}`);\n }\n\n await new Promise(resolve => setTimeout(resolve, intervalMs));\n }\n\n throw new Error(`KMS key derivation timed out after ${timeoutMs}ms`);\n }\n\n // ── Signing ─────────────────────────────────────────────────────\n\n /**\n * Sign a hash using Legacy Passkey assertion (reusable for BLS dual-signing).\n */\n async signHash(\n hash: string,\n assertion: LegacyPasskeyAssertion,\n target: { Address?: string; KeyId?: string }\n ): Promise<KmsSignHashResponse> {\n this.ensureEnabled();\n\n const formattedHash = hash.startsWith(\"0x\") ? hash : `0x${hash}`;\n\n const body: Record<string, unknown> = {\n Hash: formattedHash,\n Passkey: assertion,\n };\n\n if (target.Address) {\n body.Address = target.Address;\n }\n if (target.KeyId) {\n body.KeyId = target.KeyId;\n }\n\n return this.amzPost(\"/SignHash\", \"TrentService.SignHash\", body);\n }\n\n /**\n * Sign a hash using a WebAuthn ceremony assertion (one-time use).\n */\n async signHashWithWebAuthn(\n hash: string,\n challengeId: string,\n credential: unknown,\n target: { Address?: string; KeyId?: string }\n ): Promise<KmsSignHashResponse> {\n this.ensureEnabled();\n\n const formattedHash = hash.startsWith(\"0x\") ? hash : `0x${hash}`;\n\n const body: Record<string, unknown> = {\n Hash: formattedHash,\n WebAuthn: { ChallengeId: challengeId, Credential: credential },\n };\n\n if (target.Address) {\n body.Address = target.Address;\n }\n if (target.KeyId) {\n body.KeyId = target.KeyId;\n }\n\n return this.amzPost(\"/SignHash\", \"TrentService.SignHash\", body);\n }\n\n // ── Sign Typed Data (v0.19.0+) ─────────────────────────────────\n\n /**\n * Sign arbitrary EIP-712 typed data via `POST /kms/SignTypedData` (v0.20.0).\n *\n * The KMS hashes the typed data host-side, so the FULL EIP-712 structure\n * (domain / primaryType / types / message) is sent — not a pre-hashed\n * domainSeparator/structHash. The `webAuthnAssertion` challenge comes from a\n * generic {@link beginAuthentication} ceremony (purpose=\"authentication\").\n *\n * Alternatively, agents authenticate with a Bearer JWT — see KmsAgentService.\n */\n async signTypedDataWithWebAuthn(\n params: KmsSignTypedDataRequest\n ): Promise<KmsSignTypedDataResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsSignTypedDataResponse>(\"/kms/SignTypedData\", params);\n }\n\n // ── Grant Session Off-chain Signing (v0.19.0+) ─────────────────\n\n /**\n * Begin a grant-session WebAuthn challenge.\n * The returned challengeId can ONLY be used with sign-grant-session, not sign-typed-data.\n */\n async beginGrantSessionAuth(\n params: KmsBeginGrantSessionAuthRequest\n ): Promise<KmsBeginGrantSessionAuthResponse> {\n this.ensureEnabled();\n\n return this.client.get<KmsBeginGrantSessionAuthResponse>(\"/kms/begin-grant-session-auth\", {\n params: { keyId: params.keyId },\n });\n }\n\n /**\n * Sign a GRANT_SESSION_V2 hash off-chain inside the TEE (secp256k1 session key).\n * Returns a 65-byte signature (R||S||V, V=27/28) for use in grantSessionWithSig().\n */\n async signGrantSession(\n params: KmsSignGrantSessionRequest\n ): Promise<KmsSignGrantSessionResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsSignGrantSessionResponse>(\"/kms/sign-grant-session\", params);\n }\n\n /**\n * Sign a GRANT_P256_SESSION_V2 hash off-chain inside the TEE (P256 session key).\n * Returns a 65-byte signature for use in grantP256SessionWithSig().\n */\n async signP256GrantSession(\n params: KmsSignP256GrantSessionRequest\n ): Promise<KmsSignGrantSessionResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsSignGrantSessionResponse>(\"/kms/sign-p256-grant-session\", params);\n }\n\n // ── Challenge-binding ceremonies (#49 / Beta3) ──────────────────\n //\n // These run the full WebAuthn challenge-binding ceremony in one call:\n // fetch the TA one-time nonce, embed it in clientDataJSON, build + sign the\n // assertion, then invoke the signing endpoint with the resulting\n // `WebAuthn` / `webAuthnAssertion`. They share the\n // {@link runAuthenticationCeremony} / {@link runGrantSessionCeremony} helper,\n // so every path produces an identical, replay-protected assertion structure.\n\n /**\n * Run a generic authentication ceremony (purpose=\"authentication\") bound to a\n * fresh TA challenge. The returned assertion is valid for DeriveAddress / Sign\n * / SignHash / SignTypedData / agent-key / p256-session signing.\n */\n async runAuthenticationCeremony(\n keyId: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<WebAuthnAssertion> {\n this.ensureEnabled();\n return runAuthenticationCeremony(this.client, keyId, signer, options);\n }\n\n /**\n * Run a grant-session ceremony (purpose=\"grant-session\") bound to a fresh TA\n * challenge — required by {@link signGrantSession} / {@link signP256GrantSession}\n * (the generic 'authentication' challenge is rejected there for replay safety).\n */\n async runGrantSessionCeremony(\n keyId: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<WebAuthnAssertion> {\n this.ensureEnabled();\n return runGrantSessionCeremony(this.client, keyId, signer, options);\n }\n\n /** Derive an address, running the challenge-binding ceremony internally. */\n async deriveAddressWithCeremony(\n params: { KeyId: string; DerivationPath: string },\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsDeriveAddressResponse> {\n this.ensureEnabled();\n const WebAuthn = await this.runAuthenticationCeremony(params.KeyId, signer, options);\n return this.deriveAddress({ ...params, WebAuthn });\n }\n\n /**\n * Sign a message or EIP-155 transaction, running the challenge-binding ceremony\n * internally. `params.KeyId` is required (it identifies the wallet to challenge).\n */\n async signWithCeremony(\n params: Omit<KmsSignRequest, \"WebAuthn\" | \"Passkey\"> & { KeyId: string },\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsSignResponse> {\n this.ensureEnabled();\n const WebAuthn = await this.runAuthenticationCeremony(params.KeyId, signer, options);\n return this.sign({ ...params, WebAuthn });\n }\n\n /** Sign a 32-byte digest, running the challenge-binding ceremony internally. */\n async signHashWithCeremony(\n hash: string,\n target: { KeyId: string },\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsSignHashResponse> {\n this.ensureEnabled();\n const assertion = await this.runAuthenticationCeremony(target.KeyId, signer, options);\n return this.signHashWithWebAuthn(hash, assertion.ChallengeId, assertion.Credential, target);\n }\n\n /** Sign EIP-712 typed data, running the challenge-binding ceremony internally. */\n async signTypedDataWithCeremony(\n params: Omit<KmsSignTypedDataRequest, \"webAuthnAssertion\">,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsSignTypedDataResponse> {\n this.ensureEnabled();\n const webAuthnAssertion = await this.runAuthenticationCeremony(params.keyId, signer, options);\n return this.signTypedDataWithWebAuthn({ ...params, webAuthnAssertion });\n }\n\n /**\n * Sign a GRANT_SESSION_V2 hash, running the grant-session ceremony internally\n * (uses the purpose-bound `begin-grant-session-auth` challenge).\n */\n async signGrantSessionWithCeremony(\n params: Omit<KmsSignGrantSessionRequest, \"webAuthnAssertion\">,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsSignGrantSessionResponse> {\n this.ensureEnabled();\n const webAuthnAssertion = await this.runGrantSessionCeremony(params.keyId, signer, options);\n return this.signGrantSession({ ...params, webAuthnAssertion });\n }\n\n /**\n * Sign a GRANT_P256_SESSION_V2 hash, running the grant-session ceremony\n * internally (uses the purpose-bound `begin-grant-session-auth` challenge).\n */\n async signP256GrantSessionWithCeremony(\n params: Omit<KmsSignP256GrantSessionRequest, \"webAuthnAssertion\">,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsSignGrantSessionResponse> {\n this.ensureEnabled();\n const webAuthnAssertion = await this.runGrantSessionCeremony(params.keyId, signer, options);\n return this.signP256GrantSession({ ...params, webAuthnAssertion });\n }\n\n // ── WebAuthn Ceremonies ─────────────────────────────────────────\n\n async beginRegistration(\n params: KmsBeginRegistrationRequest\n ): Promise<KmsBeginRegistrationResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsBeginRegistrationResponse>(\"/BeginRegistration\", params);\n }\n\n async completeRegistration(\n params: KmsCompleteRegistrationRequest\n ): Promise<KmsCompleteRegistrationResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsCompleteRegistrationResponse>(\"/CompleteRegistration\", params);\n }\n\n async beginAuthentication(\n params: KmsBeginAuthenticationRequest\n ): Promise<KmsBeginAuthenticationResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsBeginAuthenticationResponse>(\"/BeginAuthentication\", params);\n }\n\n /**\n * Begin a generic WebAuthn authentication ceremony for a key, returning a\n * challenge usable for SignHash / SignTypedData (purpose=\"authentication\").\n *\n * NOTE: there is no dedicated `begin-webauthn-auth` endpoint — this delegates\n * to `POST /BeginAuthentication`. (Grant-session signing needs a purpose-bound\n * challenge from {@link beginGrantSessionAuth} instead.)\n */\n async beginWebAuthnAuth(keyId: string): Promise<KmsBeginAuthenticationResponse> {\n this.ensureEnabled();\n\n return this.client.post<KmsBeginAuthenticationResponse>(\"/BeginAuthentication\", { KeyId: keyId });\n }\n\n // ── Factory ─────────────────────────────────────────────────────\n\n createKmsSigner(\n keyId: string,\n address: string,\n assertionProvider: () => Promise<LegacyPasskeyAssertion>\n ): KmsSigner {\n this.ensureEnabled();\n return new KmsSigner(keyId, address, this, assertionProvider);\n }\n}\n\n/**\n * KMS-backed signer with Passkey assertion.\n *\n * Each signing operation calls the `assertionProvider` to obtain a Legacy\n * Passkey assertion, which is then passed to KMS SignHash. The Legacy format\n * is reusable (no challenge consumption), enabling BLS dual-signing.\n *\n * Narrowed during the ethers -> viem migration: only the EIP-191 personal-sign\n * and address-read behaviour is actually consumed by the SDK, so the former\n * ethers.AbstractSigner surface (signTransaction / signTypedData / connect /\n * provider) has been dropped.\n */\nexport class KmsSigner {\n constructor(\n private readonly keyId: string,\n private readonly _address: string,\n private readonly kmsManager: KmsManager,\n private readonly assertionProvider: () => Promise<LegacyPasskeyAssertion>\n ) {}\n\n async getAddress(): Promise<string> {\n return this._address;\n }\n\n async signMessage(message: string | Uint8Array): Promise<string> {\n // EIP-191 personal-sign: a string is hashed as UTF-8 text, a byte array as\n // raw bytes — byte-identical to ethers `hashMessage(toUtf8Bytes(str) | bytes)`.\n const messageHash = hashMessage(message);\n const assertion = await this.assertionProvider();\n const signResponse = await this.kmsManager.signHash(messageHash, assertion, {\n Address: this._address,\n });\n return \"0x\" + signResponse.Signature;\n }\n}\n","import { KmsHttpClient } from \"./kms-http-client\";\nimport { WebAuthnAssertion, LegacyPasskeyAssertion } from \"./kms-signer\";\nimport {\n PasskeyCeremonySigner,\n RunCeremonyOptions,\n runAuthenticationCeremony,\n} from \"./webauthn-ceremony\";\n\n// ── CreateAgentKey ───────────────────────────────────────────────\n\n/**\n * Request to mint a new agent key under an existing human key.\n *\n * WebAuthn-gated: the human approves the mint with a one-time WebAuthn ceremony\n * (preferred) or a Legacy passkey assertion. The challenge is obtained via\n * {@link KmsManager.beginAuthentication} (generic, purpose=\"authentication\") —\n * the caller supplies the resulting assertion here.\n */\nexport interface KmsCreateAgentKeyRequest {\n humanKeyId: string;\n label?: string;\n webAuthnAssertion?: WebAuthnAssertion;\n passkeyAssertion?: LegacyPasskeyAssertion;\n}\n\nexport interface KmsCreateAgentKeyResponse {\n keyId: string; // \"wallet_uuid:agent_index\"\n agentAddress: string;\n derivationPath: string;\n agentCredential: string; // TEE-issued JWT\n expiresAt: number;\n}\n\n// ── SignAgent ────────────────────────────────────────────────────\n\n/**\n * Request to sign a userOpHash with an agent key, authenticated by the agent's\n * TEE-JWT credential (Bearer). Used for gasless ERC-4337 sponsorship.\n */\nexport interface KmsSignAgentRequest {\n keyId: string;\n payload: string; // hex userOpHash\n algorithm?: string; // defaults to \"secp256k1\" server-side\n accountAddress: string; // 0x… ERC-4337 account\n}\n\nexport interface KmsSignAgentResponse {\n keyId: string;\n agentAddress: string;\n /** Hex 106-byte signature: [0x08][account(20)][key(20)][r(32)][s(32)][v(1)]. */\n signature: string;\n}\n\n// ── RefreshAgentCredential ───────────────────────────────────────\n\n/**\n * Request to refresh (re-mint) an agent's TEE-JWT credential before it expires.\n *\n * Authenticated with the existing (still-valid) credential via Bearer JWT, plus\n * a WebAuthn / Legacy passkey assertion from the human key owner.\n */\nexport interface KmsRefreshAgentCredentialRequest {\n keyId: string;\n webAuthnAssertion?: WebAuthnAssertion;\n passkeyAssertion?: LegacyPasskeyAssertion;\n}\n\n/**\n * The server response shape is not strictly documented; this models the fields\n * the SDK relies on. `keyId` is echoed back optionally.\n */\nexport interface KmsRefreshAgentCredentialResponse {\n keyId?: string;\n agentCredential: string; // new TEE-issued JWT\n expiresAt: number;\n}\n\n// ── RevokeAgentCredential ────────────────────────────────────────\n\n/**\n * Request to revoke an agent's credential (WebAuthn-gated).\n *\n * The challenge is obtained via {@link KmsManager.beginAuthentication} (generic,\n * purpose=\"authentication\"); the caller supplies the resulting assertion here.\n */\nexport interface KmsRevokeAgentCredentialRequest {\n keyId: string;\n webAuthnAssertion?: WebAuthnAssertion;\n passkeyAssertion?: LegacyPasskeyAssertion;\n}\n\nexport interface KmsRevokeAgentCredentialResponse {\n success: boolean;\n revokedAt: number;\n}\n\n/**\n * Agent-key lifecycle service for the AAStar TEE KMS (v0.20.0).\n *\n * An \"agent key\" is a TEE-JWT credential minted under a human key, used for\n * gasless ERC-4337 sponsorship without re-prompting the human for each signature.\n * Lifecycle:\n * 1. {@link createAgentKey} — human mints the agent key (WebAuthn-gated)\n * 2. {@link signAgent} — agent signs userOpHashes (Bearer JWT auth)\n * 3. {@link refreshAgentCredential}— re-mint before expiry (Bearer JWT + WebAuthn)\n * 4. {@link revokeAgentCredential} — human revokes the agent key (WebAuthn-gated)\n *\n * Wraps a shared {@link KmsHttpClient} — obtain it via {@link KmsManager.httpClient}\n * so this service reuses the same connection config and auth headers.\n */\nexport class KmsAgentService {\n constructor(private readonly http: KmsHttpClient) {}\n\n /**\n * Mint a new agent key under an existing human key (WebAuthn-gated).\n *\n * The WebAuthn challenge is obtained from a generic\n * {@link KmsManager.beginAuthentication} ceremony (purpose=\"authentication\");\n * the caller supplies the resulting assertion in the request.\n */\n async createAgentKey(\n params: KmsCreateAgentKeyRequest\n ): Promise<KmsCreateAgentKeyResponse> {\n this.http.ensureEnabled();\n\n return this.http.post<KmsCreateAgentKeyResponse>(\"/kms/create-agent-key\", params);\n }\n\n /**\n * Sign a userOpHash with an agent key, authenticated by the agent's TEE-JWT\n * credential (`jwt`, the `agentCredential` from {@link createAgentKey}).\n * Returns the 106-byte packed signature for ERC-4337 sponsorship.\n */\n async signAgent(\n params: KmsSignAgentRequest,\n jwt: string\n ): Promise<KmsSignAgentResponse> {\n this.http.ensureEnabled();\n\n return this.http.postWithBearer<KmsSignAgentResponse>(\"/kms/sign-agent\", params, jwt);\n }\n\n /**\n * Refresh (re-mint) an agent credential before it expires. Authenticated with\n * the existing credential (`jwt`, Bearer) plus a human WebAuthn / passkey\n * assertion in the request.\n */\n async refreshAgentCredential(\n params: KmsRefreshAgentCredentialRequest,\n jwt: string\n ): Promise<KmsRefreshAgentCredentialResponse> {\n this.http.ensureEnabled();\n\n return this.http.postWithBearer<KmsRefreshAgentCredentialResponse>(\n \"/kms/refresh-agent-credential\",\n params,\n jwt\n );\n }\n\n /**\n * Revoke an agent's credential (WebAuthn-gated).\n *\n * The WebAuthn challenge is obtained from a generic\n * {@link KmsManager.beginAuthentication} ceremony (purpose=\"authentication\");\n * the caller supplies the resulting assertion in the request.\n */\n async revokeAgentCredential(\n params: KmsRevokeAgentCredentialRequest\n ): Promise<KmsRevokeAgentCredentialResponse> {\n this.http.ensureEnabled();\n\n return this.http.post<KmsRevokeAgentCredentialResponse>(\n \"/kms/revoke-agent-credential\",\n params\n );\n }\n\n // ── Challenge-binding ceremony variants (#49 / Beta3) ────────────\n //\n // All agent-key WebAuthn gates use the generic purpose=\"authentication\"\n // challenge bound to the HUMAN key. These helpers run the full ceremony\n // (begin → clientDataJSON → assertion) via the shared\n // {@link runAuthenticationCeremony} helper, then invoke the endpoint.\n\n /** Mint an agent key, running the challenge-binding ceremony internally. */\n async createAgentKeyWithCeremony(\n params: Omit<KmsCreateAgentKeyRequest, \"webAuthnAssertion\" | \"passkeyAssertion\">,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsCreateAgentKeyResponse> {\n this.http.ensureEnabled();\n const webAuthnAssertion = await runAuthenticationCeremony(\n this.http,\n params.humanKeyId,\n signer,\n options\n );\n return this.createAgentKey({ ...params, webAuthnAssertion });\n }\n\n /**\n * Refresh an agent credential, running the challenge-binding ceremony\n * internally. `humanKeyId` is the owning human key challenged by the ceremony\n * (distinct from the agent `keyId` in `params`); `jwt` is the existing credential.\n */\n async refreshAgentCredentialWithCeremony(\n params: Omit<KmsRefreshAgentCredentialRequest, \"webAuthnAssertion\" | \"passkeyAssertion\">,\n humanKeyId: string,\n jwt: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsRefreshAgentCredentialResponse> {\n this.http.ensureEnabled();\n const webAuthnAssertion = await runAuthenticationCeremony(this.http, humanKeyId, signer, options);\n return this.refreshAgentCredential({ ...params, webAuthnAssertion }, jwt);\n }\n\n /**\n * Revoke an agent credential, running the challenge-binding ceremony internally.\n * `humanKeyId` is the owning human key challenged by the ceremony (distinct from\n * the agent `keyId` in `params`).\n */\n async revokeAgentCredentialWithCeremony(\n params: Omit<KmsRevokeAgentCredentialRequest, \"webAuthnAssertion\" | \"passkeyAssertion\">,\n humanKeyId: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<KmsRevokeAgentCredentialResponse> {\n this.http.ensureEnabled();\n const webAuthnAssertion = await runAuthenticationCeremony(this.http, humanKeyId, signer, options);\n return this.revokeAgentCredential({ ...params, webAuthnAssertion });\n }\n}\n","import { KmsHttpClient } from \"./kms-http-client\";\nimport { WebAuthnAssertion } from \"./kms-signer\";\nimport {\n PasskeyCeremonySigner,\n RunCeremonyOptions,\n runAuthenticationCeremony,\n} from \"./webauthn-ceremony\";\n\n// ── Create P256 Session Key (v0.20.0) ───────────────────────────\n\nexport interface CreateP256SessionKeyRequest {\n /** Human (root) key under which the session key is minted. */\n humanKeyId: string;\n /** Optional human-readable label for the session key. */\n label?: string;\n /**\n * One-time WebAuthn assertion gating creation. The challenge comes from a\n * generic {@link KmsManager.beginAuthentication} ceremony — the caller runs\n * the ceremony and supplies the resulting assertion here.\n */\n webAuthnAssertion?: WebAuthnAssertion;\n}\n\nexport interface CreateP256SessionKeyResponse {\n keyId: string;\n pubKeyX: string; // 0x… 32-byte P256 public key X coordinate\n pubKeyY: string; // 0x… 32-byte P256 public key Y coordinate\n algorithm: string; // \"p256\"\n agentCredential: string; // JWT — bearer token for subsequent per-UserOp signing\n expiresAt: number; // unix seconds\n}\n\n// ── Sign P256 UserOp (Bearer JWT auth) ──────────────────────────\n\nexport interface SignP256UserOpRequest {\n keyId: string;\n payload: string; // hex userOpHash (32 bytes)\n accountAddress: string; // 0x… ERC-4337 account address\n}\n\nexport interface SignP256UserOpResponse {\n keyId: string;\n pubKeyX: string;\n pubKeyY: string;\n /**\n * 149-byte P256 session-key wire format (hex):\n * [0x08][account(20)][keyX(32)][keyY(32)][r(32)][s(32)].\n */\n signature: string;\n}\n\n// ── Revoke P256 Session Key (v0.20.0) ───────────────────────────\n\nexport interface RevokeP256SessionKeyRequest {\n keyId: string;\n /**\n * One-time WebAuthn assertion gating revocation. The challenge comes from a\n * generic {@link KmsManager.beginAuthentication} ceremony — the caller runs\n * the ceremony and supplies the resulting assertion here.\n */\n webAuthnAssertion?: WebAuthnAssertion;\n}\n\nexport interface RevokeP256SessionKeyResponse {\n success: boolean;\n revokedAt: number; // unix seconds\n}\n\n/**\n * Manages the lifecycle of a P-256 session key minted under a human key for\n * ERC-4337 UserOp signing (AAStar TEE KMS v0.20.0).\n *\n * A session key is created under a root (human) key, used to sign UserOps via a\n * TEE-issued bearer JWT (the `agentCredential`), and eventually revoked. The\n * per-UserOp signature is the 149-byte P256 session-key wire format.\n *\n * Relationship to {@link KmsManager.signP256GrantSession}: that method signs the\n * GRANT_P256_SESSION_V2 authorization needed to *install* this key on-chain\n * (granting the session key its on-chain scope/policies). This service instead\n * manages the session key's own lifecycle (create / sign / revoke) once granted.\n *\n * Create and revoke are WebAuthn-gated: the challenge originates from a generic\n * {@link KmsManager.beginAuthentication} ceremony and the caller supplies the\n * resulting assertion. Per-UserOp signing authenticates with the bearer JWT.\n *\n * Wraps a shared {@link KmsHttpClient} — pass `KmsManager.httpClient`.\n */\nexport class KmsSessionService {\n constructor(private readonly http: KmsHttpClient) {}\n\n /**\n * Create a P-256 session key under a human key (WebAuthn-gated).\n *\n * `POST /kms/create-p256-session-key`. The `webAuthnAssertion` challenge comes\n * from a generic {@link KmsManager.beginAuthentication} ceremony supplied by\n * the caller. Returns the session key's public key plus an `agentCredential`\n * JWT used to authenticate subsequent {@link signP256UserOp} calls.\n */\n async createP256SessionKey(\n params: CreateP256SessionKeyRequest\n ): Promise<CreateP256SessionKeyResponse> {\n this.http.ensureEnabled();\n\n return this.http.post<CreateP256SessionKeyResponse>(\n \"/kms/create-p256-session-key\",\n params\n );\n }\n\n /**\n * Sign an ERC-4337 UserOp hash with a P-256 session key (Bearer JWT auth).\n *\n * `POST /kms/sign-p256-user-op`, authenticated with the `agentCredential` JWT\n * returned by {@link createP256SessionKey}. Returns the 149-byte P256\n * session-key wire-format signature.\n */\n async signP256UserOp(\n params: SignP256UserOpRequest,\n jwt: string\n ): Promise<SignP256UserOpResponse> {\n this.http.ensureEnabled();\n\n return this.http.postWithBearer<SignP256UserOpResponse>(\n \"/kms/sign-p256-user-op\",\n params,\n jwt\n );\n }\n\n /**\n * Revoke a P-256 session key (WebAuthn-gated, idempotent).\n *\n * `POST /kms/revoke-p256-session-key`. The `webAuthnAssertion` challenge comes\n * from a generic {@link KmsManager.beginAuthentication} ceremony supplied by\n * the caller. Idempotent: revoking an already-revoked key still resolves.\n */\n async revokeP256SessionKey(\n params: RevokeP256SessionKeyRequest\n ): Promise<RevokeP256SessionKeyResponse> {\n this.http.ensureEnabled();\n\n return this.http.post<RevokeP256SessionKeyResponse>(\n \"/kms/revoke-p256-session-key\",\n params\n );\n }\n\n // ── Challenge-binding ceremony variants (#49 / Beta3) ────────────\n //\n // Create + revoke gate on the generic purpose=\"authentication\" challenge bound\n // to the HUMAN key. These helpers run the full ceremony (begin → clientDataJSON\n // → assertion) via the shared {@link runAuthenticationCeremony} helper.\n\n /** Create a P-256 session key, running the challenge-binding ceremony internally. */\n async createP256SessionKeyWithCeremony(\n params: Omit<CreateP256SessionKeyRequest, \"webAuthnAssertion\">,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<CreateP256SessionKeyResponse> {\n this.http.ensureEnabled();\n const webAuthnAssertion = await runAuthenticationCeremony(\n this.http,\n params.humanKeyId,\n signer,\n options\n );\n return this.createP256SessionKey({ ...params, webAuthnAssertion });\n }\n\n /**\n * Revoke a P-256 session key, running the challenge-binding ceremony internally.\n * `humanKeyId` is the owning human key challenged by the ceremony (distinct from\n * the session `keyId` in `params`).\n */\n async revokeP256SessionKeyWithCeremony(\n params: Omit<RevokeP256SessionKeyRequest, \"webAuthnAssertion\">,\n humanKeyId: string,\n signer: PasskeyCeremonySigner,\n options?: Omit<RunCeremonyOptions, \"signer\">\n ): Promise<RevokeP256SessionKeyResponse> {\n this.http.ensureEnabled();\n const webAuthnAssertion = await runAuthenticationCeremony(this.http, humanKeyId, signer, options);\n return this.revokeP256SessionKey({ ...params, webAuthnAssertion });\n }\n}\n","import { KmsHttpClient } from \"./kms-http-client\";\nimport { WebAuthnAssertion } from \"./kms-signer\";\n\n// ── Auth modes (v0.20.0 P2 SuperPaymaster convenience signers) ───\n//\n// Each KMS payment endpoint authorizes the signing operation in ONE of two ways:\n// - a one-time WebAuthn ceremony assertion carried in the request body, or\n// - an agent/session JWT carried in the `Authorization: Bearer <jwt>` header.\n// Callers pick exactly one via the discriminated `KmsPaymentAuth` union.\n\nexport type KmsPaymentAuth = { jwt: string } | { webAuthnAssertion: WebAuthnAssertion };\n\n/** Shared signature response for all payment signing endpoints. */\nexport interface KmsPaymentSignatureResponse {\n keyId: string;\n signature: string; // 65-byte hex (R||S||V)\n}\n\n// ── SignMicropaymentVoucher ──────────────────────────────────────\n\nexport interface KmsSignMicropaymentVoucherRequest {\n keyId: string;\n hdPath?: string; // defaults to m/44'/60'/0'/0/0 server-side\n chainId: number;\n verifyingContract: string; // MicroPaymentChannel address (0x… 20-byte)\n channelId: string; // 0x… 32-byte\n cumulativeAmount: string; // uint256 (decimal or 0x…)\n}\n\n// ── SignGTokenAuthorization (EIP-3009 TransferWithAuthorization) ──\n\nexport interface KmsSignGTokenAuthorizationRequest {\n keyId: string;\n hdPath?: string; // defaults to m/44'/60'/0'/0/0 server-side\n chainId: number;\n gTokenAddress: string;\n from: string; // MUST equal the derived address\n to: string;\n value: string; // uint256\n validAfter: string;\n validBefore: string;\n nonce: string; // 0x… 32-byte\n}\n\n// ── SignX402Payment ──────────────────────────────────────────────\n\nexport interface KmsSignX402PaymentRequest {\n keyId: string;\n hdPath?: string; // defaults to m/44'/60'/0'/0/0 server-side\n chainId: number;\n verifyingContract: string;\n paymentId: string; // 0x… 32-byte\n amount: string; // uint256\n recipient: string;\n deadline: string;\n}\n\n/**\n * Convenience signers for SuperPaymaster payment flows (v0.20.0 P2).\n *\n * Each method maps to a fixed EIP-712 domain + type that the KMS builds host-side\n * and signs inside the TEE; the SDK only forwards the structured parameters. Every\n * endpoint accepts EITHER a one-time `webAuthnAssertion` in the body OR an agent\n * Bearer JWT — see {@link KmsPaymentAuth}.\n *\n * Wraps a shared {@link KmsHttpClient}; reuse the same instance across the agent /\n * session / payment / monitor services.\n */\nexport class KmsPaymentSigner {\n constructor(private readonly http: KmsHttpClient) {}\n\n /**\n * Dispatch a payment-signing request with the chosen auth mode.\n * JWT auth uses `postWithBearer`; WebAuthn auth merges the assertion into the body.\n */\n private async signWithAuth(\n path: string,\n body: Record<string, unknown>,\n auth: KmsPaymentAuth\n ): Promise<KmsPaymentSignatureResponse> {\n if (\"jwt\" in auth) {\n return this.http.postWithBearer<KmsPaymentSignatureResponse>(path, body, auth.jwt);\n }\n return this.http.post<KmsPaymentSignatureResponse>(path, {\n ...body,\n webAuthnAssertion: auth.webAuthnAssertion,\n });\n }\n\n /**\n * Sign a MicroPaymentChannel voucher (cumulative-amount EIP-712 message)\n * via `POST /kms/SignMicropaymentVoucher`.\n */\n async signMicropaymentVoucher(\n params: KmsSignMicropaymentVoucherRequest,\n auth: KmsPaymentAuth\n ): Promise<KmsPaymentSignatureResponse> {\n this.http.ensureEnabled();\n return this.signWithAuth(\"/kms/SignMicropaymentVoucher\", { ...params }, auth);\n }\n\n /**\n * Sign an EIP-3009 TransferWithAuthorization for a GToken transfer\n * via `POST /kms/SignGTokenAuthorization`. `from` MUST equal the derived address.\n */\n async signGTokenAuthorization(\n params: KmsSignGTokenAuthorizationRequest,\n auth: KmsPaymentAuth\n ): Promise<KmsPaymentSignatureResponse> {\n this.http.ensureEnabled();\n return this.signWithAuth(\"/kms/SignGTokenAuthorization\", { ...params }, auth);\n }\n\n /**\n * Sign an x402 payment authorization via `POST /kms/SignX402Payment`.\n */\n async signX402Payment(\n params: KmsSignX402PaymentRequest,\n auth: KmsPaymentAuth\n ): Promise<KmsPaymentSignatureResponse> {\n this.http.ensureEnabled();\n return this.signWithAuth(\"/kms/SignX402Payment\", { ...params }, auth);\n }\n}\n","import { KmsHttpClient } from \"./kms-http-client\";\n\n// ── Health (GET /health, no auth) ────────────────────────────────\n\n/**\n * Liveness probe response. Returned by `GET /health` without auth — works even\n * when the SDK's KMS feature flag is off.\n */\nexport interface KmsHealthResponse {\n status: string;\n service?: string;\n ta_mode?: string;\n version?: string;\n}\n\n// ── Version (GET /version, no auth) ──────────────────────────────\n\n/**\n * Version / capability descriptor. Returned by `GET /version` without auth.\n * Extra fields are passed through.\n */\nexport interface KmsVersionResponse {\n version?: string;\n ta_mode?: string;\n endpoints?: string[];\n [k: string]: unknown;\n}\n\n// ── Queue Status (GET /QueueStatus) ──────────────────────────────\n\n/**\n * KMS request-queue health, including circuit-breaker state. Useful for\n * back-pressure decisions before submitting signing operations.\n */\nexport interface KmsQueueStatusResponse {\n queue_depth: number;\n estimated_wait_seconds: number;\n circuit_breaker_open: boolean;\n consecutive_failures: number;\n}\n\n// ── Rollback Counter (GET /RollbackCounter, v0.20.0) ─────────────\n\n/**\n * RPMB anti-rollback monotonic counter (diagnostic, v0.20.0). The exact shape\n * is undocumented; the known `counter` field is surfaced and all other fields\n * are passed through.\n */\nexport interface KmsRollbackCounterResponse {\n counter?: number;\n [k: string]: unknown;\n}\n\n// ── Stats (GET /stats, v0.20.0) ──────────────────────────────────\n\n/**\n * Machine-readable runtime statistics (v0.20.0). Pass-through; the response is\n * not strongly typed. Known top-level fields:\n * - `wallets` — wallet / key counts\n * - `tx` — transaction / signing counts\n * - `queue` — queue depth and timing metrics\n * - `warnings` — active operational warnings\n */\nexport interface KmsStatsResponse {\n [k: string]: unknown;\n}\n\n// ── TEE remote-attestation (GET /attestation + .well-known, #37/#12/#87) ──\n\n/** `GET /attestation` evidence bound to a caller nonce (#37). */\nexport interface KmsAttestationResponse {\n schema?: string;\n nonce?: string;\n ta_uuid?: string;\n ta_measurement?: string;\n signature?: string;\n attest_pubkey_exp?: string;\n attest_pubkey_mod?: string;\n sig_alg?: number;\n ree_time_secs?: number;\n trust_root?: string;\n [k: string]: unknown;\n}\n\n/** `GET /.well-known/attestation-measurements.json` — Ed25519-signed manifest (#12). */\nexport interface KmsAttestationManifestResponse {\n body?: Record<string, unknown>;\n publisher_key?: string;\n signature?: string;\n [k: string]: unknown;\n}\n\n/** `GET /.well-known/attestation-measurements-proof.json` — Sigsum proof sidecar (#87). */\nexport interface KmsAttestationProofResponse {\n proof?: Record<string, unknown>;\n [k: string]: unknown;\n}\n\n// ── Admin Purge Key (POST /admin/purge-key, v0.20.0) ─────────────\n\n/**\n * Response of the destructive operator-only purge action (v0.20.0).\n * Pass-through; the response shape is not strongly typed.\n */\nexport interface KmsPurgeKeyResponse {\n [k: string]: unknown;\n}\n\n/**\n * Infrastructure monitoring + operator admin surface for the AAStar TEE KMS\n * (v0.20.0, kms.aastar.io).\n *\n * Wraps a shared {@link KmsHttpClient}. Liveness probes (`health`, `version`)\n * intentionally bypass the `enabled` gate so they work even when the SDK's KMS\n * feature flag is off; every other method calls `ensureEnabled()` first.\n */\nexport class KmsMonitorService {\n constructor(private readonly http: KmsHttpClient) {}\n\n /**\n * Liveness probe (`GET /health`, no auth). Does NOT require the KMS feature\n * flag to be enabled.\n */\n async health(): Promise<KmsHealthResponse> {\n return this.http.get<KmsHealthResponse>(\"/health\");\n }\n\n /**\n * Version / capability descriptor (`GET /version`, no auth). Does NOT require\n * the KMS feature flag to be enabled.\n */\n async version(): Promise<KmsVersionResponse> {\n return this.http.get<KmsVersionResponse>(\"/version\");\n }\n\n /**\n * Request-queue health and circuit-breaker state (`GET /QueueStatus`).\n */\n async queueStatus(): Promise<KmsQueueStatusResponse> {\n this.http.ensureEnabled();\n return this.http.get<KmsQueueStatusResponse>(\"/QueueStatus\");\n }\n\n /**\n * RPMB anti-rollback monotonic counter (`GET /RollbackCounter`, diagnostic,\n * v0.20.0).\n */\n async rollbackCounter(): Promise<KmsRollbackCounterResponse> {\n this.http.ensureEnabled();\n return this.http.get<KmsRollbackCounterResponse>(\"/RollbackCounter\");\n }\n\n /**\n * Machine-readable runtime statistics (`GET /stats`, v0.20.0) — wallets, tx,\n * queue, warnings.\n */\n async stats(): Promise<KmsStatsResponse> {\n this.http.ensureEnabled();\n return this.http.get<KmsStatsResponse>(\"/stats\");\n }\n\n /**\n * TEE remote-attestation evidence bound to a caller nonce (`GET /attestation`,\n * #37). Public (no auth) — pass a fresh random `nonce` (hex, ≤64 bytes) to bind\n * the evidence + defeat replay, then verify the returned signed measurement.\n */\n async getAttestation(nonce: string): Promise<KmsAttestationResponse> {\n return this.http.get<KmsAttestationResponse>(\"/attestation\", { params: { nonce } });\n }\n\n /**\n * Ed25519-signed measurement manifest, version → ta_measurement\n * (`GET /.well-known/attestation-measurements.json`, #12). Public.\n */\n async getAttestationMeasurements(): Promise<KmsAttestationManifestResponse> {\n return this.http.get<KmsAttestationManifestResponse>(\"/.well-known/attestation-measurements.json\");\n }\n\n /**\n * Sigsum transparency proof sidecar for the measurement manifest\n * (`GET /.well-known/attestation-measurements-proof.json`, #87). Public.\n */\n async getAttestationMeasurementsProof(): Promise<KmsAttestationProofResponse> {\n return this.http.get<KmsAttestationProofResponse>(\"/.well-known/attestation-measurements-proof.json\");\n }\n\n /**\n * WARNING — DESTRUCTIVE, IRREVERSIBLE. Force-purges a key from both the TEE\n * and the SQLite store with NO passkey/WebAuthn check (`POST /admin/purge-key`,\n * v0.20.0). Operator-only: authorised solely by the `KMS_ADMIN_TOKEN` operator\n * secret sent as `Authorization: Bearer <adminToken>`. There is no recovery\n * once a key is purged.\n *\n * @internal Operator/break-glass tooling only — not part of the general SDK surface.\n * The endpoint is gated server-side and intentionally omitted from the public KMS\n * docs; do not expose it in application-facing flows.\n */\n async adminPurgeKey(\n params: { key_id: string; reason: string },\n adminToken: string\n ): Promise<KmsPurgeKeyResponse> {\n this.http.ensureEnabled();\n return this.http.postWithBearer<KmsPurgeKeyResponse>(\"/admin/purge-key\", params, adminToken);\n }\n}\n","import {\n IStorageAdapter,\n AccountRecord,\n TransferRecord,\n PaymasterRecord,\n BlsConfigRecord,\n} from \"../interfaces/storage-adapter\";\n\n/**\n * In-memory storage adapter — useful for testing and demos.\n * All data is lost when the process exits.\n */\nexport class MemoryStorage implements IStorageAdapter {\n private accounts: AccountRecord[] = [];\n private transfers: TransferRecord[] = [];\n private paymasters: Map<string, PaymasterRecord[]> = new Map();\n private blsConfig: BlsConfigRecord | null = null;\n\n // ── Accounts ─────────────────────────────────────────────────\n\n async getAccounts(): Promise<AccountRecord[]> {\n return [...this.accounts];\n }\n\n async saveAccount(account: AccountRecord): Promise<void> {\n this.accounts.push({ ...account });\n }\n\n async findAccountByUserId(userId: string): Promise<AccountRecord | null> {\n return this.accounts.find(a => a.userId === userId) ?? null;\n }\n\n async updateAccount(userId: string, updates: Partial<AccountRecord>): Promise<void> {\n const index = this.accounts.findIndex(a => a.userId === userId);\n if (index >= 0) {\n this.accounts[index] = { ...this.accounts[index], ...updates };\n }\n }\n\n // ── Transfers ────────────────────────────────────────────────\n\n async saveTransfer(transfer: TransferRecord): Promise<void> {\n this.transfers.push({ ...transfer });\n }\n\n async findTransfersByUserId(userId: string): Promise<TransferRecord[]> {\n return this.transfers.filter(t => t.userId === userId);\n }\n\n async findTransferById(id: string): Promise<TransferRecord | null> {\n return this.transfers.find(t => t.id === id) ?? null;\n }\n\n async updateTransfer(id: string, updates: Partial<TransferRecord>): Promise<void> {\n const index = this.transfers.findIndex(t => t.id === id);\n if (index >= 0) {\n this.transfers[index] = { ...this.transfers[index], ...updates };\n }\n }\n\n // ── Paymasters ───────────────────────────────────────────────\n\n async getPaymasters(userId: string): Promise<PaymasterRecord[]> {\n return this.paymasters.get(userId) ?? [];\n }\n\n async savePaymaster(userId: string, paymaster: PaymasterRecord): Promise<void> {\n const list = this.paymasters.get(userId) ?? [];\n const existingIndex = list.findIndex(p => p.name === paymaster.name);\n if (existingIndex >= 0) {\n list[existingIndex] = { ...paymaster };\n } else {\n list.push({ ...paymaster });\n }\n this.paymasters.set(userId, list);\n }\n\n async removePaymaster(userId: string, name: string): Promise<boolean> {\n const list = this.paymasters.get(userId) ?? [];\n const filtered = list.filter(p => p.name !== name);\n if (filtered.length < list.length) {\n this.paymasters.set(userId, filtered);\n return true;\n }\n return false;\n }\n\n // ── BLS Config ───────────────────────────────────────────────\n\n async getBlsConfig(): Promise<BlsConfigRecord | null> {\n return this.blsConfig;\n }\n\n async updateSignerNodesCache(nodes: unknown[]): Promise<void> {\n this.blsConfig = {\n ...this.blsConfig,\n signerNodes: {\n nodes: nodes as BlsConfigRecord[\"signerNodes\"] extends { nodes: infer N } ? N : never,\n },\n } as BlsConfigRecord;\n }\n}\n","import { privateKeyToAccount, type PrivateKeyAccount } from \"viem/accounts\";\nimport { ISignerAdapter, PasskeyAssertionContext } from \"../interfaces/signer-adapter\";\n\n/**\n * Local wallet signer — backs all users with a single private key.\n * Suitable for testing, demos, and single-tenant server setups.\n *\n * For multi-tenant production use, implement ISignerAdapter with\n * per-user key management (e.g., KMS, HSM, or encrypted database).\n */\nexport class LocalWalletSigner implements ISignerAdapter {\n private readonly account: PrivateKeyAccount;\n\n constructor(privateKey: string) {\n this.account = privateKeyToAccount(privateKey as `0x${string}`);\n }\n\n async getAddress(_userId: string): Promise<`0x${string}`> {\n return this.account.address;\n }\n\n async signMessage(\n _userId: string,\n message: `0x${string}` | Uint8Array,\n _ctx?: PasskeyAssertionContext\n ): Promise<`0x${string}`> {\n // EIP-191 personal-sign over raw bytes — identical to\n // ethers `wallet.signMessage(bytes)`. `{ raw }` signs the bytes as-is\n // (no UTF-8 reinterpretation of a 0x hex digest).\n return this.account.signMessage({ message: { raw: message } });\n }\n\n async ensureSigner(_userId: string): Promise<{ address: `0x${string}` }> {\n return { address: this.account.address };\n }\n}\n"]}