import { type PublicClient, type Chain, type Transport } from 'viem'; import { type SupportedChainName, type AzethContractAddresses, type RegistryEntry, type DiscoveryParams, type PaymentAgreement, type MessageHandler, type OnChainOpinion, type WeightedReputation, type ActiveOpinion, type OpinionEntry, type XMTPConfig, type XMTPConversation, type XMTPMessage } from '@azeth/common'; import { type CreateAccountParams, type CreateAccountResult } from './account/create.js'; import { type BalanceResult } from './account/balance.js'; import type { AggregatedBalanceResult } from '@azeth/common'; import { type TransferParams, type TransferResult } from './account/transfer.js'; import { type HistoryParams, type HistoryResult } from './account/history.js'; import { type DepositParams, type DepositResult } from './account/deposit.js'; import { type RegisterParams, type RegisterResult, type MetadataUpdate } from './registry/register.js'; import { type Fetch402Options, type Fetch402Result } from './payments/x402.js'; import { type SmartFetch402Options, type SmartFetch402Result } from './payments/smart-fetch.js'; import { type CreateAgreementParams, type AgreementResult } from './payments/agreements.js'; import { type SendMessageParams } from './messaging/xmtp.js'; import { AzethEventEmitter, type AzethEventName, type AzethEventListener, type AzethEventMap } from './events/emitter.js'; import { BudgetManager, type BudgetConfig } from './payments/budget.js'; import type { PaymasterPolicy } from './utils/paymaster.js'; import { type L2UsdDeltaProof } from './crosschain/proof-builder.js'; import { type ProveL2UsdDeltaResult } from './crosschain/prove.js'; import { type ProvenDeltaResult, type CrossChainReputationResult } from './crosschain/read.js'; export interface AzethKitConfig { /** The account owner's private key */ privateKey: `0x${string}`; /** Chain to connect to */ chain: SupportedChainName; /** Custom RPC URL (optional) */ rpcUrl?: string; /** Azeth server URL for indexed data and message relay */ serverUrl?: string; /** ERC-4337 bundler URL for UserOperation submission. * Required for state-changing smart account operations (transfers, payments, reputation). * Resolution: explicit value > AZETH_BUNDLER_URL env > SUPPORTED_CHAINS default > error. * Get a free key at https://dashboard.pimlico.io or https://portal.cdp.coinbase.com. */ bundlerUrl?: string; /** ERC-4337 paymaster URL for gas sponsorship (optional). * When provided, the paymaster will sponsor gas for UserOperations. * Resolution: explicit value > AZETH_PAYMASTER_URL env > SUPPORTED_CHAINS default. * When not configured, UserOps use self-paid gas (no single point of failure). */ paymasterUrl?: string; /** Client-side sponsorship policy for paymaster gas sponsorship (optional). * Defense-in-depth layer on top of the paymaster's server-side policies. * Only applies when a paymaster is configured. */ paymasterPolicy?: PaymasterPolicy; /** Override contract addresses (merged with chain defaults) */ contractAddresses?: Partial; /** XMTP messaging configuration (optional — messaging lazy-initializes on first use) */ xmtp?: XMTPConfig; /** Budget configuration for x402 payments. * When provided, enables reputation-aware spending limits. */ budget?: BudgetConfig; /** Optional guardian co-signing key. * Used to derive the guardian address for account creation and for interactive XMTP approval. * Only auto-signs UserOperations when `guardianAutoSign` is also set to `true`. * The address derived from this key must match the guardian set in the account's guardrails. */ guardianKey?: `0x${string}`; /** When true AND guardianKey is set, the SDK auto-appends a guardian co-signature * to every UserOperation, enabling operations that exceed standard spending limits. * Must be explicitly set to `true` — defaults to `false` (guardian must confirm via XMTP). */ guardianAutoSign?: boolean; /** L1 chain hosting TrustL2Reader (cross-chain reputation verification). * Default: 'ethereumSepolia' when chain ∈ {baseSepolia, ethereumSepolia}, else 'ethereum'. */ l1Chain?: SupportedChainName; /** RPC for the L1 verification chain. Default: SUPPORTED_CHAINS[l1Chain].rpcDefault. */ l1RpcUrl?: string; /** ARCHIVE RPC for the L2 (eth_getProof at the ~7-day-old anchor block — public RPCs reject this). * Serves the kit's own chain. On a kit connected to the L1 chain (which has no L2 of its own), * an explicit value here serves the L2 named by the `chainId` passed to * buildCrossChainProof/proveCrossChainReputation — the endpoint's eth_chainId is verified * against the requested chain before any proof data is read. * Default: config.rpcUrl, then chain default; proof building will likely fail without a true archive endpoint. */ l2ArchiveRpcUrl?: string; } /** Simplified account creation — auto-fills owner, guardrails, and wraps into registry. * Use this when you want sensible defaults without manual guardrail configuration. */ export interface SimpleCreateAccountParams { /** Display name for the trust registry entry */ name: string; /** Entity type: 'agent', 'service', or 'infrastructure' */ entityType: 'agent' | 'service' | 'infrastructure'; /** Human-readable description */ description: string; /** Service capabilities for discovery (e.g., ['weather-data', 'price-feed']) */ capabilities?: string[]; /** Service endpoint URL */ endpoint?: string; /** Max per-transaction amount in USD (default: 100) */ maxTxAmountUSD?: number; /** Daily spending limit in USD (default: 1000) */ dailySpendLimitUSD?: number; /** Guardian address for co-signing high-value txs (default: self-guardian) */ guardian?: `0x${string}`; /** Emergency withdrawal destination (default: owner) */ emergencyWithdrawTo?: `0x${string}`; } /** Simplified opinion — rating from -100 to 100, auto-converts to WAD format */ export interface SimpleOpinion { /** Target service's ERC-8004 token ID */ serviceTokenId: bigint; /** Rating from -100 to 100 (supports decimals like 85.5) */ rating: number; /** Primary categorization tag (default: 'quality') */ tag1?: string; /** Secondary categorization tag (default: '') */ tag2?: string; /** Service endpoint being rated */ endpoint?: string; } /** Result from pay() — fetch402 result with auto-parsed response body */ export interface PayResult { /** Parsed response body (JSON object or raw text string) */ data: unknown; /** Raw HTTP response (body already consumed) */ response: Response; /** Whether an x402 payment was made */ paymentMade: boolean; /** Payment amount in token base units (e.g., USDC with 6 decimals) */ amount?: bigint; /** On-chain transaction hash of the payment */ txHash?: `0x${string}`; /** Response time in milliseconds */ responseTimeMs?: number; /** Whether on-chain settlement was verified */ settlementVerified: boolean; /** How access was obtained — see Fetch402Result.paymentMethod. * 'agreement' = access granted via an active on-chain payment agreement. */ paymentMethod: 'x402' | 'smart-account' | 'session' | 'agreement' | 'none'; } /** AzethKit -- Trust Infrastructure SDK for the Machine Economy * * Provides Phase 0 methods for machine participants: * - create: Deploy a smart account + trust registry entry * - transfer: Send ETH or tokens to another participant * - getBalance: Check account balances * - getHistory: Get transaction history * - fetch402: Pay for x402-gated services (with budget enforcement) * - publishService: Register on the trust registry * - discoverServices: Find services by capability + reputation * - createPaymentAgreement: Set up recurring payments * - submitOpinion: Submit reputation opinion for a service * - getWeightedReputation: Get payment-weighted reputation for an agent * - getNetPaid: Get net payment delta with a counterparty * - getActiveOpinion: Check active opinion for an agent * - sendMessage: Send XMTP encrypted messages * - onMessage: Listen for incoming messages * - canReach: Check if an address is reachable on XMTP * * Events: on('beforePayment'), on('afterPayment'), on('paymentError'), * on('beforeTransfer'), on('afterTransfer'), on('transferError') */ export declare class AzethKit { readonly address: `0x${string}`; readonly chainName: SupportedChainName; readonly addresses: AzethContractAddresses; readonly publicClient: PublicClient; private readonly walletClient; readonly serverUrl: string; /** All smart account addresses owned by this EOA, resolved from factory. * null until createAccount() is called or resolveSmartAccount() resolves them. */ private _smartAccounts; /** H-2 fix: Private key stored as Uint8Array for proper zeroing in destroy() */ private _privateKeyBytes; /** MEDIUM-7 fix: Track destroyed state to prevent use-after-destroy. * H-6 fix (Audit #8): All state-changing methods now check this flag. */ private _destroyed; private readonly _xmtpConfig; private _messaging; private _messagingInitPromise; /** Event emitter for lifecycle hooks */ readonly events: AzethEventEmitter; /** Budget manager for x402 spending limits */ readonly budget: BudgetManager; /** ERC-4337 bundler URL for UserOperation submission */ private readonly _bundlerUrl; /** ERC-4337 paymaster URL for gas sponsorship */ private readonly _paymasterUrl; /** Client-side paymaster sponsorship policy */ private readonly _paymasterPolicy; /** Guardian co-signing key — used for address derivation and optional auto-signing */ private readonly _guardianKey; /** When true, auto-append guardian co-signature to every UserOp */ private readonly _guardianAutoSign; /** Cached SmartAccountClient instances keyed by smart account address */ private readonly _smartAccountClients; /** Cache of per-account self-guardian detection (guardian == owner EOA). * Guardian changes require a 24h on-chain timelock, so a per-instance cache * cannot go stale within a kit's lifetime in any practical scenario. */ private readonly _selfGuardianCache; /** L1 chain hosting TrustL2Reader (cross-chain reputation verification) */ private readonly _l1ChainName; /** Resolved RPC URL for the L1 verification chain */ private readonly _l1RpcUrl; /** Resolved ARCHIVE RPC URL for L2 proof building (eth_getProof at the anchor block) */ private readonly _l2ArchiveRpcUrl; /** Whether `config.l2ArchiveRpcUrl` was set explicitly (vs falling back to rpcUrl/chain default). * Only an explicit value may serve a chain other than the kit's own (L1-connected kits). */ private readonly _l2ArchiveRpcUrlExplicit; /** Explicit trustL2Reader override from config.contractAddresses (applies to the L1 lookup) */ private readonly _trustL2ReaderOverride; /** Lazily created L1 public client (TrustL2Reader reads + proof simulation) */ private _l1PublicClient; /** Lazily created L1 wallet client (plain-EOA proof broadcast — requires L1 ETH) */ private _l1WalletClient; /** Lazily created L2 archive clients (proof building at the anchor block), keyed by L2 chain id — * per-chain so an explicit `chainId` never silently reads proof data from the wrong chain */ private readonly _l2ProofClients; private constructor(); /** Create an AzethKit instance from a private key * * This connects to the chain and sets up clients for the owner's address. * Call publishService() to register on the trust registry if not already registered. */ static create(config: AzethKitConfig): Promise; /** Subscribe to a lifecycle event. Returns an unsubscribe function. */ on(event: K, listener: AzethEventListener): () => void; /** Subscribe to a lifecycle event for a single firing. */ once(event: K, listener: AzethEventListener): () => void; /** H-6 fix (Audit #8): Guard all state-changing methods against use-after-destroy. * After destroy(), the walletClient may still hold a working key copy in memory. * This prevents accidental operations on a "destroyed" instance. */ private _requireNotDestroyed; /** The first (default) smart account address owned by this EOA, or null if not yet resolved */ get smartAccount(): `0x${string}` | null; /** All smart account addresses owned by this EOA, or null if not yet resolved */ get smartAccounts(): readonly `0x${string}`[] | null; /** Resolve all smart account addresses from the on-chain factory. * Queries factory.getAccountsByOwner(ownerAddress). * Caches the result for subsequent calls. * * @returns Array of smart account addresses owned by this EOA */ getSmartAccounts(): Promise; /** Resolve the default (first) smart account address from the on-chain factory. * Caches the result for subsequent calls. * * @throws AzethError if no account is found for this owner */ resolveSmartAccount(): Promise<`0x${string}`>; /** Set the active smart account for subsequent operations (payments, transfers, etc.). * Reorders the internal accounts array so the specified address becomes the default. * All methods that use `resolveSmartAccount()` or `_smartAccounts[0]` will use it. * * @param address - Address of one of your smart accounts (must already be in the accounts list) * @throws AzethError if no accounts are loaded or the address is not found */ setActiveAccount(address: `0x${string}`): void; /** Deploy a new Azeth smart account via the AzethFactory v11 (one-call setup). * * Single atomic transaction: deploys ERC-1967 proxy, installs all 4 modules, * registers on ERC-8004 trust registry (optional), and permanently revokes factory access. * * Accepts either full params (CreateAccountParams) or simplified params * (SimpleCreateAccountParams) that auto-fill owner, guardrails, and registry. * * @example Simplified (recommended for most cases): * ```typescript * await agent.createAccount({ * name: 'WeatherOracle', * entityType: 'service', * description: 'Real-time weather data', * capabilities: ['weather-data'], * endpoint: 'http://localhost:3402', * }); * ``` * * @example Full control: * ```typescript * await agent.createAccount({ * owner: agent.address, * guardrails: { maxTxAmountUSD: 500n * 10n**18n, ... }, * registry: { name: 'WeatherOracle', entityType: 'service', ... }, * }); * ``` */ createAccount(params: CreateAccountParams | SimpleCreateAccountParams): Promise; /** Compute the deterministic address for an account without deploying */ getAccountAddress(salt: `0x${string}`): Promise<`0x${string}`>; /** Transfer ETH or ERC-20 tokens from a smart account to another address. * * Executes via AzethAccount.execute() so transfers go through the smart account, * not the EOA directly. Defaults to the first smart account if none specified. * * @param params - Transfer parameters (to, amount, token) * @param fromAccount - Optional: specific smart account to transfer from (defaults to first) */ transfer(params: TransferParams, fromAccount?: `0x${string}`): Promise; /** Get ETH and token balances for the smart account (primary) and EOA (gas). * * @param forAccount - Optional: specific smart account to check (defaults to first) */ getBalance(forAccount?: `0x${string}`): Promise; /** Get balances for ALL accounts (EOA + all smart accounts) with USD values. * Single RPC call via AzethFactory.getOwnerBalancesAndUSD(). * * Returns: EOA at index 0, smart accounts at index 1+. * Each account has per-token balances with USD values and a total. * Grand total USD sums across all accounts. */ getAllBalances(): Promise; /** Get transaction history for a smart account. * * @param params - History params (limit, offset) * @param forAccount - Optional: specific smart account (defaults to first) */ getHistory(params?: HistoryParams, forAccount?: `0x${string}`): Promise; /** Deposit ETH or ERC-20 tokens from the owner EOA to a self-owned smart account. * * SECURITY: On-chain validation ensures the target is: * 1. A real Azeth smart account (factory.isAzethAccount) * 2. Owned by this EOA (factory.getOwnerOf) */ deposit(params: DepositParams): Promise; /** Deposit ETH or ERC-20 tokens to this account's smart account. * Convenience wrapper that auto-resolves the smart account address. */ depositToSelf(params: Omit): Promise; /** Update the token whitelist on the GuardianModule. * Tokens must be whitelisted for executor-module operations (e.g., PaymentAgreementModule). * * @param token - Token address (use 0x0...0 for native ETH) * @param allowed - true to whitelist, false to remove * @param account - Optional: specific smart account (defaults to first) */ setTokenWhitelist(token: `0x${string}`, allowed: boolean, account?: `0x${string}`): Promise<`0x${string}`>; /** Update the protocol whitelist on the GuardianModule. * Protocols must be whitelisted for executor-module operations. * * @param protocol - Protocol/contract address * @param allowed - true to whitelist, false to remove * @param account - Optional: specific smart account (defaults to first) */ setProtocolWhitelist(protocol: `0x${string}`, allowed: boolean, account?: `0x${string}`): Promise<`0x${string}`>; /** Fetch a URL, automatically paying x402 requirements. * * If the service returns 402, the SDK signs an ERC-3009 payment authorization, * retries the request with the payment proof. * * Budget checking: If a BudgetManager is configured (default), the payment amount is * checked against reputation-aware spending tiers before signing. * * @param url - Service URL to fetch * @param options - Fetch options including budget overrides * @param serviceReputation - Optional reputation score (0-100) for budget tier lookup */ fetch402(url: string, options?: Fetch402Options, serviceReputation?: number): Promise; /** Discover, pay, and rate a service in one call. * * Given a capability (e.g., "price-feed"), discovers the best-reputation service, * pays for it via x402, falls back to alternatives on failure, and submits * reputation feedback automatically. * * Budget lock: Held for the entire retry sequence to prevent concurrent calls * from exhausting budget between retries. * * Feedback lifecycle: Feedback is awaited (not fire-and-forget) so that callers * like the MCP tool can safely call destroy() after this method returns without * killing in-flight UserOps. Feedback errors are caught and never propagate. * * @param capability - Service capability to discover (e.g., 'price-feed', 'market-data') * @param options - Smart fetch options (minReputation, maxRetries, autoFeedback, etc.) */ smartFetch402(capability: string, options?: SmartFetch402Options): Promise; /** Submit reputation feedback for smartFetch402 routing. * Errors are swallowed — this must never fail the payment flow. * * opinionURI: empty string (auto-generated opinions have no external URI) * opinionHash: zero bytes32 (no off-chain content to hash) */ private _submitSmartFeedback; /** Pay for an x402-gated service and return parsed response data. * * Convenience wrapper around fetch402 that auto-parses the response body. * Returns JSON objects for JSON responses, raw text for others. * * @param url - Service URL to fetch and pay for * @param options - Fetch options (method, body, maxAmount, etc.) * @returns PayResult with parsed `data` field * * @example * ```typescript * const result = await agent.pay('https://api.example.com/data'); * console.log(result.data); // parsed JSON response * ``` */ pay(url: string, options?: Fetch402Options): Promise; /** Register on the ERC-8004 trust registry, or update metadata if already registered. * * If the smart account is already registered (e.g., via createAccount with registry params), * this method gracefully falls back to updating the metadata fields instead of reverting. */ publishService(params: RegisterParams): Promise; /** Discover services by capability and reputation */ discoverServices(params: DiscoveryParams): Promise; /** Update metadata for this account's trust registry entry. * * @param key - Metadata key (e.g., 'endpoint', 'description', 'capabilities') * @param value - Metadata value as string (will be hex-encoded internally) * @returns Transaction hash */ updateServiceMetadata(key: string, value: string): Promise<`0x${string}`>; /** Update multiple metadata fields in a single batch transaction. * * @param updates - Array of { key, value } pairs to update * @returns Transaction hash of the batch UserOp */ updateServiceMetadataBatch(updates: MetadataUpdate[]): Promise<`0x${string}`>; /** Create a recurring payment agreement */ createPaymentAgreement(params: CreateAgreementParams): Promise; /** Find an active payment agreement with a specific payee. * Searches from newest to oldest, returning the first match. * * @param payee - The payee address to search for * @param token - Optional token address to filter by * @returns The first matching active agreement, or null */ findAgreementWithPayee(payee: `0x${string}`, token?: `0x${string}`): Promise; /** Get details of a specific payment agreement */ getAgreement(agreementId: bigint, account?: `0x${string}`): Promise; /** Execute a due payment agreement. * * Auto-detects own vs foreign account: * - Own account: executes via UserOp from the payer's smart account (self-execution) * - Foreign account: executes as keeper — routes via the caller's own smart account * or falls back to direct EOA call if the caller has no smart account */ executeAgreement(agreementId: bigint, account?: `0x${string}`): Promise<`0x${string}`>; /** Cancel an active payment agreement. Only the payer can cancel. * @param account - Optional: specific smart account that owns the agreement (defaults to first) */ cancelAgreement(agreementId: bigint, account?: `0x${string}`): Promise<`0x${string}`>; /** Get the total number of agreements for an account */ getAgreementCount(account?: `0x${string}`): Promise; /** Check if a payment agreement can be executed right now */ canExecutePayment(agreementId: bigint, account?: `0x${string}`): Promise<{ executable: boolean; reason: string; }>; /** Get the next execution timestamp for a payment agreement */ getNextExecutionTime(agreementId: bigint, account?: `0x${string}`): Promise; /** Get comprehensive agreement data in a single RPC call. * Combines agreement details + executability + isDue + nextExecutionTime + count. */ getAgreementData(agreementId: bigint, account?: `0x${string}`): Promise<{ agreement: PaymentAgreement; executable: boolean; reason: string; isDue: boolean; nextExecutionTime: bigint; count: bigint; }>; /** Submit a reputation opinion for an agent via the ReputationModule. * * Accepts either full OnChainOpinion params or simplified SimpleOpinion with a rating. * Requires a positive net USD payment from this account to the target agent. * * @example Simplified: * ```typescript * await agent.submitOpinion({ * serviceTokenId: service.tokenId, * rating: 85, // -100 to 100 * tag1: 'quality', // optional * }); * ``` * * @example Full control: * ```typescript * await agent.submitOpinion({ * agentId: 1024n, * value: 85n * 10n**18n, * valueDecimals: 18, * tag1: 'quality', tag2: 'x402', * endpoint: 'https://...', opinionURI: '', opinionHash: '0x...', * }); * ``` */ submitOpinion(opinion: OnChainOpinion | SimpleOpinion): Promise<`0x${string}`>; /** Get payment-weighted reputation for an agent. * * @param agentId - Target agent's ERC-8004 token ID * @param raters - Optional list of rater addresses. If omitted, defaults to empty array. */ getWeightedReputation(agentId: bigint, raters?: `0x${string}`[]): Promise; /** Get the net payment between this account and a counterparty. * * - **No token** (default): Returns total net paid in 18-decimal USD, aggregated across * all tokens via the on-chain oracle. Always >= 0. This is what the contract uses * to gate reputation opinions. * - **With token**: Returns the signed per-token delta. Positive means this account * has paid more; negative means the counterparty has paid more. * * @param counterparty - The other account address * @param token - Optional token address. Omit for total USD. Use 0x0 for native ETH. */ getNetPaid(counterparty: `0x${string}`, token?: `0x${string}`): Promise; /** Get active opinion state for this account's opinion on an agent. * * @param agentId - Target agent's ERC-8004 token ID * @param account - Smart account address to query. Defaults to first smart account. * @returns Active opinion index and existence flag */ getActiveOpinion(agentId: bigint, account?: `0x${string}`): Promise; /** Read a single opinion entry from the on-chain registry */ readOpinion(agentId: bigint, clientAddress: `0x${string}`, opinionIndex: bigint): Promise; /** Build a complete MPT storage-proof bundle for the L2 net-USD payment delta * between this account and a counterparty, against the current rollup anchor. * * Read-only (L1 reads + L2 archive reads); requires an archive-capable L2 RPC * (`l2ArchiveRpcUrl`) because the anchor block is ~7 days old. * * @param params.counterparty - The other side of the pair * @param params.account - Defaults to this kit's resolved smart account * @param params.chainId - L2 chain id; defaults to the kit's current chain. An explicit * id resolves its own archive client (see `l2ArchiveRpcUrl`) and the endpoint's * eth_chainId is verified against it — a mismatch throws INVALID_INPUT rather than * silently reading proof data from the wrong chain. */ buildCrossChainProof(params: { counterparty: `0x${string}`; account?: `0x${string}`; chainId?: bigint; }): Promise; /** Prove this account's L2 payment relationship with a counterparty on L1. * * Builds the proof (unless a pre-built `proof` is supplied) and SIMULATES it. * Only submits an L1 transaction when `broadcast: true` — a plain, permissionless * EOA transaction paid in L1 ETH by the owner key (no UserOp/guardian involvement). * * @param params.broadcast - default false (simulate only) * @param params.proof - pre-built bundle from buildCrossChainProof (skips the builder) */ proveCrossChainReputation(params: { counterparty: `0x${string}`; account?: `0x${string}`; chainId?: bigint; broadcast?: boolean; proof?: L2UsdDeltaProof; }): Promise; /** Get the L1-proven net USD `from` has paid `to` on one L2 chain (clamped ≥ 0). * @param chainId - defaults to the kit's current L2 chain id */ getCrossChainNetPaid(from: `0x${string}`, to: `0x${string}`, chainId?: bigint): Promise; /** Get the L1-proven net USD `from` has paid `to` aggregated across L2 chains. * @param chainIds - defaults to all chains registered on the TrustL2Reader */ getCrossChainAggregateNetPaid(from: `0x${string}`, to: `0x${string}`, chainIds?: bigint[]): Promise; /** Get the cached proven delta for a pair on one L2 chain (any input order). * @param chainId - defaults to the kit's current L2 chain id */ getCrossChainProvenDelta(accountA: `0x${string}`, accountB: `0x${string}`, chainId?: bigint): Promise; /** Composite cross-chain reputation read: per-registered-chain breakdown + total. */ getCrossChainReputation(from: `0x${string}`, to: `0x${string}`): Promise; /** Send an encrypted message via XMTP. * * Lazy-initializes the XMTP client on first call. * * @param params - Message parameters (to, content) * @returns The conversation ID */ sendMessage(params: SendMessageParams): Promise; /** Listen for incoming XMTP messages. * * The handler is registered immediately. If the XMTP client has not been * initialized yet, it will be initialized asynchronously when the first * handler is registered. * * @param handler - Async function called for each incoming message * @returns Unsubscribe function */ onMessage(handler: MessageHandler): () => void; /** Check if an address is reachable on the XMTP network. * * @param address - Ethereum address to check * @returns Whether the address can receive XMTP messages */ canReach(address: `0x${string}`): Promise; /** List active XMTP conversations. * * Lazy-initializes the XMTP client on first call. * * @returns Array of conversation summaries with peer address and creation time */ getConversations(): Promise; /** Read recent messages from a conversation with a peer. * * @param peerAddress - Ethereum address of the conversation peer * @param limit - Max messages to return (default 20, max 100) * @returns Array of messages sorted by timestamp */ getMessages(peerAddress: `0x${string}`, limit?: number): Promise; /** Get a fetch function that automatically adds ERC-8128 auth headers */ getSignedFetch(): typeof fetch; /** Clean up resources (XMTP agent, timers, etc.) and zero sensitive material. * IMPORTANT: Call this when done with the AzethKit instance to zero private key * bytes from memory. Use in a try/finally block for safety. */ destroy(): Promise; /** Get or create a SmartAccountClient for a specific smart account address. * * Uses permissionless's createSmartAccountClient with a custom viem SmartAccount * implementation that routes all state-changing calls through ERC-4337 UserOperations. * * Lazily created and cached per smart account address. */ private _getSmartAccountClient; /** True when the account's on-chain guardian equals the owner EOA (self-guardian). * Cached per account; a failed read conservatively returns false (previous behavior). */ private _isSelfGuardianAccount; /** True when this kit can satisfy a guardian co-signature requirement for the * account — either an explicit auto-sign guardian key or the self-guardian * fast path. Used by pre-flight checks to decide whether guardian-tier * requirements are blocking or satisfiable. */ private _guardianCosignAvailable; /** Resolve the L2 chain id for cross-chain operations. * Defaults to the kit's current chain; requires an explicit chainId when the * kit itself is connected to the L1 verification chain. */ private _resolveCrossChainChainId; /** Lazily create the L1 public client used for TrustL2Reader reads + proof simulation */ private _getL1PublicClient; /** Lazily create the L1 wallet client (owner EOA on the L1 chain) for proof broadcast. * Plain-EOA transactions only — must hold L1 ETH for gas. */ private _getL1WalletClient; /** Lazily create (and cache per chain id) the L2 archive client used for proof building * at the anchor block. * * RPC resolution per requested chain: * - kit's own chain → configured `_l2ArchiveRpcUrl` (explicit > rpcUrl > chain default); * - another supported chain, kit connected to the L1 with an EXPLICIT l2ArchiveRpcUrl → * that URL (the L1 kit has no L2 of its own, so the knob can only mean the target L2); * - another supported chain otherwise → that chain's own public default (the kit's * archive URL serves the kit's chain and must never be reused for a different one); * - unsupported chain id → INVALID_INPUT instead of silently querying the wrong chain. * * Callers must still verify the endpoint via _verifyL2ArchiveChainId before reading * proof data. */ private _getL2ProofClient; /** Fail-closed guard: verify the L2 archive RPC actually serves the requested chain id * (eth_chainId) before any proof data is read from it. Without this, a mispointed * archive endpoint surfaces as a confusing ANCHOR_MISMATCH/NETWORK_ERROR deep inside * proof building instead of a clear configuration error. */ private _verifyL2ArchiveChainId; /** Resolve the TrustL2Reader address on the L1 verification chain. * Resolution: config.contractAddresses.trustL2Reader → AZETH_CONTRACTS[l1Chain].trustL2Reader. * Never `this.addresses` (the kit's own chain record — '' on L2s). */ private _getTrustL2ReaderAddress; /** Get or create the XMTPClient instance (without initialization) */ private _getOrCreateMessaging; /** Ensure the XMTP client is initialized. Returns the ready client. */ private _ensureMessaging; } //# sourceMappingURL=client.d.ts.map