import { ethers } from 'ethers'; import { U as UserOperation, P as PackedUserOperation } from '../index-BrOH79EF.cjs'; export { G as GasEstimate } from '../index-BrOH79EF.cjs'; import { b as BLSSignatureData } from '../types-DgyPLum6.cjs'; export { B as BLSConfig, a as BLSNode, C as CumulativeT2SignatureData, c as CumulativeT3SignatureData } from '../types-DgyPLum6.cjs'; import { T as TierLevel$1, f as TierConfig, G as GuardStatus, P as PreCheckResult } from '../tier-router-6fchEA9V.cjs'; export { A as ALG_BLS, c as ALG_CUMULATIVE_T2, d as ALG_CUMULATIVE_T3, a as ALG_ECDSA, b as ALG_P256, e as AlgId, g as algIdForTier, r as resolveTier } from '../tier-router-6fchEA9V.cjs'; /** * Account record stored by the SDK. */ interface AccountRecord { userId: string; address: string; signerAddress: string; salt: number; deployed: boolean; deploymentTxHash: string | null; validatorAddress: string; entryPointVersion: string; factoryAddress: string; createdAt: string; /** * Daily transfer limit in wei, stored as a decimal string (bigint serialization). * "0" or undefined means no guard / no limit. * Written into the factory config at account creation time. */ dailyLimit?: string; /** * Guardian addresses and their acceptance signatures. * Present only for accounts created via createAccountWithGuardians(). * Required by transfer-manager to reconstruct initCode using createAccountWithDefaults. */ guardian1?: string; guardian1Sig?: string; guardian2?: string; guardian2Sig?: string; } /** * Transfer record stored by the SDK. */ interface TransferRecord { id: string; userId: string; from: string; to: string; amount: string; data?: string; userOpHash: string; bundlerUserOpHash?: string; transactionHash?: string; status: "pending" | "submitted" | "completed" | "failed"; error?: string; nodeIndices: number[]; tokenAddress?: string; tokenSymbol?: string; createdAt: string; submittedAt?: string; completedAt?: string; failedAt?: string; } /** * Paymaster configuration record. */ interface PaymasterRecord { id?: string; name: string; address: string; apiKey?: string; type: "pimlico" | "stackup" | "alchemy" | "custom"; endpoint?: string; createdAt?: string; } /** * BLS configuration record. */ interface BlsConfigRecord { signerNodes?: { nodes: Array<{ nodeId: string; nodeName: string; apiEndpoint: string; status: string; lastSeen?: string; }>; }; discovery?: { seedNodes?: Array<{ endpoint: string; }>; discoveryTimeout?: number; }; } /** * Pluggable storage adapter — replaces NestJS DatabaseService. * SDK only manages accounts, transfers, paymasters, and BLS config. * User authentication is NOT handled by the SDK. */ interface IStorageAdapter { getAccounts(): Promise; saveAccount(account: AccountRecord): Promise; findAccountByUserId(userId: string): Promise; updateAccount(userId: string, updates: Partial): Promise; saveTransfer(transfer: TransferRecord): Promise; findTransfersByUserId(userId: string): Promise; findTransferById(id: string): Promise; updateTransfer(id: string, updates: Partial): Promise; getPaymasters(userId: string): Promise; savePaymaster(userId: string, paymaster: PaymasterRecord): Promise; removePaymaster(userId: string, name: string): Promise; getBlsConfig(): Promise; updateSignerNodesCache(nodes: unknown[]): Promise; } /** * Optional logger interface for server SDK. * Implement this to integrate with your application's logging framework. */ interface ILogger { debug(message: string, ...args: unknown[]): void; log(message: string, ...args: unknown[]): void; warn(message: string, ...args: unknown[]): void; error(message: string, ...args: unknown[]): void; } /** * Default console logger used when no custom logger is provided. */ declare class ConsoleLogger implements ILogger { private readonly prefix; constructor(prefix?: string); debug(message: string, ...args: unknown[]): void; log(message: string, ...args: unknown[]): void; warn(message: string, ...args: unknown[]): void; error(message: string, ...args: unknown[]): void; } /** * Silent logger that suppresses all output. */ declare class SilentLogger implements ILogger { debug(): void; log(): void; warn(): void; error(): void; } interface LegacyPasskeyAssertion { AuthenticatorData: string; ClientDataHash: string; Signature: string; } interface KmsCreateKeyResponse { KeyMetadata: { KeyId: string; Arn: string; CreationDate: string; Enabled: boolean; Description: string; KeyUsage: string; KeySpec: string; Origin: string; Address?: string; }; Mnemonic: string; Address?: string; Status?: string; } interface KmsSignHashResponse { Signature: string; } interface KmsBeginRegistrationRequest { Description?: string; UserName?: string; UserDisplayName?: string; } interface KmsBeginRegistrationResponse { ChallengeId: string; Options: PublicKeyCredentialCreationOptions; } interface KmsCompleteRegistrationRequest { ChallengeId: string; Credential: unknown; Description?: string; } interface KmsCompleteRegistrationResponse { KeyId: string; CredentialId: string; Status: string; } interface KmsBeginAuthenticationRequest { Address?: string; KeyId?: string; } interface KmsBeginAuthenticationResponse { ChallengeId: string; Options: PublicKeyCredentialRequestOptions; } interface KmsKeyStatusResponse { KeyId: string; Status: "creating" | "deriving" | "ready" | "error"; Address?: string; PublicKey?: string; DerivationPath?: string; Error?: string; } interface KmsDescribeKeyResponse { KeyMetadata: { KeyId: string; Address?: string; PublicKey?: string; DerivationPath?: string; PasskeyPublicKey?: string; Arn?: string; CreationDate?: string; Enabled?: boolean; Description?: string; KeyUsage?: string; KeySpec?: string; Origin?: string; }; } /** * KMS service for remote key management with WebAuthn/Passkey integration. * * The new STM32 KMS (kms1.aastar.io) natively integrates WebAuthn, so * registration/authentication ceremonies are handled by the KMS directly. * Signing operations require a Passkey assertion (Legacy hex or WebAuthn ceremony). */ declare class KmsManager { private readonly kmsEndpoint; private readonly isEnabled; private readonly apiKey?; private readonly logger; private readonly http; constructor(options: { kmsEndpoint?: string; kmsEnabled?: boolean; kmsApiKey?: string; logger?: ILogger; }); isKmsEnabled(): boolean; private ensureEnabled; /** POST with x-amz-target header (required for wallet/signing operations). */ private amzPost; createKey(description: string, passkeyPublicKey: string): Promise; getKeyStatus(keyId: string): Promise; describeKey(keyId: string): Promise; /** * Poll KeyStatus until the key is ready (address derived) or timeout. * STM32 key derivation takes 60-75 seconds on first creation. */ pollUntilReady(keyId: string, timeoutMs?: number, intervalMs?: number): Promise; /** * Sign a hash using Legacy Passkey assertion (reusable for BLS dual-signing). */ signHash(hash: string, assertion: LegacyPasskeyAssertion, target: { Address?: string; KeyId?: string; }): Promise; /** * Sign a hash using a WebAuthn ceremony assertion (one-time use). */ signHashWithWebAuthn(hash: string, challengeId: string, credential: unknown, target: { Address?: string; KeyId?: string; }): Promise; beginRegistration(params: KmsBeginRegistrationRequest): Promise; completeRegistration(params: KmsCompleteRegistrationRequest): Promise; beginAuthentication(params: KmsBeginAuthenticationRequest): Promise; createKmsSigner(keyId: string, address: string, assertionProvider: () => Promise, provider?: ethers.Provider): KmsSigner; } /** * ethers.AbstractSigner backed by KMS with Passkey assertion. * * Each signing operation calls the `assertionProvider` to obtain a Legacy * Passkey assertion, which is then passed to KMS SignHash. The Legacy format * is reusable (no challenge consumption), enabling BLS dual-signing. */ declare class KmsSigner extends ethers.AbstractSigner { private readonly keyId; private readonly _address; private readonly kmsManager; private readonly assertionProvider; constructor(keyId: string, _address: string, kmsManager: KmsManager, assertionProvider: () => Promise, provider?: ethers.Provider); getAddress(): Promise; signMessage(message: string | Uint8Array): Promise; signTransaction(tx: ethers.TransactionRequest): Promise; signTypedData(domain: ethers.TypedDataDomain, types: Record, value: Record): Promise; connect(provider: ethers.Provider): KmsSigner; } /** * Context for passing Passkey assertion data through the signing chain. * Used by KMS-backed signers to authenticate signing operations. */ interface PasskeyAssertionContext { assertion: LegacyPasskeyAssertion; } /** * Pluggable signer adapter — replaces NestJS AuthService wallet management. * Implement this to provide signing capabilities from your key management system. */ interface ISignerAdapter { /** Get the EOA address for a given user. */ getAddress(userId: string): Promise; /** Get an ethers Signer instance for a given user. */ getSigner(userId: string, ctx?: PasskeyAssertionContext): Promise; /** * Ensure a signer exists for the user (create on demand if needed). * Returns the signer and its address. */ ensureSigner(userId: string): Promise<{ signer: ethers.Signer; address: string; }>; } /** * Per-version EntryPoint configuration. */ interface EntryPointVersionConfig { entryPointAddress: string; factoryAddress: string; validatorAddress: string; } /** * Server SDK configuration — replaces NestJS ConfigService. */ interface ServerConfig { /** Main network RPC URL. */ rpcUrl: string; /** Bundler RPC URL (e.g. Pimlico, StackUp). */ bundlerRpcUrl: string; /** Chain ID of the target network. */ chainId: number; /** EntryPoint configurations — at least one version must be provided. */ entryPoints: { v06?: EntryPointVersionConfig; v07?: EntryPointVersionConfig; v08?: EntryPointVersionConfig; }; /** Default EntryPoint version to use when not specified. */ defaultVersion?: "0.6" | "0.7" | "0.8"; /** BLS signer seed nodes for gossip discovery. */ blsSeedNodes?: string[]; /** Timeout for BLS node discovery in ms. */ blsDiscoveryTimeout?: number; /** KMS endpoint URL (optional, for KMS-based signing). */ kmsEndpoint?: string; /** Whether KMS signing is enabled. */ kmsEnabled?: boolean; /** KMS API key for authenticated requests. */ kmsApiKey?: string; /** Storage adapter (required). */ storage: IStorageAdapter; /** Signer adapter (required). */ signer: ISignerAdapter; /** Logger (optional, defaults to ConsoleLogger). */ logger?: ILogger; } /** AirAccount contract version selection. */ type AirAccountVersion = "M5" | "M7"; /** * Build a pre-configured EntryPointVersionConfig for Sepolia using a known AirAccount deployment. * Eliminates the need to look up contract addresses manually. * * @example * // Use M7 (default) * const config = { entryPoints: { v07: sepoliaV07Config() }, ... }; * * // Use M5 legacy * const config = { entryPoints: { v07: sepoliaV07Config("M5") }, ... }; */ declare function sepoliaV07Config(version?: AirAccountVersion): EntryPointVersionConfig; /** * Validate a ServerConfig and throw descriptive errors for missing fields. */ declare function validateConfig(config: ServerConfig): void; declare enum EntryPointVersion { V0_6 = "0.6", V0_7 = "0.7", V0_8 = "0.8" } interface EntryPointConfig { version: EntryPointVersion; address: string; factoryAddress: string; validatorAddress: string; } /** Default EntryPoint addresses (same on Sepolia, Mainnet, and OP Mainnet). */ declare const ENTRYPOINT_ADDRESSES: { "0.6": { sepolia: string; mainnet: string; optimism: string; }; "0.7": { sepolia: string; mainnet: string; optimism: string; }; "0.8": { sepolia: string; mainnet: string; optimism: string; }; }; declare const ENTRYPOINT_ABI_V6: string[]; declare const ENTRYPOINT_ABI_V7_V8: string[]; declare const FACTORY_ABI_V6: string[]; declare const FACTORY_ABI_V7_V8: string[]; declare const ACCOUNT_ABI: string[]; declare const VALIDATOR_ABI: string[]; declare const AIRACCOUNT_ADDRESSES: { sepolia: { factoryM4: string; factoryM5: string; factoryM7r5Prev: string; factory: string; factoryM7: string; accountImpl: string; validatorRouter: string; blsAlgorithm: string; blsAggregator: string; superPaymaster: string; compositeValidator: string; tierGuardHook: string; agentSessionKeyValidator: string; sessionKeyValidator: string; calldataParserRegistry: string; uniswapV3Parser: string; }; }; declare const AIRACCOUNT_ABI: string[]; declare const AIRACCOUNT_FACTORY_ABI: string[]; declare const GLOBAL_GUARD_ABI: string[]; declare const ERC20_ABI: string[]; declare const AGENT_SESSION_KEY_VALIDATOR_ABI: string[]; declare const TIER_GUARD_HOOK_ABI: string[]; declare const AIR_ACCOUNT_COMPOSITE_VALIDATOR_ABI: string[]; declare const FORCE_EXIT_MODULE_ABI: string[]; declare const MODULE_TYPE: { readonly VALIDATOR: 1; readonly EXECUTOR: 2; readonly HOOK: 3; }; declare const ALG_ID: { readonly BLS: 1; readonly ECDSA: 2; readonly P256: 3; readonly CUMULATIVE_T2: 4; readonly CUMULATIVE_T3: 5; readonly COMBINED_T1: 6; readonly WEIGHTED: 7; readonly SESSION_KEY: 8; readonly AGENT_SESSION_KEY: 9; }; declare const SESSION_KEY_VALIDATOR_ABI: string[]; declare const CALLDATA_PARSER_REGISTRY_ABI: string[]; declare const AIR_ACCOUNT_DELEGATE_ABI: string[]; /** * Unified Ethereum provider — replaces NestJS EthereumService. * Manages RPC + Bundler providers and contract interactions. */ declare class EthereumProvider { private readonly provider; private readonly bundlerProvider; private readonly config; private readonly logger; constructor(config: ServerConfig); getProvider(): ethers.JsonRpcProvider; getBundlerProvider(): ethers.JsonRpcProvider; private getVersionConfig; getEntryPointAddress(version: EntryPointVersion): string; getFactoryAddress(version: EntryPointVersion): string; getValidatorAddress(version: EntryPointVersion): string; getDefaultVersion(): EntryPointVersion; getFactoryContract(version?: EntryPointVersion): ethers.Contract; getEntryPointContract(version?: EntryPointVersion): ethers.Contract; getValidatorContract(version?: EntryPointVersion): ethers.Contract; getAccountContract(address: string): ethers.Contract; getAgentSessionKeyValidatorContract(address?: string): ethers.Contract; getTierGuardHookContract(address?: string): ethers.Contract; getCompositeValidatorContract(address?: string): ethers.Contract; getForceExitModuleContract(address: string): ethers.Contract; getBalance(address: string): Promise; getNonce(accountAddress: string, key?: number, version?: EntryPointVersion): Promise; getUserOpHash(userOp: UserOperation | PackedUserOperation, version?: EntryPointVersion): Promise; estimateUserOperationGas(userOp: unknown, version?: EntryPointVersion): Promise<{ callGasLimit: string; verificationGasLimit: string; preVerificationGas: string; }>; sendUserOperation(userOp: unknown, version?: EntryPointVersion): Promise; getUserOperationReceipt(userOpHash: string): Promise; waitForUserOp(userOpHash: string, maxAttempts?: number): Promise; getUserOperationGasPrice(): Promise<{ maxFeePerGas: string; maxPriorityFeePerGas: string; }>; } /** * Account manager — extracted from NestJS AccountService. * Creates and retrieves smart accounts without framework dependencies. */ declare class AccountManager { private readonly ethereum; private readonly storage; private readonly signer; private readonly logger; constructor(ethereum: EthereumProvider, storage: IStorageAdapter, signer: ISignerAdapter, logger?: ILogger); createAccount(userId: string, options?: { entryPointVersion?: EntryPointVersion; salt?: number; /** Daily transfer limit in wei. When > 0 the account is created with on-chain guard enforcement. */ dailyLimit?: bigint; }): Promise; getAccount(userId: string): Promise<(AccountRecord & { balance: string; nonce: string; }) | null>; getAccountAddress(userId: string): Promise; getAccountBalance(userId: string): Promise<{ address: string; balance: string; balanceInWei: string; }>; getAccountNonce(userId: string): Promise<{ address: string; nonce: string; }>; getAccountByUserId(userId: string): Promise; /** * Build the acceptance hash that guardian devices must sign before account creation. * * Encoding: keccak256(solidityPacked( * ["string","uint256","address","address","uint256"], * ["ACCEPT_GUARDIAN", chainId, factoryAddress, owner, salt] * )) * Total packed bytes: 13 + 32 + 20 + 20 + 32 = 117 bytes * * Returns the RAW keccak256 hash (no EIP-191 prefix). * Guardians MUST sign via personal_sign / ethers.signMessage(ethers.getBytes(hash)). * Do NOT use eth_sign — the EIP-191 "\x19Ethereum Signed Message:\n32" prefix * is applied inside the contract (toEthSignedMessageHash) before ecrecover, not here. * * @returns raw hex keccak256 hash — encode this into the QR code shown to guardian devices */ buildGuardianAcceptanceHash(owner: string, salt: number, factoryAddress: string, chainId: number): string; /** * Create an AirAccount with 3 on-chain guardians: * - guardian1 and guardian2: user's own devices (passkeys on phone 1 and phone 2) * - guardian3: team Safe multisig (defaultCommunityGuardian, set in factory at deploy time) * * Both guardian1 and guardian2 must sign the acceptance hash produced by * buildGuardianAcceptanceHash() before this method is called. * * Recovery: any 2-of-3 guardians can initiate social recovery after a 48h timelock. */ createAccountWithGuardians(userId: string, params: { guardian1: string; guardian1Sig: string; guardian2: string; guardian2Sig: string; dailyLimit: bigint; salt?: number; entryPointVersion?: EntryPointVersion; }): Promise; } /** * BLS signature service — extracted from NestJS BlsService. * Uses lazy initialization instead of onModuleInit. */ declare class BLSSignatureService { private readonly config; private readonly ethereum; private readonly storage; private readonly signer; private blsManager; private readonly logger; constructor(config: ServerConfig, ethereum: EthereumProvider, storage: IStorageAdapter, signer: ISignerAdapter, logger?: ILogger); /** Lazy-initialize BLSManager on first use. */ private ensureInitialized; getActiveSignerNodes(): Promise; generateBLSSignature(userId: string, userOpHash: string, ctx?: PasskeyAssertionContext): Promise; packSignature(blsData: BLSSignatureData): Promise; /** * Generate a tiered signature based on the required tier level. * * - Tier 1: raw 65-byte ECDSA (no algId prefix, backwards-compat) * - Tier 2: algId 0x04 — P256 + BLS aggregate + messagePoint ECDSA * - Tier 3: algId 0x05 — P256 + BLS + messagePoint ECDSA + Guardian ECDSA * * @param tier - Required tier level (1, 2, or 3) * @param userId - User ID for account lookup * @param userOpHash - The UserOp hash to sign * @param p256Signature - P256 passkey signature (64 bytes, required for tier 2/3) * @param guardianSigner - Guardian ethers.Signer (required for tier 3) * @param ctx - Optional passkey assertion context for KMS signing */ generateTieredSignature(params: { tier: TierLevel$1; userId: string; userOpHash: string; p256Signature?: string; guardianSigner?: ethers.Signer; ctx?: PasskeyAssertionContext; }): Promise; } /** * Pre-checks transactions against GlobalGuard before submitting on-chain. * Avoids wasted gas from predictable reverts. */ declare class GuardChecker { private readonly ethereum; private readonly logger; constructor(ethereum: EthereumProvider, logger?: ILogger); /** * Fetch tier limits from an AirAccount contract. */ fetchTierConfig(accountAddress: string): Promise; /** * Fetch guard status from the account's GlobalGuard. */ fetchGuardStatus(accountAddress: string): Promise; /** * Pre-check a transaction: determine tier, check guard limits and algorithm approval. * Returns errors array (empty = OK to proceed). */ preCheck(accountAddress: string, value: bigint): Promise; } /** * Thrown when a paymaster's on-chain price cache is stale. * Caller should invoke `paymasterManager.updatePrice(paymasterAddress)` before retrying. */ declare class PaymasterPriceStalenessError extends Error { readonly paymasterAddress: string; readonly ageSeconds: number; readonly thresholdSeconds: number; constructor(paymasterAddress: string, ageSeconds: number, thresholdSeconds: number); } /** * Paymaster manager — extracted from NestJS PaymasterService. * Storage via IStorageAdapter instead of filesystem JSON files. */ declare class PaymasterManager { private readonly ethereum; private readonly storage; private readonly logger; constructor(ethereum: EthereumProvider, storage: IStorageAdapter, logger?: ILogger); getAvailablePaymasters(userId: string): Promise<{ name: string; address: string; configured: boolean; }[]>; addCustomPaymaster(userId: string, name: string, address: string, type?: "pimlico" | "stackup" | "alchemy" | "custom", apiKey?: string, endpoint?: string): Promise; removeCustomPaymaster(userId: string, name: string): Promise; /** * Check whether a paymaster's on-chain price cache is still fresh. * Returns `{ fresh, ageSeconds, thresholdSeconds }`. * Throws if the contract does not implement `cachedPriceTimestamp()` / `priceStalenessThreshold()`. */ checkPriceFreshness(paymasterAddress: string): Promise<{ fresh: boolean; ageSeconds: number; thresholdSeconds: number; }>; /** * Call `updatePrice()` on a paymaster contract (permissionless). * Useful when `checkPriceFreshness()` reports stale price. * * @param signer - An ethers Signer that will send the transaction (must have gas). */ updatePrice(paymasterAddress: string, signer: ethers.Signer): Promise; getPaymasterData(userId: string, paymasterName: string, userOp: unknown, entryPoint: string, customAddress?: string, options?: { tokenAddress?: string; }): Promise; private getPimlicoPaymasterData; private getStackUpPaymasterData; private getAlchemyPaymasterData; } interface TokenInfo { address: string; symbol: string; name: string; decimals: number; } interface TokenBalance { token: TokenInfo; balance: string; formattedBalance: string; } /** * Token service — extracted from NestJS TokenService. * Only on-chain queries and calldata generation (no preset token list). */ declare class TokenService { private readonly ethereum; constructor(ethereum: EthereumProvider); getTokenInfo(tokenAddress: string): Promise; getTokenBalance(tokenAddress: string, walletAddress: string): Promise; getFormattedTokenBalance(tokenAddress: string, walletAddress: string): Promise; generateTransferCalldata(to: string, amount: string, decimals: number): string; validateToken(tokenAddress: string): Promise<{ isValid: boolean; token?: TokenInfo; error?: string; }>; } interface ExecuteTransferParams { to: string; amount: string; data?: string; tokenAddress?: string; usePaymaster?: boolean; paymasterAddress?: string; paymasterData?: string; /** ERC-20 token address for deposit-pull paymasters (e.g. PMv4) that require * the gas token address appended to paymasterData. Used when the paymaster * contract does not expose a public token() getter for auto-detection. */ paymasterTokenAddress?: string; passkeyAssertion?: LegacyPasskeyAssertion; /** P256 passkey signature (64 bytes hex). Required for AirAccount Tier 2/3. */ p256Signature?: string; /** Guardian ethers.Signer instance. Required for AirAccount Tier 3. */ guardianSigner?: ethers.Signer; /** Enable AirAccount tiered signature routing. Default: false (legacy BLS-only). */ useAirAccountTiering?: boolean; } interface EstimateGasParams { to: string; amount: string; data?: string; tokenAddress?: string; } interface TransferResult { success: boolean; transferId: string; userOpHash: string; status: string; message: string; from: string; to: string; amount: string; } /** * Transfer manager — extracted from NestJS TransferService. * No passkey verification: callers are responsible for their own auth. */ declare class TransferManager { private readonly ethereum; private readonly accountManager; private readonly blsService; private readonly paymasterManager; private readonly tokenService; private readonly storage; private readonly signer; private readonly logger; private readonly guardChecker; constructor(ethereum: EthereumProvider, accountManager: AccountManager, blsService: BLSSignatureService, paymasterManager: PaymasterManager, tokenService: TokenService, storage: IStorageAdapter, signer: ISignerAdapter, logger?: ILogger, guardChecker?: GuardChecker); executeTransfer(userId: string, params: ExecuteTransferParams): Promise; private processTransferAsync; estimateGas(userId: string, params: EstimateGasParams): Promise<{ callGasLimit: string; verificationGasLimit: string; preVerificationGas: string; validatorGasEstimate: any; totalGasEstimate: string; maxFeePerGas: string; maxPriorityFeePerGas: string; }>; getTransferStatus(userId: string, transferId: string): Promise>; getTransferHistory(userId: string, page?: number, limit?: number): Promise<{ transfers: TransferRecord[]; total: number; page: number; limit: number; totalPages: number; }>; private buildUserOperation; private formatUserOpForBundler; } /** * Thin wrapper around ISignerAdapter for consistent wallet access. */ declare class WalletManager { private readonly signer; constructor(signer: ISignerAdapter); getAddress(userId: string): Promise; getSigner(userId: string): Promise; ensureSigner(userId: string): Promise<{ signer: ethers.Signer; address: string; }>; } /** * Main facade for the YAAA Server SDK. * Wires all services together from a single config object. * * @example * ```ts * import { YAAAServerClient, MemoryStorage, LocalWalletSigner } from '@aastar/airaccount/server'; * * const client = new YAAAServerClient({ * rpcUrl: 'https://sepolia.infura.io/v3/...', * bundlerRpcUrl: 'https://api.pimlico.io/v2/11155111/rpc?apikey=...', * chainId: 11155111, * entryPoints: { * v06: { * entryPointAddress: '0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789', * factoryAddress: '0x...', * validatorAddress: '0x...', * }, * }, * storage: new MemoryStorage(), * signer: new LocalWalletSigner('0xPRIVATE_KEY'), * }); * * const account = await client.accounts.createAccount('user-123'); * ``` */ declare class YAAAServerClient { readonly ethereum: EthereumProvider; readonly accounts: AccountManager; readonly transfers: TransferManager; readonly bls: BLSSignatureService; readonly paymaster: PaymasterManager; readonly tokens: TokenService; readonly wallets: WalletManager; constructor(config: ServerConfig); } type ModuleTypeId = 1 | 2 | 3; interface InstallModuleParams { /** The deployed AirAccount address */ account: string; /** ERC-7579 module type: 1=Validator, 2=Executor, 3=Hook */ moduleTypeId: ModuleTypeId; /** Module contract address to install */ module: string; /** * Guardian signatures + module init data, packed as: * bytes[0..65*sigsRequired] = guardian ECDSA sigs * bytes[65*sigsRequired..] = module onInstall() init data * * Sig hash (per guardian, r5 format): * keccak256("INSTALL_MODULE" ‖ chainId ‖ account ‖ moduleTypeId ‖ module ‖ keccak256(moduleInitData)).toEthSignedMessageHash() * * sigsRequired: 0 if threshold<=40, 1 if <=70, 2 if =100 */ guardianSigs?: string[]; /** Raw bytes passed to module.onInstall() after guardian sigs */ moduleInitData?: string; } interface UninstallModuleParams { account: string; moduleTypeId: ModuleTypeId; module: string; /** Always requires 2 guardian sigs for uninstall */ guardianSig1: string; guardianSig2: string; /** Passed to module.onUninstall() */ moduleDeInitData?: string; } /** * Build the EIP-191 install hash that guardians must sign. * * r5 format: includes keccak256(moduleInitData) to prevent config-swap attacks. * * @example * const hash = buildInstallModuleHash(chainId, account, 1, moduleAddress, moduleInitData); * const sig = await guardian.signMessage(ethers.getBytes(hash)); */ declare function buildInstallModuleHash(chainId: number, account: string, moduleTypeId: ModuleTypeId, module: string, moduleInitData?: string): string; /** * Build the EIP-191 uninstall hash that guardians must sign. */ declare function buildUninstallModuleHash(chainId: number, account: string, moduleTypeId: ModuleTypeId, module: string): string; /** * ModuleManager — ERC-7579 module install/uninstall helpers. * * Handles the guardian-sig packing required by AAStarAirAccountV7: * installModule(moduleTypeId, module, guardianSigs ‖ moduleInitData) * uninstallModule(moduleTypeId, module, guardianSig1 ‖ guardianSig2 ‖ deInitData) */ declare class ModuleManager { private readonly provider; private readonly chainId; constructor(provider: ethers.JsonRpcProvider, chainId: number); /** * Encode calldata for installModule(). * Caller is responsible for submitting via UserOp (EntryPoint) or direct tx. */ encodeInstall(params: InstallModuleParams): string; /** * Encode calldata for uninstallModule(). * Always requires 2 guardian signatures. */ encodeUninstall(params: UninstallModuleParams): string; /** Check if a module is currently installed on the account. */ isInstalled(account: string, moduleTypeId: ModuleTypeId, module: string): Promise; /** Return the install hash for a guardian to sign (r5 format, includes moduleInitData hash). */ installHash(account: string, moduleTypeId: ModuleTypeId, module: string, moduleInitData?: string): string; /** Return the uninstall hash for guardians to sign. */ uninstallHash(account: string, moduleTypeId: ModuleTypeId, module: string): string; /** * Convenience: build install calldata for the standard M7 module set. * Uses pre-deployed Sepolia addresses. No guardian sigs required when * account threshold <= 40 (default for newly created accounts). */ encodeInstallDefaultModules(account: string): { compositeValidator: string; tierGuardHook: string; }; } interface GrantSessionParams { /** Account that owns the session */ account: string; /** The session key address (ephemeral EOA) */ sessionKey: string; /** Expiry unix timestamp (max 7 days from now) */ expiry: number; /** address(0) = any destination allowed */ contractScope?: string; /** bytes4(0) = any selector allowed */ selectorScope?: string; /** Owner signature over buildGrantHash() — omit if calling directly from account */ ownerSig?: string; } interface SessionInfo { expiry: number; contractScope: string; selectorScope: string; revoked: boolean; active: boolean; } interface AgentSessionConfig { expiry: number; velocityLimit: number; velocityWindow: number; spendToken: string; spendCap: bigint; callTargets: string[]; selectorAllowlist: string[]; } interface AgentSessionInfo extends AgentSessionConfig { revoked: boolean; callCount: bigint; windowStart: bigint; totalSpent: bigint; } /** * SessionKeyService — manage M6 (basic) and M7 (agent) session keys. * * M6 SessionKeyValidator (algId=0x08): * Simple time-limited ECDSA/P256 key with optional contract+selector scope. * Used for standard delegated actions (hot wallet, automated tasks). * * M7 AgentSessionKeyValidator (algId=0x09): * Rich session key for AI agents: velocity limits, spend caps, call allowlists, * hierarchical delegation (parent → sub-agent with scope narrowing). */ declare class SessionKeyService { private readonly provider; private readonly skValidator; private readonly askValidator; constructor(provider: ethers.JsonRpcProvider, sessionKeyValidatorAddress: string, agentSessionKeyValidatorAddress: string); /** * Build the hash that the account owner must sign to grant a session key. * Use grantSession() with this sig, or grantSessionDirect() from the account itself. */ buildGrantHash(params: Omit): Promise; /** Query an ECDSA session key state. */ getSession(account: string, sessionKey: string): Promise; /** Check if an ECDSA session is currently active. */ isSessionActive(account: string, sessionKey: string): Promise; /** * Encode calldata for grantSession() — submit via UserOp from the account. * ownerSig is the account owner's signature over buildGrantHash(). */ encodeGrantSession(params: GrantSessionParams): string; /** Encode calldata for revokeSession(). */ encodeRevokeSession(account: string, sessionKey: string): string; /** * Encode calldata for grantAgentSession(). * Must be called from the account (via UserOp or direct execute). * The contract uses msg.sender as the account — no account param needed. */ encodeGrantAgentSession(sessionKey: string, cfg: AgentSessionConfig): string; /** * Encode calldata for delegateSession() — sub-agent delegation. * The sub-agent config must be a strict subset of the parent session's scope. * Called by the parent session key (not the account owner). */ encodeDelegateSession(subKey: string, subCfg: AgentSessionConfig): string; /** Encode calldata for revokeAgentSession(). */ encodeRevokeAgentSession(sessionKey: string): string; /** Query agent session config + runtime state. */ getAgentSession(account: string, sessionKey: string): Promise; /** Check if an agent session is active (not expired, not revoked). */ isAgentSessionActive(account: string, sessionKey: string): Promise; /** Return the parent account of a delegated session key. */ getSessionKeyOwner(sessionKey: string): Promise; /** Return the parent key that delegated to subKey, or ZeroAddress if not delegated. */ getDelegatedBy(account: string, subKey: string): Promise; } type TierLevel = 1 | 2 | 3; interface GuardState { /** ETH daily limit in wei */ dailyLimit: bigint; /** ETH already spent today in wei */ todaySpent: bigint; /** ETH remaining for today in wei */ remaining: bigint; /** Current tier based on spent amount */ currentTier: TierLevel; /** Tier 1 max spend threshold in wei (single sig) */ tier1Limit: bigint; /** Tier 2 max spend threshold in wei (dual sig) */ tier2Limit: bigint; /** Minimum daily limit floor (cannot decrease below this) */ minDailyLimit: bigint; /** Guard contract address */ guardAddress: string; } interface TokenGuardState { token: string; todaySpent: bigint; dailyLimit: bigint; remaining: bigint; currentTier: TierLevel; tier1Limit: bigint; tier2Limit: bigint; } /** * GuardStateReader — F6: read AAStarGlobalGuard spending state. * * Enables UI components to show: * - Daily spend progress bar * - Current required tier (T1/T2/T3) for next transaction * - Per-token limits and remaining allowances */ declare class GuardStateReader { private readonly provider; constructor(provider: ethers.JsonRpcProvider); /** * Read the full ETH guard state for an account. * Returns null if the account has no guard (dailyLimit=0). */ getGuardState(accountAddress: string): Promise; /** * Read per-token guard state. * Returns null if the token is not configured on the guard. */ getTokenGuardState(accountAddress: string, token: string): Promise; /** * Determine the minimum tier required to send a given ETH amount. * Useful for showing "this transfer needs 2 signatures" before submission. */ requiredTierForAmount(accountAddress: string, amountWei: bigint): Promise; /** * Check if a given algorithm ID is approved on the guard. */ isAlgorithmApproved(accountAddress: string, algId: number): Promise; } /** * OAPD — One Account Per DApp address derivation (F7). * * Each DApp gets a unique counterfactual AirAccount address derived from: * salt = keccak256(owner ‖ dappId) * * This prevents DApps from correlating user activity across sites while * sharing the same underlying owner key and guardians. * * The OAPD address is a standard AirAccount clone — it has its own guard, * its own daily limits, and can be funded independently. */ interface OapdConfig { /** Account owner address */ owner: string; /** DApp identifier — use the DApp's domain or contract address */ dappId: string; /** Factory address (defaults to M7 Sepolia) */ factoryAddress?: string; /** * InitConfig for the OAPD account. * Typically lower daily limits than the main account. */ initConfig: { guardians: [string, string, string]; dailyLimit: bigint; approvedAlgIds: number[]; minDailyLimit: bigint; initialTokens: string[]; initialTokenConfigs: Array<{ tier1Limit: bigint; tier2Limit: bigint; dailyLimit: bigint; }>; }; } /** * Compute the numeric salt for an OAPD address. * salt = uint256(keccak256(abi.encodePacked(owner, dappId))) */ declare function computeOapdSalt(owner: string, dappId: string): bigint; /** * Predict the counterfactual OAPD address without deploying. * Uses the factory's getAddress() view function. */ declare function getOapdAddress(provider: ethers.JsonRpcProvider, config: OapdConfig): Promise; /** * Get the OAPD address and its ERC-7828 chain-qualified identifier. */ declare function getOapdAddressWithChainId(provider: ethers.JsonRpcProvider, config: OapdConfig): Promise<{ address: string; chainQualified: string; }>; /** * Check if an OAPD account has been deployed yet. */ declare function isOapdDeployed(provider: ethers.JsonRpcProvider, config: OapdConfig): Promise; /** * In-memory storage adapter — useful for testing and demos. * All data is lost when the process exits. */ declare class MemoryStorage implements IStorageAdapter { private accounts; private transfers; private paymasters; private blsConfig; getAccounts(): Promise; saveAccount(account: AccountRecord): Promise; findAccountByUserId(userId: string): Promise; updateAccount(userId: string, updates: Partial): Promise; saveTransfer(transfer: TransferRecord): Promise; findTransfersByUserId(userId: string): Promise; findTransferById(id: string): Promise; updateTransfer(id: string, updates: Partial): Promise; getPaymasters(userId: string): Promise; savePaymaster(userId: string, paymaster: PaymasterRecord): Promise; removePaymaster(userId: string, name: string): Promise; getBlsConfig(): Promise; updateSignerNodesCache(nodes: unknown[]): Promise; } /** * Local wallet signer — backs all users with a single private key. * Suitable for testing, demos, and single-tenant server setups. * * For multi-tenant production use, implement ISignerAdapter with * per-user key management (e.g., KMS, HSM, or encrypted database). */ declare class LocalWalletSigner implements ISignerAdapter { private readonly wallet; constructor(privateKey: string, provider?: ethers.Provider); getAddress(_userId: string): Promise; getSigner(_userId: string, _ctx?: PasskeyAssertionContext): Promise; ensureSigner(_userId: string): Promise<{ signer: ethers.Signer; address: string; }>; } export { ACCOUNT_ABI, AGENT_SESSION_KEY_VALIDATOR_ABI, AIRACCOUNT_ABI, AIRACCOUNT_ADDRESSES, AIRACCOUNT_FACTORY_ABI, AIR_ACCOUNT_COMPOSITE_VALIDATOR_ABI, AIR_ACCOUNT_DELEGATE_ABI, ALG_ID, AccountManager, type AccountRecord, type AgentSessionConfig, type AgentSessionInfo, type AirAccountVersion, BLSSignatureData, BLSSignatureService, type BlsConfigRecord, CALLDATA_PARSER_REGISTRY_ABI, ConsoleLogger, ENTRYPOINT_ABI_V6, ENTRYPOINT_ABI_V7_V8, ENTRYPOINT_ADDRESSES, ERC20_ABI, type EntryPointConfig, EntryPointVersion, type EntryPointVersionConfig, type EstimateGasParams, EthereumProvider, type ExecuteTransferParams, FACTORY_ABI_V6, FACTORY_ABI_V7_V8, FORCE_EXIT_MODULE_ABI, GLOBAL_GUARD_ABI, type GrantSessionParams, GuardChecker, type GuardState, GuardStateReader, GuardStatus, type ILogger, type ISignerAdapter, type IStorageAdapter, type InstallModuleParams, type KmsBeginAuthenticationRequest, type KmsBeginAuthenticationResponse, type KmsBeginRegistrationRequest, type KmsBeginRegistrationResponse, type KmsCompleteRegistrationRequest, type KmsCompleteRegistrationResponse, type KmsCreateKeyResponse, type KmsDescribeKeyResponse, type KmsKeyStatusResponse, KmsManager, type KmsSignHashResponse, KmsSigner, type LegacyPasskeyAssertion, LocalWalletSigner, MODULE_TYPE, MemoryStorage, ModuleManager, type ModuleTypeId, type OapdConfig, PackedUserOperation, type PasskeyAssertionContext, PaymasterManager, PaymasterPriceStalenessError, type PaymasterRecord, PreCheckResult, SESSION_KEY_VALIDATOR_ABI, type ServerConfig, type SessionInfo, SessionKeyService, SilentLogger, TIER_GUARD_HOOK_ABI, TierConfig, TierLevel$1 as TierLevel, type TokenBalance, type TokenGuardState, type TokenInfo, TokenService, TransferManager, type TransferRecord, type TransferResult, type UninstallModuleParams, UserOperation, VALIDATOR_ABI, WalletManager, YAAAServerClient, buildInstallModuleHash, buildUninstallModuleHash, computeOapdSalt, getOapdAddress, getOapdAddressWithChainId, isOapdDeployed, sepoliaV07Config, validateConfig };