@aastar/sdk 0.18.0 → 0.20.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.
- package/LICENSE +180 -21
- package/dist/UserClient-YUHCJJJL.js +6 -0
- package/dist/UserClient-YUHCJJJL.js.map +1 -0
- package/dist/account.d.ts +1 -0
- package/dist/account.js +6 -0
- package/dist/account.js.map +1 -0
- package/dist/admin.d.ts +1 -0
- package/dist/admin.js +6 -0
- package/dist/admin.js.map +1 -0
- package/dist/airaccount.d.ts +2 -0
- package/dist/airaccount.js +4501 -0
- package/dist/airaccount.js.map +1 -0
- package/dist/channel.d.ts +1 -0
- package/dist/channel.js +6 -0
- package/dist/channel.js.map +1 -0
- package/dist/chunk-4DVUM4MC.js +106 -0
- package/dist/chunk-4DVUM4MC.js.map +1 -0
- package/dist/chunk-4KRQXOTI.js +4421 -0
- package/dist/chunk-4KRQXOTI.js.map +1 -0
- package/dist/chunk-DI3E6PMI.js +426 -0
- package/dist/chunk-DI3E6PMI.js.map +1 -0
- package/dist/chunk-DSZ372PH.js +333 -0
- package/dist/chunk-DSZ372PH.js.map +1 -0
- package/dist/chunk-HVAB4TTT.js +116 -0
- package/dist/chunk-HVAB4TTT.js.map +1 -0
- package/dist/chunk-MPOMWT2J.js +1140 -0
- package/dist/chunk-MPOMWT2J.js.map +1 -0
- package/dist/chunk-NZGXB2C5.js +115 -0
- package/dist/chunk-NZGXB2C5.js.map +1 -0
- package/dist/chunk-O3Y7II3B.js +578 -0
- package/dist/chunk-O3Y7II3B.js.map +1 -0
- package/dist/chunk-OSPRJZ5T.js +113 -0
- package/dist/chunk-OSPRJZ5T.js.map +1 -0
- package/dist/chunk-PCLPYRTX.js +229 -0
- package/dist/chunk-PCLPYRTX.js.map +1 -0
- package/dist/chunk-PZ5AY32C.js +9 -0
- package/dist/chunk-PZ5AY32C.js.map +1 -0
- package/dist/chunk-XFI3AK32.js +416 -0
- package/dist/chunk-XFI3AK32.js.map +1 -0
- package/dist/chunk-YHM77LIP.js +432 -0
- package/dist/chunk-YHM77LIP.js.map +1 -0
- package/dist/chunk-ZSSNU3UF.js +42091 -0
- package/dist/chunk-ZSSNU3UF.js.map +1 -0
- package/dist/contract-addresses-JE3X6DFY.js +4 -0
- package/dist/contract-addresses-JE3X6DFY.js.map +1 -0
- package/dist/core.d.ts +13 -0
- package/dist/core.js +5 -0
- package/dist/core.js.map +1 -0
- package/dist/dapp.d.ts +1 -0
- package/dist/dapp.js +283 -0
- package/dist/dapp.js.map +1 -0
- package/dist/dist-GHTBO7CD.js +6 -0
- package/dist/dist-GHTBO7CD.js.map +1 -0
- package/dist/enduser.d.ts +1 -0
- package/dist/enduser.js +7 -0
- package/dist/enduser.js.map +1 -0
- package/dist/identity.d.ts +1 -0
- package/dist/identity.js +6 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +601 -13
- package/dist/index.js +1639 -28
- package/dist/index.js.map +1 -0
- package/dist/index.node-55LOPHNQ.js +5 -0
- package/dist/index.node-55LOPHNQ.js.map +1 -0
- package/dist/lib-VRTYVDUO.js +1861 -0
- package/dist/lib-VRTYVDUO.js.map +1 -0
- package/dist/operator.d.ts +1 -0
- package/dist/operator.js +6 -0
- package/dist/operator.js.map +1 -0
- package/dist/paymaster.d.ts +1 -0
- package/dist/paymaster.js +6 -0
- package/dist/paymaster.js.map +1 -0
- package/dist/tokens.d.ts +1 -0
- package/dist/tokens.js +6 -0
- package/dist/tokens.js.map +1 -0
- package/dist/x402.d.ts +1 -0
- package/dist/x402.js +6 -0
- package/dist/x402.js.map +1 -0
- package/package.json +87 -18
- package/dist/clients/ExperimentClient.d.ts +0 -34
- package/dist/clients/ExperimentClient.js +0 -58
- package/dist/clients/admin.d.ts +0 -11
- package/dist/clients/admin.js +0 -20
- package/dist/clients/community.d.ts +0 -40
- package/dist/clients/community.js +0 -300
- package/dist/clients/endUser.d.ts +0 -77
- package/dist/clients/endUser.js +0 -298
- package/dist/clients/operator.d.ts +0 -66
- package/dist/clients/operator.js +0 -209
- package/dist/errors/decoder.d.ts +0 -6
- package/dist/errors/decoder.js +0 -44
- package/dist/utils/errorHandler.d.ts +0 -40
- package/dist/utils/errorHandler.js +0 -114
- package/dist/utils/funding.d.ts +0 -115
- package/dist/utils/funding.js +0 -188
- package/dist/utils/keys.d.ts +0 -61
- package/dist/utils/keys.js +0 -130
- package/dist/utils/roleData.d.ts +0 -66
- package/dist/utils/roleData.js +0 -128
- package/dist/utils/testScenarios.d.ts +0 -33
- package/dist/utils/testScenarios.js +0 -85
- package/dist/utils/userOp.d.ts +0 -89
- package/dist/utils/userOp.js +0 -231
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/nist.ts","../../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/services/account-manager.ts","../../airaccount/src/server/utils/execute-user-op.ts","../../airaccount/src/server/services/paymaster-manager.ts","../../airaccount/src/core/erc4337/utils.ts","../../airaccount/src/server/services/transfer-manager.ts","../../airaccount/src/core/bls/bls.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/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/core/tier/types.ts","../../airaccount/src/core/tier/tier-router.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","../../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","ethers","ERC4337Utils","BLSManager","bls","axios"],"mappings":";;;;;;;;AAqBA,IAAM,6BAAuD,CAAA,OAAO;AAClE,EAAA,CAAA,EAAG,OAAO,oEAAoE,CAAA;AAC9E,EAAA,CAAA,EAAG,OAAO,oEAAoE,CAAA;AAC9E,EAAA,CAAA,EAAG,OAAO,CAAC,CAAA;AACX,EAAA,CAAA,EAAG,OAAO,oEAAoE,CAAA;AAC9E,EAAA,CAAA,EAAG,OAAO,oEAAoE,CAAA;AAC9E,EAAA,EAAA,EAAI,OAAO,oEAAoE,CAAA;AAC/E,EAAA,EAAA,EAAI,OAAO,oEAAoE;AAC9E,CAAA,CAAA,GAAA;AA4DH,IAAM,UAAA,+BAAyC,UAAU,CAAA;AAgBlD,IAAM,IAAA,mBAA8B,KAAA,CAAM,UAAA,EAAY,MAAM,CAAA;;;ACzG5D,IAAK,iBAAA,qBAAAA,kBAAAA,KAAL;AACLA,EAAAA,kBAAAA,CAAA,MAAA,CAAA,GAAO,KAAA;AACPA,EAAAA,kBAAAA,CAAA,MAAA,CAAA,GAAO,KAAA;AACPA,EAAAA,kBAAAA,CAAA,MAAA,CAAA,GAAO,KAAA;AAHG,EAAA,OAAAA,kBAAAA;AAAA,CAAA,EAAA,iBAAA,IAAA,EAAA;AAcL,IAAM,oBAAA,GAAuB;AAClC,EAAA;AAAC,IAAA;;KAAyB;IACxB,OAAA,EAAS,4CAAA;IACT,OAAA,EAAS,4CAAA;IACT,QAAA,EAAU;AAAA,GAAA;AAEZ,EAAA;AAAC,IAAA;;KAAyB;IACxB,O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AEA,EAAA,MAAM,aAAa,OAAA,EAAsE;AACvF,IAAA,OAAO,EAAE,MAAA,EAAQ,IAAA,CAAK,QAAQ,OAAA,EAAS,IAAA,CAAK,OAAO,OAAA,EAAA;AACrD,EAAA;AACF","file":"airaccount.js","sourcesContent":["/**\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","export 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: v0.17.2-beta.4 (bundler-compat — algId whitelist on account + executeUserOp) ─────\n // beta.4 upgrades the AirAccount account contracts; it REUSES the beta.3 router /\n // sessionKey / forceExit / BLS (per the beta.4 migration notes).\n factory: \"0x3a9127a5f0b4ca734d54629d0c3ad9f52739c071\", // beta.4\n factoryM7: \"0x3a9127a5f0b4ca734d54629d0c3ad9f52739c071\", // beta.4\n accountImpl: \"0x0321Fa7261Ad5945e4B3f0c73aFD7D9392E39796\", // beta.4\n validatorRouter: \"0x3c2b06f50300912794f29de031b33dd37bb8d6c6\", // beta.3 (reused; M3 timelock)\n blsAlgorithm: \"0xB82127182A855B82eED05e47536FcE568b626457\",\n blsAggregator: \"0xBAc3f24946d0eb15189E1c01e38182e5B078Bbc1\",\n superPaymaster: \"0xFb090E82bD041C6e9787eDEbE1D3BE55b3c7266a\",\n // beta.3 ERC-7579 modules (reused by beta.4)\n sessionKeyValidator: \"0x655ca2e9a2d1178f7fbcea1856560d1e0c657ebf\",\n forceExitModule: \"0xdb396ca2dc279f9bcb95fa3d8275f77c9f0c8702\",\n airAccountDelegate: \"0x4bda4849b80cc444fb2da65beec0724005c6675c\", // beta.4\n airAccountExtension: \"0x20FB2A65a52Fc6507FdD51260f055017a2BA2860\", // beta.4\n agentRegistry: \"0xe1320c35485b4d7817866a8d0d8f77dd58202253\", // beta.4\n calldataParserRegistry: \"0x076EE45d2a97F70FCb2e45809DC5f9b72BB4883F\",\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 \"function getConfigDescription() external view returns (tuple(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 \"event RecoveryProposed(address indexed newOwner, address indexed proposedBy)\",\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// InitConfig: (address[3] guardians, uint256 dailyLimit, uint8[] approvedAlgIds, uint256 minDailyLimit, address[] initialTokens, (uint256 tier1Limit, uint256 tier2Limit, uint256 dailyLimit)[] initialTokenConfigs)\nexport const AIRACCOUNT_FACTORY_ABI = [\n // Full config creation\n \"function createAccount(address owner, uint256 salt, (address[3] guardians, uint256 dailyLimit, uint8[] approvedAlgIds, uint256 minDailyLimit, address[] initialTokens, (uint256 tier1Limit, uint256 tier2Limit, uint256 dailyLimit)[] initialTokenConfigs) config) external returns (address)\",\n \"function getAddress(address owner, uint256 salt, (address[3] guardians, uint256 dailyLimit, uint8[] approvedAlgIds, uint256 minDailyLimit, address[] initialTokens, (uint256 tier1Limit, uint256 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, uint256 dailyLimit, uint8[] approvedAlgIds, uint256 minDailyLimit, address[] initialTokens, (uint256 tier1Limit, uint256 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 { ethers } from \"ethers\";\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 * Unified Ethereum provider — replaces NestJS EthereumService.\n * Manages RPC + Bundler providers and contract interactions.\n */\nexport class EthereumProvider {\n private readonly provider: ethers.JsonRpcProvider;\n private readonly bundlerProvider: ethers.JsonRpcProvider;\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 = new ethers.JsonRpcProvider(config.rpcUrl);\n this.bundlerProvider = new ethers.JsonRpcProvider(config.bundlerRpcUrl);\n }\n\n getProvider(): ethers.JsonRpcProvider {\n return this.provider;\n }\n\n getBundlerProvider(): ethers.JsonRpcProvider {\n return this.bundlerProvider;\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 getFactoryContract(version: EntryPointVersion = EntryPointVersion.V0_6): ethers.Contract {\n const address = this.getFactoryAddress(version);\n const abi = version === EntryPointVersion.V0_6 ? FACTORY_ABI_V6 : AIRACCOUNT_FACTORY_ABI;\n return new ethers.Contract(address, abi, this.provider);\n }\n\n getEntryPointContract(version: EntryPointVersion = EntryPointVersion.V0_6): ethers.Contract {\n const address = this.getEntryPointAddress(version);\n const abi = version === EntryPointVersion.V0_6 ? ENTRYPOINT_ABI_V6 : ENTRYPOINT_ABI_V7_V8;\n return new ethers.Contract(address, abi, this.provider);\n }\n\n getValidatorContract(version: EntryPointVersion = EntryPointVersion.V0_6): ethers.Contract {\n const address = this.getValidatorAddress(version);\n return new ethers.Contract(address, VALIDATOR_ABI, this.provider);\n }\n\n getAccountContract(address: string): ethers.Contract {\n return new ethers.Contract(address, AIRACCOUNT_ABI, this.provider);\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): ethers.Contract {\n return new ethers.Contract(address, AGENT_SESSION_KEY_VALIDATOR_ABI, this.provider);\n }\n\n getTierGuardHookContract(address: string = AIRACCOUNT_ADDRESSES.sepolia.tierGuardHookM7r4): ethers.Contract {\n return new ethers.Contract(address, TIER_GUARD_HOOK_ABI, this.provider);\n }\n\n getCompositeValidatorContract(address: string = AIRACCOUNT_ADDRESSES.sepolia.compositeValidatorM7r4): ethers.Contract {\n return new ethers.Contract(address, AIR_ACCOUNT_COMPOSITE_VALIDATOR_ABI, this.provider);\n }\n\n getForceExitModuleContract(address: string): ethers.Contract {\n return new ethers.Contract(address, FORCE_EXIT_MODULE_ABI, this.provider);\n }\n\n // ── On-chain queries ────────────────────────────────────────────\n\n async getBalance(address: string): Promise<string> {\n const balance = await this.provider.getBalance(address);\n return ethers.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.getNonce(accountAddress, key);\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\n if (version === EntryPointVersion.V0_6) {\n const op = userOp as UserOperation;\n const userOpArray = [\n op.sender,\n op.nonce,\n op.initCode || \"0x\",\n op.callData,\n op.callGasLimit,\n op.verificationGasLimit,\n op.preVerificationGas,\n op.maxFeePerGas,\n op.maxPriorityFeePerGas,\n op.paymasterAndData || \"0x\",\n \"0x\", // Always use empty signature for hash calculation\n ];\n return await entryPoint.getUserOpHash(userOpArray);\n } else {\n const packedOp = userOp as PackedUserOperation;\n const packedOpArray = [\n packedOp.sender,\n packedOp.nonce,\n packedOp.initCode || \"0x\",\n packedOp.callData,\n packedOp.accountGasLimits,\n packedOp.preVerificationGas,\n packedOp.gasFees,\n packedOp.paymasterAndData || \"0x\",\n \"0x\",\n ];\n return await entryPoint.getUserOpHash(packedOpArray);\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.bundlerProvider.send(\"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.bundlerProvider.send(\"eth_sendUserOperation\", [\n userOp,\n this.getEntryPointAddress(version),\n ]);\n }\n\n async getUserOperationReceipt(userOpHash: string): Promise<unknown> {\n return await this.bundlerProvider.send(\"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.bundlerProvider.send(\"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.getFeeData();\n const baseFee = feeData.maxFeePerGas || ethers.parseUnits(\"20\", \"gwei\");\n const priorityFee = feeData.maxPriorityFeePerGas || ethers.parseUnits(\"2\", \"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\" + ethers.parseUnits(\"3\", \"gwei\").toString(16),\n maxPriorityFeePerGas: \"0x\" + ethers.parseUnits(\"1\", \"gwei\").toString(16),\n };\n }\n }\n }\n}\n","import { ethers } from \"ethers\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\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\";\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 ): Promise<AccountRecord> {\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) as ethers.BaseContract).target 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 [ethers.ZeroAddress, ethers.ZeroAddress, ethers.ZeroAddress], // guardians (address[3])\n dailyLimitValue, // dailyLimit (0 = no guard)\n [], // approvedAlgIds\n 0n, // minDailyLimit\n [], // initialTokens\n [], // initialTokenConfigs\n ];\n const accountAddress = await factory.getFunction(\"getAddress\")(signerAddress, salt, minimalConfig);\n\n // Check deployment status\n let deployed = false;\n try {\n const code = await this.ethereum.getProvider().getCode(accountAddress);\n deployed = 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.target 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: ethers.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 return ethers.keccak256(\n ethers.solidityPacked(\n [\"string\", \"uint256\", \"address\", \"address\", \"uint256\", \"uint256\"],\n [\"ACCEPT_GUARDIAN\", chainId, factoryAddress, owner, 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 const iface = new ethers.Interface(AIRACCOUNT_ABI);\n return iface.encodeFunctionData(\"modifyTierLimitsWithGuardians\", [\n tier1,\n tier2,\n deadline,\n guardianSigs,\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.target as string) ?? this.ethereum.getFactoryAddress(version);\n\n const accountAddress = await factory.getFunction(\"getAddressWithDefaults\")(\n signerAddress,\n 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(accountAddress);\n deployed = 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","import { ethers } from \"ethers\";\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 = ethers\n .id(\"executeUserOp((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes),bytes32)\")\n .slice(0, 10);\n\n/** 4-byte selector of `execute(address,uint256,bytes)`. */\nexport const EXECUTE_SELECTOR = ethers.id(\"execute(address,uint256,bytes)\").slice(0, 10);\n\n/** 4-byte selector of `executeBatch(address[],uint256[],bytes[])`. */\nexport const EXECUTE_BATCH_SELECTOR = ethers\n .id(\"executeBatch(address[],uint256[],bytes[])\")\n .slice(0, 10);\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 ethers.concat([EXECUTE_USER_OP_SELECTOR, innerCallData]);\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 { ethers } from \"ethers\";\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 = [\n \"function token() view returns (address)\",\n \"function cachedPriceTimestamp() view returns (uint256)\",\n \"function priceStalenessThreshold() view returns (uint256)\",\n \"function updatePrice() external\",\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 = new ethers.Contract(paymasterAddress, PAYMASTER_PRICE_ABI, provider);\n const [timestamp, threshold] = await Promise.all([\n contract.cachedPriceTimestamp() as Promise<bigint>,\n contract.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 signer - An ethers Signer that will send the transaction (must have gas).\n */\n async updatePrice(paymasterAddress: string, signer: ethers.Signer): Promise<string> {\n const contract = new ethers.Contract(paymasterAddress, PAYMASTER_PRICE_ABI, signer);\n const tx = await contract.updatePrice({ gasLimit: 300000 });\n await tx.wait();\n this.logger.log(`Paymaster ${paymasterAddress} price updated, tx: ${tx.hash}`);\n return tx.hash as string;\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 = new ethers.Contract(\n formattedAddress,\n [\n \"function owner() view returns (address)\",\n \"function operators(address) view returns (bool,uint256,address,uint256)\",\n ],\n provider\n );\n const owner = await spContract.owner();\n const opInfo = await spContract.operators(owner);\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 ethers.concat([\n formattedAddress,\n ethers.zeroPadValue(ethers.toBeHex(verGas), 16),\n ethers.zeroPadValue(ethers.toBeHex(postGas), 16),\n operatorAddress,\n ethers.zeroPadValue(ethers.toBeHex(maxRate), 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 = new ethers.Contract(\n formattedAddress,\n PAYMASTER_PRICE_ABI,\n provider\n );\n tokenAddress = await pmContract.token();\n if (tokenAddress === ethers.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: string[] = [\n formattedAddress,\n ethers.zeroPadValue(ethers.toBeHex(paymasterVerificationGasLimit), 16),\n ethers.zeroPadValue(ethers.toBeHex(paymasterPostOpGasLimit), 16),\n ];\n if (tokenAddress) {\n parts.push(tokenAddress);\n }\n return ethers.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 ethers.concat([\n result.result.paymaster,\n ethers.zeroPadValue(\n ethers.toBeHex(BigInt(result.result.paymasterVerificationGasLimit || \"0x30000\")),\n 16\n ),\n ethers.zeroPadValue(\n ethers.toBeHex(BigInt(result.result.paymasterPostOpGasLimit || \"0x30000\")),\n 16\n ),\n result.result.paymasterData || \"0x\",\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 type { PackedUserOperation } from \"../types\";\n\nexport class ERC4337Utils {\n static packAccountGasLimits(\n verificationGasLimit: bigint | string,\n callGasLimit: bigint | string\n ): string {\n const vgl = BigInt(verificationGasLimit);\n const cgl = BigInt(callGasLimit);\n const packed = (vgl << 128n) | cgl;\n return \"0x\" + packed.toString(16).padStart(64, \"0\");\n }\n\n static unpackAccountGasLimits(accountGasLimits: string): {\n verificationGasLimit: bigint;\n callGasLimit: bigint;\n } {\n const packed = BigInt(accountGasLimits);\n return {\n verificationGasLimit: packed >> 128n,\n callGasLimit: packed & ((1n << 128n) - 1n),\n };\n }\n\n static packGasFees(maxPriorityFeePerGas: bigint | string, maxFeePerGas: bigint | string): string {\n const priority = BigInt(maxPriorityFeePerGas);\n const max = BigInt(maxFeePerGas);\n const packed = (priority << 128n) | max;\n return \"0x\" + packed.toString(16).padStart(64, \"0\");\n }\n\n static unpackGasFees(gasFees: string): {\n maxPriorityFeePerGas: bigint;\n maxFeePerGas: bigint;\n } {\n const packed = BigInt(gasFees);\n return {\n maxPriorityFeePerGas: packed >> 128n,\n maxFeePerGas: packed & ((1n << 128n) - 1n),\n };\n }\n\n static packUserOperation(userOp: any): PackedUserOperation {\n return {\n sender: userOp.sender,\n nonce: userOp.nonce,\n initCode: userOp.initCode || \"0x\",\n callData: userOp.callData,\n accountGasLimits: ERC4337Utils.packAccountGasLimits(\n userOp.verificationGasLimit,\n userOp.callGasLimit\n ),\n preVerificationGas: userOp.preVerificationGas,\n gasFees: ERC4337Utils.packGasFees(userOp.maxPriorityFeePerGas, userOp.maxFeePerGas),\n paymasterAndData: userOp.paymasterAndData || \"0x\",\n signature: userOp.signature || \"0x\",\n };\n }\n\n static unpackUserOperation(packedOp: PackedUserOperation): any {\n const gasLimits = ERC4337Utils.unpackAccountGasLimits(packedOp.accountGasLimits);\n const gasFees = ERC4337Utils.unpackGasFees(packedOp.gasFees);\n\n return {\n sender: packedOp.sender,\n nonce: packedOp.nonce,\n initCode: packedOp.initCode,\n callData: packedOp.callData,\n callGasLimit: \"0x\" + gasLimits.callGasLimit.toString(16),\n verificationGasLimit: \"0x\" + gasLimits.verificationGasLimit.toString(16),\n preVerificationGas: packedOp.preVerificationGas,\n maxFeePerGas: \"0x\" + gasFees.maxFeePerGas.toString(16),\n maxPriorityFeePerGas: \"0x\" + gasFees.maxPriorityFeePerGas.toString(16),\n paymasterAndData: packedOp.paymasterAndData,\n signature: packedOp.signature,\n };\n }\n}\n","import { ethers } from \"ethers\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport { AccountManager } from \"./account-manager\";\nimport { BLSSignatureService } 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 { EntryPointVersion, ALG_ID } from \"../constants/entrypoint\";\nimport { ILogger, ConsoleLogger } from \"../interfaces/logger\";\nimport { PaymasterPriceStalenessError } from \"./paymaster-manager\";\nimport { UserOperation, PackedUserOperation } from \"../../core/types\";\nimport { ERC4337Utils } from \"../../core/erc4337\";\nimport { TierLevel } from \"../../core/tier\";\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: ethers.Provider,\n accountAddress: string\n): Promise<{ useECDSA: boolean; isCompositeValidator: boolean }> {\n try {\n const accountCode = await provider.getCode(accountAddress);\n if (accountCode === \"0x\") {\n // AirAccount factory invariant: all counterfactual addresses are compositeValidator deployments.\n return { useECDSA: true, isCompositeValidator: true };\n }\n const acc = new ethers.Contract(\n accountAddress,\n [\"function validator() view returns (address)\"],\n provider\n );\n const v = (await acc.validator()) as string;\n // validator() exists → confirmed compositeValidator account.\n return { useECDSA: v === ethers.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 ethers.Signer instance. Required for AirAccount Tier 3. */\n guardianSigner?: ethers.Signer;\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(account.address);\n const needsDeployment = 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 signer = await this.signer.getSigner(userId, assertionCtx);\n const ecdsaSig = await signer.signMessage(ethers.getBytes(userOpHash));\n if (isCompositeValidator) {\n this.logger.log(\"ECDSA path for compositeValidator: prepending algId prefix\");\n userOp.signature = ethers.concat([ethers.toBeHex(ALG_ID.ECDSA, 1), ecdsaSig]);\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 : ethers.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 = ethers.concat([ethers.toBeHex(ALG_ID.BLS, 1), packedBls]);\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(from);\n if (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 const validatorGasEstimate = await validatorContract.getGasEstimate(3);\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 accountContract = this.ethereum.getAccountContract(sender);\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(sender);\n const needsDeployment = 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 = await factory.getAddress();\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.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 // ethers.js v6: 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 = factory.interface.encodeFunctionData(\"createAccountWithDefaults\", [\n account.signerAddress,\n 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 [ethers.ZeroAddress, ethers.ZeroAddress, ethers.ZeroAddress], // guardians (address[3])\n storedDailyLimit,\n [], // approvedAlgIds\n 0n, // minDailyLimit\n [], // initialTokens\n [], // initialTokenConfigs\n ];\n deployCalldata = factory.interface.encodeFunctionData(\"createAccount\", [\n account.signerAddress,\n account.salt,\n minimalConfig,\n ]);\n }\n } else {\n deployCalldata = factory.interface.encodeFunctionData(\n \"createAccountWithAAStarValidator\",\n [\n account.signerAddress,\n account.signerAddress,\n account.validatorAddress,\n true,\n account.salt,\n ]\n );\n }\n\n initCode = ethers.concat([factoryAddress, deployCalldata]);\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 = accountContract.interface.encodeFunctionData(\"execute\", [\n tokenAddress,\n 0,\n transferCalldata,\n ]);\n } else {\n callData = accountContract.interface.encodeFunctionData(\"execute\", [\n to,\n ethers.parseEther(amount),\n data,\n ]);\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 axios from \"axios\";\nimport { ethers } from \"ethers\";\nimport { bls12_381 as bls } from \"@noble/curves/bls12-381.js\";\nimport {\n BLSConfig,\n BLSNode,\n BLSSignatureData,\n CumulativeT2SignatureData,\n CumulativeT3SignatureData,\n} from \"./types\";\n\nexport class BLSManager {\n private config: BLSConfig;\n\n constructor(config: BLSConfig) {\n this.config = config;\n }\n\n /**\n * Discover available BLS nodes from seed nodes (Gossip network)\n */\n async getAvailableNodes(): Promise<BLSNode[]> {\n const { seedNodes, discoveryTimeout = 5000 } = this.config;\n\n for (const seedEndpoint of seedNodes) {\n try {\n // Try to get peers from gossip endpoint\n const response = await axios.get(`${seedEndpoint}/gossip/peers`, {\n timeout: discoveryTimeout,\n });\n\n const peers = response.data.peers || [];\n\n // Filter active nodes with proper structure\n const activeNodes: BLSNode[] = peers\n .filter((p: any) => p.status === \"active\" && p.apiEndpoint && p.publicKey)\n .map((p: any, index: number) => ({\n index: index + 1, // 1-based index likely expected by contract if using bitmap\n nodeId: p.nodeId,\n nodeName: p.nodeName,\n apiEndpoint: p.apiEndpoint,\n status: \"active\",\n publicKey: p.publicKey,\n }));\n\n if (activeNodes.length > 0) {\n return activeNodes;\n }\n } catch {\n // Try next seed node\n continue;\n }\n }\n\n return [];\n }\n\n /**\n * Helper to pack the full signature for ERC-4337 UserOp\n * Format: [nodeIdsLength][nodeIds...][blsSignature][messagePoint][aaSignature][messagePointSignature]\n */\n packSignature(data: BLSSignatureData): string {\n if (!data.nodeIds || !data.aaSignature || !data.messagePointSignature) {\n throw new Error(\"Missing required signature components\");\n }\n\n const nodeIdsLength = ethers.solidityPacked([\"uint256\"], [data.nodeIds.length]);\n const nodeIdsBytes = ethers.solidityPacked(\n Array(data.nodeIds.length).fill(\"bytes32\"),\n data.nodeIds\n );\n\n return ethers.solidityPacked(\n [\"bytes\", \"bytes\", \"bytes\", \"bytes\", \"bytes\", \"bytes\"],\n [\n nodeIdsLength,\n nodeIdsBytes,\n data.signature,\n data.messagePoint,\n data.aaSignature,\n data.messagePointSignature,\n ]\n );\n }\n\n /**\n * Calculate the MessagePoint G2 point for a given message (UserOpHash)\n */\n async generateMessagePoint(message: string | Uint8Array): Promise<string> {\n const messageBytes = typeof message === \"string\" ? ethers.getBytes(message) : message;\n const DST = \"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_\";\n\n const messagePointBLS = await bls.G2.hashToCurve(messageBytes, { DST });\n const messageG2EIP = this.encodeG2Point(messagePointBLS);\n\n return \"0x\" + Buffer.from(messageG2EIP).toString(\"hex\");\n }\n\n /**\n * Encode G2 Point to bytes for EIP-2537 format\n */\n private encodeG2Point(point: any): Uint8Array {\n const result = new Uint8Array(256);\n const affine = point.toAffine();\n\n const x0Bytes = this.hexToBytes(affine.x.c0.toString(16).padStart(96, \"0\"));\n const x1Bytes = this.hexToBytes(affine.x.c1.toString(16).padStart(96, \"0\"));\n const y0Bytes = this.hexToBytes(affine.y.c0.toString(16).padStart(96, \"0\"));\n const y1Bytes = this.hexToBytes(affine.y.c1.toString(16).padStart(96, \"0\"));\n\n result.set(x0Bytes, 16);\n result.set(x1Bytes, 80);\n result.set(y0Bytes, 144);\n result.set(y1Bytes, 208);\n return result;\n }\n\n private hexToBytes(hex: string): Uint8Array {\n if (hex.startsWith(\"0x\")) hex = hex.slice(2);\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.substr(i, 2), 16);\n }\n return bytes;\n }\n\n /**\n * Pack cumulative Tier 2 signature (algId 0x04): P256 + BLS.\n *\n * Format:\n * [algId=0x04 (1)] [P256 r (32)] [P256 s (32)]\n * [nodeIdsLength (32)] [nodeIds (N×32)]\n * [blsAggregateSig (256)] [messagePoint (256)]\n * [messagePointECDSA (65)]\n */\n packCumulativeT2Signature(data: CumulativeT2SignatureData): string {\n const nodeIdsLength = ethers.solidityPacked([\"uint256\"], [data.nodeIds.length]);\n const nodeIdsBytes = ethers.solidityPacked(\n Array(data.nodeIds.length).fill(\"bytes32\"),\n data.nodeIds\n );\n\n return ethers.solidityPacked(\n [\"bytes1\", \"bytes\", \"bytes\", \"bytes\", \"bytes\", \"bytes\", \"bytes\"],\n [\n \"0x04\",\n data.p256Signature,\n nodeIdsLength,\n nodeIdsBytes,\n data.blsSignature,\n data.messagePoint,\n data.messagePointSignature,\n ]\n );\n }\n\n /**\n * Pack cumulative Tier 3 signature (algId 0x05): P256 + BLS + Guardian.\n *\n * Format:\n * [algId=0x05 (1)] [P256 r (32)] [P256 s (32)]\n * [nodeIdsLength (32)] [nodeIds (N×32)]\n * [blsAggregateSig (256)] [messagePoint (256)]\n * [messagePointECDSA (65)] [guardianECDSA (65)]\n */\n packCumulativeT3Signature(data: CumulativeT3SignatureData): string {\n const nodeIdsLength = ethers.solidityPacked([\"uint256\"], [data.nodeIds.length]);\n const nodeIdsBytes = ethers.solidityPacked(\n Array(data.nodeIds.length).fill(\"bytes32\"),\n data.nodeIds\n );\n\n return ethers.solidityPacked(\n [\"bytes1\", \"bytes\", \"bytes\", \"bytes\", \"bytes\", \"bytes\", \"bytes\", \"bytes\"],\n [\n \"0x05\",\n data.p256Signature,\n nodeIdsLength,\n nodeIdsBytes,\n data.blsSignature,\n data.messagePoint,\n data.messagePointSignature,\n data.guardianSignature,\n ]\n );\n }\n\n /**\n * Request signature from a single node\n */\n async requestNodeSignature(\n node: BLSNode,\n message: string\n ): Promise<{ signature: string; publicKey: string }> {\n const response = await axios.post(`${node.apiEndpoint}/signature/sign`, {\n message,\n });\n\n const signatureEIP = response.data.signature;\n // Prefer compact if available, logic copied from legacy service\n const signature = response.data.signatureCompact || signatureEIP;\n\n return {\n signature: signature.startsWith(\"0x\") ? signature : `0x${signature}`,\n publicKey: response.data.publicKey,\n };\n }\n\n /**\n * Request aggregation from a node\n */\n async aggregateSignatures(node: BLSNode, signatures: string[]): Promise<string> {\n const response = await axios.post(`${node.apiEndpoint}/signature/aggregate`, {\n signatures,\n });\n\n const sig = response.data.signature;\n return sig.startsWith(\"0x\") ? sig : `0x${sig}`;\n }\n}\n","import { ethers } from \"ethers\";\nimport axios from \"axios\";\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 wallet = await this.signer.getSigner(userId, ctx);\n const walletAddress = await wallet.getAddress();\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 wallet.signMessage(ethers.getBytes(userOpHash));\n const messagePointHash = ethers.keccak256(messagePoint);\n const messagePointSignature = await wallet.signMessage(ethers.getBytes(messagePointHash));\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 ethers.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?: ethers.Signer;\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 const wallet = await this.signer.getSigner(userId, ctx);\n return wallet.signMessage(ethers.getBytes(userOpHash));\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(ethers.getBytes(userOpHash));\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","import { ethers } from \"ethers\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport { ERC20_ABI } from \"../constants/entrypoint\";\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 provider = this.ethereum.getProvider();\n const contract = new ethers.Contract(tokenAddress, ERC20_ABI, provider);\n\n const [name, symbol, decimals] = await Promise.all([\n contract.name(),\n contract.symbol(),\n contract.decimals(),\n ]);\n\n return {\n address: tokenAddress.toLowerCase(),\n name,\n symbol,\n decimals: Number(decimals),\n };\n }\n\n async getTokenBalance(tokenAddress: string, walletAddress: string): Promise<string> {\n const provider = this.ethereum.getProvider();\n const contract = new ethers.Contract(tokenAddress, ERC20_ABI, provider);\n\n try {\n const balance = await contract.balanceOf(walletAddress);\n return balance.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 = ethers.formatUnits(rawBalance, tokenInfo.decimals);\n return { token: tokenInfo, balance: rawBalance, formattedBalance };\n }\n\n generateTransferCalldata(to: string, amount: string, decimals: number): string {\n const contract = new ethers.Contract(ethers.ZeroAddress, ERC20_ABI);\n const parsedAmount = ethers.parseUnits(amount, decimals);\n return contract.interface.encodeFunctionData(\"transfer\", [to, parsedAmount]);\n }\n\n async validateToken(tokenAddress: string): Promise<{\n isValid: boolean;\n token?: TokenInfo;\n error?: string;\n }> {\n try {\n const provider = this.ethereum.getProvider();\n const contract = new ethers.Contract(tokenAddress, ERC20_ABI, provider);\n\n const [name, symbol, decimals] = (await Promise.race([\n Promise.all([contract.name(), contract.symbol(), contract.decimals()]),\n new Promise((_, reject) => setTimeout(() => reject(new Error(\"Timeout\")), 10000)),\n ])) as [string, string, bigint];\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 { ethers } from \"ethers\";\nimport { ISignerAdapter } 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<string> {\n return this.signer.getAddress(userId);\n }\n\n async getSigner(userId: string): Promise<ethers.Signer> {\n return this.signer.getSigner(userId);\n }\n\n async ensureSigner(userId: string): Promise<{ signer: ethers.Signer; address: 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 { YAAAServerClient, MemoryStorage, LocalWalletSigner } from '@aastar/airaccount/server';\n *\n * const client = new YAAAServerClient({\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 YAAAServerClient {\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","import { ethers } from \"ethers\";\nimport { MODULE_TYPE, AIRACCOUNT_ABI, AIRACCOUNT_ADDRESSES } from \"../constants/entrypoint\";\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(ethers.getBytes(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 = ethers.keccak256(moduleInitData);\n const raw = ethers.keccak256(\n ethers.solidityPacked(\n [\"string\", \"uint256\", \"address\", \"uint256\", \"address\", \"bytes32\"],\n [\"INSTALL_MODULE\", chainId, account, moduleTypeId, module, moduleInitDataHash],\n ),\n );\n return ethers.hashMessage(ethers.getBytes(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 = ethers.keccak256(\n ethers.solidityPacked(\n [\"string\", \"uint256\", \"address\", \"uint256\", \"address\"],\n [\"UNINSTALL_MODULE\", chainId, account, moduleTypeId, module],\n ),\n );\n return ethers.hashMessage(ethers.getBytes(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: ethers.JsonRpcProvider;\n private readonly chainId: number;\n\n constructor(provider: ethers.JsonRpcProvider, 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\";\n\n // Pack: guardian sigs (65 bytes each) concatenated with module init data\n const packed =\n sigs.length > 0\n ? ethers.concat([...sigs.map((s) => ethers.getBytes(s)), ethers.getBytes(initData)])\n : ethers.getBytes(initData);\n\n const iface = new ethers.Interface(AIRACCOUNT_ABI);\n return iface.encodeFunctionData(\"installModule\", [\n params.moduleTypeId,\n params.module,\n 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\";\n const packed = ethers.concat([\n ethers.getBytes(params.guardianSig1),\n ethers.getBytes(params.guardianSig2),\n ethers.getBytes(deInitData),\n ]);\n\n const iface = new ethers.Interface(AIRACCOUNT_ABI);\n return iface.encodeFunctionData(\"uninstallModule\", [\n params.moduleTypeId,\n params.module,\n 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 const contract = new ethers.Contract(account, AIRACCOUNT_ABI, this.provider);\n return contract.isModuleInstalled(moduleTypeId, module, \"0x\") as Promise<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 { ethers } from \"ethers\";\nimport {\n SESSION_KEY_VALIDATOR_ABI,\n AGENT_SESSION_KEY_VALIDATOR_ABI,\n} from \"../constants/entrypoint\";\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 ?? ethers.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 * Decode the 8-field Session tuple returned by getSession/getP256Session into\n * a SessionInfo, computing the derived `active` flag.\n * The contract returns the tuple positionally: ethers exposes it as an\n * indexable Result, so we read by index to match the on-chain field order.\n */\nfunction decodeSessionInfo(session: ethers.Result | unknown[]): SessionInfo {\n const s = session as ArrayLike<unknown>;\n const expiry = Number(s[0]);\n const now = Math.floor(Date.now() / 1000);\n return {\n expiry,\n contractScope: s[1] as string,\n selectorScope: s[2] as string,\n revoked: s[3] as boolean,\n velocityLimit: Number(s[4]),\n velocityWindow: Number(s[5]),\n callTargets: [...((s[6] as string[]) ?? [])],\n selectorAllowlist: [...((s[7] as string[]) ?? [])],\n active: expiry > now && !(s[3] as boolean),\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 provider: ethers.JsonRpcProvider;\n private readonly skValidator: ethers.Contract;\n private readonly askValidator: ethers.Contract;\n\n constructor(\n provider: ethers.JsonRpcProvider,\n sessionKeyValidatorAddress: string,\n agentSessionKeyValidatorAddress: string,\n ) {\n this.provider = provider;\n this.skValidator = new ethers.Contract(\n sessionKeyValidatorAddress,\n SESSION_KEY_VALIDATOR_ABI,\n provider,\n );\n this.askValidator = new ethers.Contract(\n agentSessionKeyValidatorAddress,\n AGENT_SESSION_KEY_VALIDATOR_ABI,\n provider,\n );\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 this.skValidator.buildGrantHash(\n params.account,\n params.sessionKey,\n buildSessionStruct(params),\n ) as Promise<string>;\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.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.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 iface = new ethers.Interface(SESSION_KEY_VALIDATOR_ABI);\n const cfg = buildSessionStruct(params);\n if (params.ownerSig) {\n return iface.encodeFunctionData(\"grantSession\", [\n params.account,\n params.sessionKey,\n cfg,\n params.ownerSig,\n ]);\n }\n // grantSessionDirect — owner EOA direct tx only (NOT for UserOp/gasless flows).\n return iface.encodeFunctionData(\"grantSessionDirect\", [\n params.account,\n params.sessionKey,\n cfg,\n ]);\n }\n\n /** Encode calldata for revokeSession(). */\n encodeRevokeSession(account: string, sessionKey: string): string {\n const iface = new ethers.Interface(SESSION_KEY_VALIDATOR_ABI);\n return iface.encodeFunctionData(\"revokeSession\", [account, sessionKey]);\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 this.skValidator.buildP256GrantHash(\n params.account,\n params.keyX,\n params.keyY,\n buildSessionStruct(params),\n ) as Promise<string>;\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.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.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 iface = new ethers.Interface(SESSION_KEY_VALIDATOR_ABI);\n const cfg = buildSessionStruct(params);\n if (params.ownerSig) {\n return iface.encodeFunctionData(\"grantP256Session\", [\n params.account,\n params.keyX,\n params.keyY,\n cfg,\n params.ownerSig,\n ]);\n }\n // grantP256SessionDirect — owner EOA direct tx only (NOT for UserOp/gasless flows).\n return iface.encodeFunctionData(\"grantP256SessionDirect\", [\n params.account,\n params.keyX,\n params.keyY,\n cfg,\n ]);\n }\n\n /** Encode calldata for revokeP256Session(). */\n encodeRevokeP256Session(account: string, keyX: string, keyY: string): string {\n const iface = new ethers.Interface(SESSION_KEY_VALIDATOR_ABI);\n return iface.encodeFunctionData(\"revokeP256Session\", [account, keyX, keyY]);\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 const iface = new ethers.Interface(AGENT_SESSION_KEY_VALIDATOR_ABI);\n return iface.encodeFunctionData(\"grantAgentSession\", [\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 * 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 const iface = new ethers.Interface(AGENT_SESSION_KEY_VALIDATOR_ABI);\n return iface.encodeFunctionData(\"delegateSession\", [\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 /** Encode calldata for revokeAgentSession(). */\n encodeRevokeAgentSession(sessionKey: string): string {\n const iface = new ethers.Interface(AGENT_SESSION_KEY_VALIDATOR_ABI);\n return iface.encodeFunctionData(\"revokeAgentSession\", [sessionKey]);\n }\n\n /** Query agent session config + runtime state. */\n async getAgentSession(account: string, sessionKey: string): Promise<AgentSessionInfo> {\n const [expiry, velocityLimit, velocityWindow, revoked, callTargets, selectorAllowlist] =\n await this.askValidator.agentSessions(account, sessionKey);\n const [callCount, windowStart] =\n await this.askValidator.sessionStates(account, sessionKey);\n return {\n expiry: Number(expiry),\n velocityLimit: Number(velocityLimit),\n velocityWindow: Number(velocityWindow),\n callTargets,\n selectorAllowlist,\n revoked,\n callCount: BigInt(callCount),\n windowStart: BigInt(windowStart),\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.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.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 { ethers } from \"ethers\";\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/**\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: ethers.JsonRpcProvider;\n\n constructor(provider: ethers.JsonRpcProvider) {\n this.provider = provider;\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 = new ethers.Contract(accountAddress, AIRACCOUNT_ABI, this.provider);\n const guardAddress: string = await account.guard();\n if (guardAddress === ethers.ZeroAddress) return null;\n\n const guard = new ethers.Contract(guardAddress, EXTENDED_GUARD_ABI, this.provider);\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),\n todaySpent: BigInt(todaySpent),\n remaining: BigInt(remaining),\n currentTier: resolveTierFromSpend(BigInt(todaySpent), BigInt(tier1Limit), BigInt(tier2Limit)),\n tier1Limit: BigInt(tier1Limit),\n tier2Limit: BigInt(tier2Limit),\n minDailyLimit: BigInt(minDailyLimit),\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 = new ethers.Contract(accountAddress, AIRACCOUNT_ABI, this.provider);\n const guardAddress: string = await account.guard();\n if (guardAddress === ethers.ZeroAddress) return null;\n\n const guard = new ethers.Contract(guardAddress, EXTENDED_GUARD_ABI, this.provider);\n try {\n const todaySpent = await guard.tokenTodaySpent(token);\n // TokenConfig is not directly readable on-chain per token; limits are not fully implemented.\n return {\n token,\n todaySpent: BigInt(todaySpent),\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 = new ethers.Contract(accountAddress, AIRACCOUNT_ABI, this.provider);\n return account.approvedAlgorithms(algId) as Promise<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","import { ethers } from \"ethers\";\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\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 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 = ethers.solidityPacked([\"address\", \"string\"], [owner, dappId]);\n return BigInt(ethers.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: ethers.JsonRpcProvider,\n config: OapdConfig,\n): Promise<string> {\n const factoryAddress = config.factoryAddress ?? AIRACCOUNT_ADDRESSES.sepolia.factory;\n const factory = new ethers.Contract(factoryAddress, AIRACCOUNT_FACTORY_ABI, provider);\n const salt = computeOapdSalt(config.owner, config.dappId);\n\n return factory.getFunction(\"getAddress\")(config.owner, salt, config.initConfig) 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: ethers.JsonRpcProvider,\n config: OapdConfig,\n): Promise<{ address: string; chainQualified: string }> {\n const factoryAddress = config.factoryAddress ?? AIRACCOUNT_ADDRESSES.sepolia.factory;\n const factory = new ethers.Contract(factoryAddress, AIRACCOUNT_FACTORY_ABI, provider);\n const salt = computeOapdSalt(config.owner, config.dappId);\n\n const result = await factory.getFunction(\"getAddressWithChainId\")(\n config.owner,\n salt,\n config.initConfig,\n );\n return { address: result[0] as string, chainQualified: result[1] as string };\n}\n\n/**\n * Check if an OAPD account has been deployed yet.\n */\nexport async function isOapdDeployed(\n provider: ethers.JsonRpcProvider,\n config: OapdConfig,\n): Promise<boolean> {\n const address = await getOapdAddress(provider, config);\n const code = await provider.getCode(address);\n return code !== \"0x\";\n}\n","// ─── Algorithm IDs (matches AAStarAirAccountBase constants) ─────\n\nexport const ALG_BLS = 0x01;\nexport const ALG_ECDSA = 0x02;\nexport const ALG_P256 = 0x03;\nexport const ALG_CUMULATIVE_T2 = 0x04; // P256 + BLS\nexport const ALG_CUMULATIVE_T3 = 0x05; // P256 + BLS + Guardian ECDSA\n\nexport type AlgId =\n | typeof ALG_BLS\n | typeof ALG_ECDSA\n | typeof ALG_P256\n | typeof ALG_CUMULATIVE_T2\n | typeof ALG_CUMULATIVE_T3;\n\n// ─── Tier Levels ───────────────────────────────────────────────\n\nexport type TierLevel = 1 | 2 | 3;\n\nexport interface TierConfig {\n /** Max value for Tier 1 (single ECDSA/Passkey). 0 = no enforcement. */\n tier1Limit: bigint;\n /** Max value for Tier 2 (P256 + BLS). 0 = no enforcement. */\n tier2Limit: bigint;\n}\n\n// ─── Guard Status ──────────────────────────────────────────────\n\nexport interface GuardStatus {\n hasGuard: boolean;\n guardAddress: string;\n dailyLimit: bigint;\n dailyRemaining: bigint;\n}\n\n// ─── Pre-check result ──────────────────────────────────────────\n\nexport interface PreCheckResult {\n ok: boolean;\n errors: string[];\n tier: TierLevel;\n algId: AlgId;\n}\n","import {\n TierLevel,\n TierConfig,\n AlgId,\n ALG_ECDSA,\n ALG_CUMULATIVE_T2,\n ALG_CUMULATIVE_T3,\n} from \"./types\";\n\n/**\n * Determine the required tier for a given transaction value.\n *\n * - Tier 1: value <= tier1Limit — single ECDSA or P256 passkey\n * - Tier 2: tier1Limit < value <= tier2Limit — P256 + BLS aggregate\n * - Tier 3: value > tier2Limit — P256 + BLS + Guardian ECDSA\n *\n * If both limits are 0 (no enforcement), always returns Tier 1.\n */\nexport function resolveTier(value: bigint, config: TierConfig): TierLevel {\n if (config.tier1Limit === 0n && config.tier2Limit === 0n) return 1;\n if (config.tier1Limit > 0n && value <= config.tier1Limit) return 1;\n if (config.tier2Limit > 0n && value <= config.tier2Limit) return 2;\n return 3;\n}\n\n/**\n * Get the algorithm ID to use for a given tier.\n *\n * - Tier 1: ALG_ECDSA (0x02) — raw 65-byte ECDSA, no prefix needed\n * - Tier 2: ALG_CUMULATIVE_T2 (0x04) — P256 + BLS\n * - Tier 3: ALG_CUMULATIVE_T3 (0x05) — P256 + BLS + Guardian\n */\nexport function algIdForTier(tier: TierLevel): AlgId {\n switch (tier) {\n case 1:\n return ALG_ECDSA;\n case 2:\n return ALG_CUMULATIVE_T2;\n case 3:\n return ALG_CUMULATIVE_T3;\n }\n}\n","import { ethers } from \"ethers\";\nimport { EthereumProvider } from \"../providers/ethereum-provider\";\nimport { AIRACCOUNT_ABI, 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 provider = this.ethereum.getProvider();\n const account = new ethers.Contract(accountAddress, AIRACCOUNT_ABI, provider);\n\n const [tier1Limit, tier2Limit] = await Promise.all([\n account.tier1Limit(),\n account.tier2Limit(),\n ]);\n\n return {\n tier1Limit: BigInt(tier1Limit),\n tier2Limit: BigInt(tier2Limit),\n };\n }\n\n /**\n * Fetch guard status from the account's GlobalGuard.\n */\n async fetchGuardStatus(accountAddress: string): Promise<GuardStatus> {\n const provider = this.ethereum.getProvider();\n const account = new ethers.Contract(accountAddress, AIRACCOUNT_ABI, provider);\n\n const config = await account.getConfigDescription();\n const guardAddress = config.guardAddress;\n\n if (guardAddress === ethers.ZeroAddress) {\n return {\n hasGuard: false,\n guardAddress: ethers.ZeroAddress,\n dailyLimit: 0n,\n dailyRemaining: 0n,\n };\n }\n\n const guard = new ethers.Contract(guardAddress, GLOBAL_GUARD_ABI, provider);\n const [dailyLimit, dailyRemaining] = await Promise.all([\n guard.dailyLimit(),\n guard.remainingDailyAllowance(),\n ]);\n\n return {\n hasGuard: true,\n guardAddress,\n dailyLimit: BigInt(dailyLimit),\n dailyRemaining: BigInt(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 provider = this.ethereum.getProvider();\n const accountContract = new ethers.Contract(accountAddress, AIRACCOUNT_ABI, provider);\n const isApproved = await accountContract.approvedAlgorithms(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 { ethers } from \"ethers\";\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\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 * 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: ethers.Contract;\n private readonly iface: ethers.Interface;\n\n constructor(\n private readonly moduleAddress: string,\n providerOrSigner: ethers.Provider | ethers.Signer\n ) {\n this.contract = new ethers.Contract(moduleAddress, FORCE_EXIT_ABI, providerOrSigner);\n this.iface = new ethers.Interface(FORCE_EXIT_ABI);\n }\n\n // ── On-chain reads ──────────────────────────────────────────────\n\n async isInitialized(smartAccount: string): Promise<boolean> {\n return this.contract.isInitialized(smartAccount) as Promise<boolean>;\n }\n\n async getPendingExit(account: string): Promise<PendingExit> {\n const [target, value, data, proposedAt, approvalBitmap, guardians] =\n await this.contract.getPendingExit(account);\n return {\n target: target as string,\n value: BigInt(value),\n data: data as string,\n proposedAt: BigInt(proposedAt),\n approvalBitmap: BigInt(approvalBitmap),\n guardians: guardians as [string, string, string],\n };\n }\n\n async getAccountL2Type(account: string): Promise<number> {\n return Number(await this.contract.accountL2Type(account));\n }\n\n async getApprovalThreshold(): Promise<number> {\n return Number(await this.contract.APPROVAL_THRESHOLD());\n }\n\n async getModuleVersion(): Promise<string> {\n return this.contract.MODULE_VERSION() as Promise<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 this.iface.encodeFunctionData(\"onInstall\", [\n ethers.AbiCoder.defaultAbiCoder().encode([\"uint8\"], [l2Type]),\n ]);\n }\n\n encodeOnUninstall(): string {\n return this.iface.encodeFunctionData(\"onUninstall\", [\"0x\"]);\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 this.iface.encodeFunctionData(\"proposeForceExit\", [target, value, data]);\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 this.iface.encodeFunctionData(\"approveForceExit\", [account, guardianSig]);\n }\n\n encodeExecuteForceExit(account: string): string {\n return this.iface.encodeFunctionData(\"executeForceExit\", [account]);\n }\n\n encodeCancelForceExit(account: string): string {\n return this.iface.encodeFunctionData(\"cancelForceExit\", [account]);\n }\n\n // ── Convenience: send transactions (requires Signer) ──────────\n\n async proposeForceExit(\n target: string,\n value: bigint,\n data: string\n ): Promise<ethers.TransactionResponse> {\n return (this.contract as ethers.Contract & {\n proposeForceExit: (t: string, v: bigint, d: string) => Promise<ethers.TransactionResponse>;\n }).proposeForceExit(target, value, data);\n }\n\n async approveForceExit(\n account: string,\n guardianSig: string\n ): Promise<ethers.TransactionResponse> {\n return (this.contract as ethers.Contract & {\n approveForceExit: (a: string, s: string) => Promise<ethers.TransactionResponse>;\n }).approveForceExit(account, guardianSig);\n }\n\n async executeForceExit(account: string): Promise<ethers.TransactionResponse> {\n return (this.contract as ethers.Contract & {\n executeForceExit: (a: string) => Promise<ethers.TransactionResponse>;\n }).executeForceExit(account);\n }\n\n async cancelForceExit(account: string): Promise<ethers.TransactionResponse> {\n return (this.contract as ethers.Contract & {\n cancelForceExit: (a: string) => Promise<ethers.TransactionResponse>;\n }).cancelForceExit(account);\n }\n}\n","import { ethers } from \"ethers\";\nimport { AIRACCOUNT_ABI } from \"../constants/entrypoint\";\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 * 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 private readonly iface: ethers.Interface;\n\n constructor(\n private readonly providerOrSigner: ethers.Provider | ethers.Signer\n ) {\n this.iface = new ethers.Interface(AIRACCOUNT_ABI);\n }\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 this.iface.encodeFunctionData(\"addGuardian\", [guardian]);\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 this.iface.encodeFunctionData(\"removeGuardian\", [index, guardianSigs]);\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 this.iface.encodeFunctionData(\"proposeRecovery\", [newOwner]);\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 this.iface.encodeFunctionData(\"approveRecovery\", []);\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 this.iface.encodeFunctionData(\"cancelRecovery\", []);\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 this.iface.encodeFunctionData(\"executeRecovery\", []);\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 contract = new ethers.Contract(account, AIRACCOUNT_ABI, this.providerOrSigner);\n const [newOwner, proposedAt, approvalBitmap, cancellationBitmap] =\n await contract.activeRecovery();\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) !== ethers.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 contract = new ethers.Contract(account, AIRACCOUNT_ABI, this.providerOrSigner);\n return Number(await contract.guardianCount());\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 contract = new ethers.Contract(account, AIRACCOUNT_ABI, this.providerOrSigner);\n const count = Number(await contract.guardianCount());\n const guardians: string[] = [];\n for (let i = 0; i < count; i++) {\n const g = (await contract.guardians(i)) as string;\n if (g !== ethers.ZeroAddress) guardians.push(g);\n }\n return guardians;\n }\n}\n","import { ethers } from \"ethers\";\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/ethers)\n * 2. Build initialize() calldata for the first UserOp / direct tx\n * 3. Submit both via integrator's relay\n */\nexport class EIP7702DelegateService {\n private readonly iface: ethers.Interface;\n private readonly contract: ethers.Contract;\n\n constructor(\n private readonly delegateAddress: string = AIR_ACCOUNT_DELEGATE_ADDRESS,\n providerOrSigner?: ethers.Provider | ethers.Signer\n ) {\n this.iface = new ethers.Interface(DELEGATE_ABI);\n if (providerOrSigner) {\n this.contract = new ethers.Contract(delegateAddress, DELEGATE_ABI, providerOrSigner);\n } else {\n // Read-only placeholder — encoding methods still work without a provider\n this.contract = new ethers.Contract(delegateAddress, DELEGATE_ABI);\n }\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 this.iface.encodeFunctionData(\"initialize\", [\n params.guardian1,\n params.guardian1Sig,\n params.guardian2,\n params.guardian2Sig,\n params.dailyLimit,\n ]);\n }\n\n encodeExecute(dest: string, value: bigint, data: string): string {\n return this.iface.encodeFunctionData(\"execute\", [dest, value, data]);\n }\n\n encodeExecuteBatch(\n dests: string[],\n values: bigint[],\n datas: string[]\n ): string {\n return this.iface.encodeFunctionData(\"executeBatch\", [dests, values, datas]);\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 ethers Signer.\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 const encoded = ethers.encodeRlp([\n chainId === 0 ? \"0x\" : ethers.toBeHex(chainId),\n this.delegateAddress,\n nonce === 0n ? \"0x\" : ethers.toBeHex(nonce),\n ]);\n return ethers.keccak256(ethers.concat([\"0x05\", encoded]));\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 verifyAuthorization(\n eoa: string,\n chainId: number,\n nonce: bigint,\n signature: string\n ): boolean {\n const hash = this.buildAuthorizationHash(chainId, nonce);\n const recovered = ethers.recoverAddress(hash, signature);\n return recovered.toLowerCase() === eoa.toLowerCase();\n }\n\n // ── On-chain reads (requires provider) ───────────────────────\n\n async isInitialized(eoa: string): Promise<boolean> {\n const provider = this.contract.runner as ethers.Provider | null;\n if (!provider) throw new Error(\"EIP7702DelegateService: provider required for on-chain reads\");\n const c = new ethers.Contract(eoa, DELEGATE_ABI, provider);\n return c.isInitialized() as Promise<boolean>;\n }\n\n async getOwner(eoa: string): Promise<string> {\n const provider = this.contract.runner as ethers.Provider | null;\n if (!provider) throw new Error(\"EIP7702DelegateService: provider required for on-chain reads\");\n const c = new ethers.Contract(eoa, DELEGATE_ABI, provider);\n return c.owner() as Promise<string>;\n }\n\n async getGuardians(eoa: string): Promise<[string, string, string]> {\n const provider = this.contract.runner as ethers.Provider | null;\n if (!provider) throw new Error(\"EIP7702DelegateService: provider required for on-chain reads\");\n const c = new ethers.Contract(eoa, DELEGATE_ABI, provider);\n return c.getGuardians() as Promise<[string, string, string]>;\n }\n}\n","import { ethers } from \"ethers\";\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/** 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: ethers.Result | unknown[]): WeightConfig {\n const r = result as Record<string, unknown> & unknown[];\n // ethers Result supports both positional indexing and named access; prefer named.\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 contract: ethers.Contract;\n private readonly iface: ethers.Interface;\n\n constructor(\n private readonly accountAddress: string,\n providerOrSigner: ethers.Provider | ethers.Signer\n ) {\n this.contract = new ethers.Contract(accountAddress, WEIGHTED_SIGNATURE_ABI, providerOrSigner);\n this.iface = new ethers.Interface(WEIGHTED_SIGNATURE_ABI);\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.contract.weightConfig();\n return fromConfigResult(result as ethers.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.contract.pendingWeightChange();\n return {\n proposed: fromConfigResult(proposed as ethers.Result),\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): string {\n return this.iface.encodeFunctionData(\"setWeightConfig\", [toConfigTuple(config)]);\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): string {\n return this.iface.encodeFunctionData(\"proposeWeightChange\", [toConfigTuple(config)]);\n }\n\n /** Encode approveWeightChange calldata. GUARDIAN only; each guardian may approve once. */\n encodeApproveWeightChange(): string {\n return this.iface.encodeFunctionData(\"approveWeightChange\", []);\n }\n\n /** Encode cancelWeightChange calldata. OWNER or any GUARDIAN may cancel a pending proposal. */\n encodeCancelWeightChange(): string {\n return this.iface.encodeFunctionData(\"cancelWeightChange\", []);\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(): string {\n return this.iface.encodeFunctionData(\"executeWeightChange\", []);\n }\n}\n","import { ethers } from \"ethers\";\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// ─── 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 provider (or a signer with an attached provider).\n */\nexport class AgentRegistryService {\n private readonly contract: ethers.Contract;\n private readonly iface: ethers.Interface;\n private readonly factoryIface: ethers.Interface;\n private readonly accountIface: ethers.Interface;\n private readonly providerOrSigner: ethers.Provider | ethers.Signer;\n\n /**\n * @param providerOrSigner ethers Provider (reads only) or Signer (reads + sends).\n * @param registryAddress deployed AgentRegistry contract address.\n */\n constructor(\n providerOrSigner: ethers.Provider | ethers.Signer,\n private readonly registryAddress: string\n ) {\n this.providerOrSigner = providerOrSigner;\n this.contract = new ethers.Contract(registryAddress, AGENT_REGISTRY_ABI, providerOrSigner);\n this.iface = new ethers.Interface(AGENT_REGISTRY_ABI);\n this.factoryIface = new ethers.Interface(AIRACCOUNT_FACTORY_ABI);\n this.accountIface = new ethers.Interface(AIRACCOUNT_ABI);\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 this.accountIface.encodeFunctionData(\"execute\", [\n this.registryAddress,\n 0n,\n this.encodeRegisterAgent(agentWallet, agentWalletSig),\n ]);\n }\n\n /** Encode `account.execute(registry, 0, revokeAgent(agentWallet))`. */\n encodeRevokeAgentViaAccount(agentWallet: string): string {\n return this.accountIface.encodeFunctionData(\"execute\", [\n this.registryAddress,\n 0n,\n this.encodeRevokeAgent(agentWallet),\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 this.iface.encodeFunctionData(\"registerAgent\", [agentWallet, agentWalletSig]);\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 this.iface.encodeFunctionData(\"revokeAgent\", [agentWallet]);\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 this.iface.encodeFunctionData(\"deregisterAgent\", [agentWallet]);\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 this.contract.isRegisteredAgent(agentWallet) as Promise<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 this.contract.isValidAccount(account) as Promise<boolean>;\n }\n\n /** The human owner bound to `agentWallet` (ZeroAddress if unregistered). */\n async getHumanOwner(agentWallet: string): Promise<string> {\n return this.contract.getHumanOwner(agentWallet) as Promise<string>;\n }\n\n /** Number of agents registered under `owner`. */\n async getAgentCount(owner: string): Promise<bigint> {\n return BigInt(await this.contract.getAgentCount(owner));\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 this.contract.getAgentByIndex(owner, index) as Promise<string>;\n }\n\n /** Full list of agent wallets registered under `humanOwner`. */\n async getAgents(humanOwner: string): Promise<string[]> {\n const result = (await this.contract.getAgents(humanOwner)) as string[];\n // Normalise the ethers Result proxy into a plain 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.contract.getAgentsPage(owner, start, count)) as string[];\n return Array.from(result);\n }\n\n /** Raw `agentWalletOwner` mapping read (agentWallet → owner). */\n async agentWalletOwner(agentWallet: string): Promise<string> {\n return this.contract.agentWalletOwner(agentWallet) as Promise<string>;\n }\n\n /** Raw `ownerAgents` array read (owner, index → agentWallet). */\n async ownerAgents(owner: string, index: bigint | number): Promise<string> {\n return this.contract.ownerAgents(owner, index) as Promise<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 this.factoryIface.encodeFunctionData(\"createAgentAccount\", [\n params.agentKey,\n params.agentId,\n params.guardian2,\n params.guardian2Sig,\n params.agentKeySig,\n params.deadline,\n params.dailyLimit,\n ]);\n }\n\n /**\n * Encode calldata for the factory's `setAgentRegistry(_agentRegistry)` (factory-admin only).\n */\n encodeSetAgentRegistry(agentRegistry: string): string {\n return this.factoryIface.encodeFunctionData(\"setAgentRegistry\", [agentRegistry]);\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 const factory = new ethers.Contract(\n factoryAddress,\n AIRACCOUNT_FACTORY_ABI,\n this.providerOrSigner\n );\n return factory.getAgentAddress(humanOwner, agentKey, agentId) as Promise<string>;\n }\n\n /** Read the AgentRegistry address currently bound to the factory. */\n async getFactoryAgentRegistry(factoryAddress: string): Promise<string> {\n const factory = new ethers.Contract(\n factoryAddress,\n AIRACCOUNT_FACTORY_ABI,\n this.providerOrSigner\n );\n return factory.agentRegistry() as Promise<string>;\n }\n}\n","import { ethers } from \"ethers\";\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 iface: ethers.Interface;\n private readonly provider?: ethers.Provider;\n\n constructor(provider?: ethers.Provider) {\n this.iface = new ethers.Interface(ERC8004_ABI);\n this.provider = provider;\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 this.iface.encodeFunctionData(\"setAgentWallet\", [\n params.agentId,\n params.agentWallet,\n params.agentRegistry,\n 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 this.iface.encodeFunctionData(\"mintAgentIdentity\", [\n params.identityRegistry,\n 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 this.iface.encodeFunctionData(\"bindERC8004AgentWallet\", [\n params.identityRegistry,\n params.agentId,\n params.agentWallet,\n params.deadline,\n params.signature,\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 this.iface.encodeFunctionData(\"submitAgentReputation\", [\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 * 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 = new ethers.Contract(accountAddress, ERC8004_ABI, this.provider);\n const [count, summaryValue, summaryDecimals] = await contract.queryAgentReputation(\n params.reputationRegistry,\n params.agentId,\n params.clientAddresses,\n params.tag1,\n params.tag2,\n );\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 this.iface.encodeFunctionData(\"queryAgentReputation\", [\n params.reputationRegistry,\n params.agentId,\n params.clientAddresses,\n params.tag1,\n params.tag2,\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 = new ethers.Contract(accountAddress, ERC8004_ABI, this.provider);\n return contract.agentExtension() as Promise<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","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 { ethers } from \"ethers\";\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 provider?: ethers.Provider\n ): KmsSigner {\n this.ensureEnabled();\n return new KmsSigner(keyId, address, this, assertionProvider, provider);\n }\n}\n\n/**\n * ethers.AbstractSigner backed by KMS 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 */\nexport class KmsSigner extends ethers.AbstractSigner {\n constructor(\n private readonly keyId: string,\n private readonly _address: string,\n private readonly kmsManager: KmsManager,\n private readonly assertionProvider: () => Promise<LegacyPasskeyAssertion>,\n provider?: ethers.Provider\n ) {\n super(provider);\n }\n\n async getAddress(): Promise<string> {\n return this._address;\n }\n\n async signMessage(message: string | Uint8Array): Promise<string> {\n const messageBytes = typeof message === \"string\" ? ethers.toUtf8Bytes(message) : message;\n const messageHash = ethers.hashMessage(messageBytes);\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 async signTransaction(tx: ethers.TransactionRequest): Promise<string> {\n if (!this.provider) {\n throw new Error(\"Provider is required for signing transactions\");\n }\n const populated = await this.populateTransaction(tx);\n const unsignedTx = ethers.Transaction.from(populated);\n const txHash = unsignedTx.hash;\n if (!txHash) {\n throw new Error(\"Failed to compute transaction hash\");\n }\n const assertion = await this.assertionProvider();\n const signResponse = await this.kmsManager.signHash(txHash, assertion, {\n Address: this._address,\n });\n const sig = ethers.Signature.from(\"0x\" + signResponse.Signature);\n unsignedTx.signature = sig;\n return unsignedTx.serialized;\n }\n\n async signTypedData(\n domain: ethers.TypedDataDomain,\n types: Record<string, ethers.TypedDataField[]>,\n value: Record<string, unknown>\n ): Promise<string> {\n const hash = ethers.TypedDataEncoder.hash(domain, types, value);\n const assertion = await this.assertionProvider();\n const signResponse = await this.kmsManager.signHash(hash, assertion, {\n Address: this._address,\n });\n return \"0x\" + signResponse.Signature;\n }\n\n connect(provider: ethers.Provider): KmsSigner {\n return new KmsSigner(\n this.keyId,\n this._address,\n this.kmsManager,\n this.assertionProvider,\n provider\n );\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 { ethers } from \"ethers\";\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 wallet: ethers.Wallet;\n\n constructor(privateKey: string, provider?: ethers.Provider) {\n this.wallet = new ethers.Wallet(privateKey, provider);\n }\n\n async getAddress(_userId: string): Promise<string> {\n return this.wallet.address;\n }\n\n async getSigner(_userId: string, _ctx?: PasskeyAssertionContext): Promise<ethers.Signer> {\n return this.wallet;\n }\n\n async ensureSigner(_userId: string): Promise<{ signer: ethers.Signer; address: string }> {\n return { signer: this.wallet, address: this.wallet.address };\n }\n}\n"]}
|