kontext-sdk 0.9.0 → 0.10.0

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/README.md CHANGED
@@ -231,6 +231,35 @@ const ctx = Kontext.init({
231
231
  // Call ctx.flush() to write, ctx.restore() to reload
232
232
  ```
233
233
 
234
+ ## Auto-Instrumentation (viem)
235
+
236
+ Run `npx kontext init` to generate a config file, then wrap your viem client — every stablecoin transfer is automatically logged.
237
+
238
+ ```bash
239
+ npx kontext init
240
+ # Wizard asks: project name, agent ID, wallets to monitor, tokens, chains, mode
241
+ # Creates kontext.config.json
242
+ ```
243
+
244
+ ```typescript
245
+ import { Kontext, withKontextCompliance } from 'kontext-sdk';
246
+ import { createWalletClient, http } from 'viem';
247
+ import { base } from 'viem/chains';
248
+
249
+ const kontext = Kontext.init(); // reads kontext.config.json
250
+ const client = withKontextCompliance(
251
+ createWalletClient({ chain: base, transport: http() }),
252
+ kontext,
253
+ );
254
+
255
+ // Every USDC/USDT/DAI/EURC transfer now auto-logged with compliance proof
256
+ await client.sendTransaction({ to: USDC_ADDRESS, data: transferCalldata });
257
+ ```
258
+
259
+ **Two interception layers:**
260
+ - **Code wrap:** `withKontextCompliance()` intercepts `sendTransaction`/`writeContract` calls. Can block pre-send if non-compliant.
261
+ - **Chain listener:** SDK watches monitored wallet addresses on-chain for ERC-20 Transfer events — catches ALL outgoing stablecoin transfers regardless of origin.
262
+
234
263
  ## Pluggable Sanctions Screening
235
264
 
236
265
  Multi-provider screening with consensus strategies. Bring your own API keys, or use the built-in OFAC SDN list at zero cost.
package/dist/index.d.mts CHANGED
@@ -434,6 +434,24 @@ interface KontextConfig {
434
434
  * $10K CTR, $50K large transaction).
435
435
  */
436
436
  policy?: PolicyConfig;
437
+ /**
438
+ * Default agent ID for verify/log calls when not specified per-call.
439
+ * Set automatically when loading from kontext.config.json.
440
+ */
441
+ agentId?: string;
442
+ /**
443
+ * Wallet monitoring configuration. When provided, SDK watches these
444
+ * addresses on-chain for stablecoin transfers and auto-calls verify().
445
+ * Requires viem as a peer dependency.
446
+ */
447
+ walletMonitoring?: WalletMonitoringConfig;
448
+ /**
449
+ * Viem interceptor mode for withKontextCompliance() (default: 'post-send').
450
+ * - 'post-send': verify() runs after tx succeeds, never blocks
451
+ * - 'pre-send': verify() runs before tx, throws if non-compliant
452
+ * - 'both': pre-send screening + post-send full verify
453
+ */
454
+ interceptorMode?: 'post-send' | 'pre-send' | 'both';
437
455
  }
438
456
  /** Screening configuration for pluggable multi-provider sanctions screening */
439
457
  interface ScreeningConfig {
@@ -473,6 +491,15 @@ interface PolicyConfig {
473
491
  /** When true, refuse verify() if no screening provider is configured (default: false) */
474
492
  requireScreening?: boolean;
475
493
  }
494
+ /** Wallet monitoring configuration for on-chain event listening */
495
+ interface WalletMonitoringConfig {
496
+ /** Wallet addresses to watch for outgoing stablecoin transfers */
497
+ wallets: string[];
498
+ /** RPC endpoints per chain (required for on-chain listening) */
499
+ rpcEndpoints: Partial<Record<Chain, string>>;
500
+ /** Polling interval in ms for HTTP transports (default: 12000) */
501
+ pollingIntervalMs?: number;
502
+ }
476
503
  /**
477
504
  * Interface for metadata validation. Compatible with Zod schemas and any
478
505
  * validator that implements a `parse` method.
@@ -1713,6 +1740,45 @@ declare class FeatureFlagManager {
1713
1740
  private triggerBackgroundRefresh;
1714
1741
  }
1715
1742
 
1743
+ /** Minimal Kontext interface needed by the monitor */
1744
+ interface KontextForMonitor {
1745
+ verify(input: VerifyInput): Promise<VerifyResult>;
1746
+ }
1747
+ /**
1748
+ * Watches monitored wallets on-chain for stablecoin Transfer events.
1749
+ * Uses viem's watchEvent with HTTP polling (works with any RPC endpoint).
1750
+ */
1751
+ declare class WalletMonitor {
1752
+ private readonly kontext;
1753
+ private readonly config;
1754
+ private readonly agentId;
1755
+ private readonly tokens;
1756
+ private readonly unwatchers;
1757
+ private running;
1758
+ /** Shared dedup set — tracks recently verified txHashes (populated by both layers) */
1759
+ readonly verifiedTxHashes: Set<string>;
1760
+ private cleanupTimer;
1761
+ private readonly txTimestamps;
1762
+ constructor(kontext: KontextForMonitor, config: WalletMonitoringConfig, options?: {
1763
+ agentId?: string;
1764
+ tokens?: Token[];
1765
+ });
1766
+ /**
1767
+ * Mark a txHash as already verified (called by the viem interceptor layer).
1768
+ * The monitor will skip this tx if it later sees it on-chain.
1769
+ */
1770
+ markVerified(txHash: string): void;
1771
+ /**
1772
+ * Start watching all configured chains for stablecoin transfers.
1773
+ * Dynamically imports viem — requires viem as a peer dependency.
1774
+ */
1775
+ start(): Promise<void>;
1776
+ /** Stop all watchers and cleanup */
1777
+ stop(): void;
1778
+ isRunning(): boolean;
1779
+ private handleTransferLog;
1780
+ }
1781
+
1716
1782
  /** Entity type for an agent identity */
1717
1783
  type EntityType = 'individual' | 'organization' | 'bot' | 'unknown';
1718
1784
  /** KYC verification status */
@@ -2337,6 +2403,7 @@ declare class Kontext {
2337
2403
  private readonly trustScorer;
2338
2404
  private readonly anomalyDetector;
2339
2405
  private readonly screeningAggregator;
2406
+ private walletMonitor;
2340
2407
  private provenanceManager;
2341
2408
  private identityRegistry;
2342
2409
  private walletClusterer;
@@ -2373,7 +2440,7 @@ declare class Kontext {
2373
2440
  * });
2374
2441
  * ```
2375
2442
  */
2376
- static init(config: KontextConfig): Kontext;
2443
+ static init(config?: KontextConfig): Kontext;
2377
2444
  /**
2378
2445
  * Get the current operating mode.
2379
2446
  */
@@ -2863,7 +2930,12 @@ declare class Kontext {
2863
2930
  */
2864
2931
  getFeatureFlagManager(): FeatureFlagManager | null;
2865
2932
  /**
2866
- * Gracefully shut down the SDK, flushing any pending data.
2933
+ * Get the wallet monitor instance (or null if not configured).
2934
+ * Used by the viem interceptor for dedup registration.
2935
+ */
2936
+ getWalletMonitor(): WalletMonitor | null;
2937
+ /**
2938
+ * Gracefully shut down the SDK, flushing any pending data and stopping watchers.
2867
2939
  */
2868
2940
  destroy(): Promise<void>;
2869
2941
  }
@@ -3854,4 +3926,112 @@ declare class ScreeningAggregator {
3854
3926
  private buildResult;
3855
3927
  }
3856
3928
 
3857
- export { type ActionLog, type AgentCard, type AgentData, type AgentIdentity, AgentIdentityRegistry, type AgentLink, type AgentSession, type AggregatedScreeningResult, type AnchorResult, type AnchorVerification, type AnomalyCallback, type AnomalyDetectionConfig, AnomalyDetector, type AnomalyEvent, type AnomalyRuleType, type AnomalySeverity, type AnomalyThresholds, type AttestationDecision, type AttestationPayload, type AttestationRequest, type AttestationResponse, type AttestationSignature, type BehavioralEmbedding, BehavioralFingerprinter, CURRENCY_REQUIRED_LISTS, type Chain, ChainalysisFreeAPIProvider, ChainalysisOracleProvider, type CheckpointStatus, type ClusteringEvidence, type ClusteringHeuristic, type ComplianceCertificate, type ComplianceCheckResult, type ComplianceReport, type ConfirmTaskInput, type ConsensusStrategy, ConsoleExporter, type CounterpartyAttestation, type CounterpartyConfig, type CreateCheckpointInput, type CreateSessionInput, type CreateTaskInput, CrossSessionLinker, type CrossSessionLinkerConfig, type DateRange, DigestChain, type DigestLink, type DigestVerification, type ERC8021Attribution, type ERC8021Config, type EntityStatus, type EntityType, type Environment, type EventExporter, type ExportFormat, type ExportOptions, type ExportResult, type ExporterResult, type FeatureFlag, type FeatureFlagConfig, FeatureFlagManager, FileStorage, type FinancialFeatures, type FlagPlanTargeting, type FlagScope, type FlagTargeting, type GatedFeature, type GenerateComplianceCertificateInput, type HumanAttestation, JsonFileExporter, type Jurisdiction, KONTEXT_BUILDER_CODE, type KYAConfidenceLevel, type KYAConfidenceScore, KYAConfidenceScorer, type KYAConfidenceScorerConfig, type KYAEnvelope, type KYAScoreComponent, type KYCProviderReference, type KYCStatus, Kontext, type KontextConfig, KontextError, KontextErrorCode, type KontextMode, type LimitEvent, type LinkSignal, type LinkStatus, type LogActionInput, type LogLevel, type LogReasoningInput, type LogTransactionInput, type MatchType, MemoryStorage, type MetadataValidator, type NetworkFeatures, NoopExporter, OFACAddressProvider, OFACEntityProvider, type OnChainAnchorConfig, OnChainExporter, OpenSanctionsLocalProvider, OpenSanctionsProvider, type OperationalFeatures, PLAN_LIMITS, PaymentCompliance, type PlanConfig, PlanManager, type PlanTier, type PlanUsage, type PolicyConfig, type PrecisionTimestamp, type ProvenanceAction, type ProvenanceAttestor, type ProvenanceBundle, type ProvenanceBundleVerification, type ProvenanceCheckpoint, ProvenanceManager, type QueryType, type ReasoningEntry, type RegisterIdentityInput, type ReportOptions, type ReportType, type RiskFactor, type SanctionsCheckResult, type SanctionsList, ScreeningAggregator, type ScreeningAggregatorConfig, type ScreeningConfig, type ScreeningContext, type ScreeningMatch, type ScreeningProvider, type ScreeningResult, type SessionConstraints, type SessionStatus, type StorageAdapter, TOKEN_REQUIRED_LISTS, type Task, type TaskEvidence, type TaskStatus, type TemporalFeatures, type Token, type TransactionEvaluation, type TransactionRecord, type TrustFactor, type TrustScore, TrustScorer, UKOFSIProvider, type UpdateIdentityInput, UsdcCompliance, type UsdcComplianceCheck, type VerificationKey, type VerifyInput, type VerifyResult, type WalletCluster, WalletClusterer, type WalletClusteringConfig, type WalletMapping, anchorDigest, encodeERC8021Suffix, exchangeAttestation, fetchAgentCard, fetchTransactionAttribution, getAnchor, getRequiredLists, isBlockchainAddress, isCryptoTransaction, isFeatureAvailable, parseERC8021Suffix, providerSupportsQuery, requirePlan, verifyAnchor, verifyExportedChain };
3929
+ /** Minimal WalletClient shape avoids hard type dependency on viem */
3930
+ interface WalletClientLike {
3931
+ sendTransaction: (args: any) => Promise<`0x${string}`>;
3932
+ writeContract?: (args: any) => Promise<`0x${string}`>;
3933
+ chain?: {
3934
+ id: number;
3935
+ name?: string;
3936
+ };
3937
+ account?: {
3938
+ address: `0x${string}`;
3939
+ };
3940
+ extend: <T>(fn: (client: any) => T) => any;
3941
+ }
3942
+ /** Minimal Kontext interface needed by the interceptor */
3943
+ interface KontextForInterceptor {
3944
+ verify(input: VerifyInput): Promise<VerifyResult>;
3945
+ getConfig(): {
3946
+ agentId?: string;
3947
+ interceptorMode?: string;
3948
+ policy?: {
3949
+ allowedTokens?: Token[];
3950
+ };
3951
+ };
3952
+ getWalletMonitor?(): WalletMonitor | null;
3953
+ }
3954
+ /** Options for the viem auto-instrumentation decorator */
3955
+ interface ViemInstrumentationOptions {
3956
+ /** Agent ID to attribute transactions to */
3957
+ agentId?: string;
3958
+ /** Session ID for grouping transactions */
3959
+ sessionId?: string;
3960
+ /** Tokens to instrument (default: all known) */
3961
+ tokens?: Token[];
3962
+ /** Chains to instrument (default: all known) */
3963
+ chains?: Chain[];
3964
+ /** Compliance mode (default: reads from config, falls back to 'post-send') */
3965
+ mode?: 'post-send' | 'pre-send' | 'both';
3966
+ /** Called after verify() succeeds */
3967
+ onVerify?: (result: VerifyResult, txHash: string) => void | Promise<void>;
3968
+ /** Called when verify() fails */
3969
+ onError?: (error: Error, txHash: string) => void | Promise<void>;
3970
+ /** Additional metadata for every verify() call */
3971
+ metadata?: Record<string, unknown>;
3972
+ }
3973
+ /**
3974
+ * Thrown in pre-send mode when compliance screening fails.
3975
+ */
3976
+ declare class ViemComplianceError extends Error {
3977
+ readonly result: VerifyResult;
3978
+ readonly from: string;
3979
+ readonly to: string;
3980
+ readonly amount: string;
3981
+ constructor(message: string, result: VerifyResult, details: {
3982
+ from: string;
3983
+ to: string;
3984
+ amount: string;
3985
+ });
3986
+ }
3987
+ /**
3988
+ * Wraps a viem WalletClient with Kontext auto-instrumentation.
3989
+ * Every stablecoin transfer is automatically compliance-checked via verify().
3990
+ *
3991
+ * Reads defaults from kontext.getConfig() — options override config values.
3992
+ */
3993
+ declare function withKontextCompliance<TClient extends WalletClientLike>(client: TClient, kontext: KontextForInterceptor, options?: Partial<ViemInstrumentationOptions>): TClient;
3994
+
3995
+ interface StablecoinContractInfo {
3996
+ token: Token;
3997
+ chain: Chain;
3998
+ decimals: number;
3999
+ }
4000
+ /**
4001
+ * Known stablecoin contract addresses indexed by lowercased address.
4002
+ * Used for O(1) detection of whether a transaction targets a stablecoin.
4003
+ */
4004
+ declare const STABLECOIN_CONTRACTS: Record<string, StablecoinContractInfo>;
4005
+ /**
4006
+ * Maps viem chain IDs to Kontext Chain strings.
4007
+ */
4008
+ declare const CHAIN_ID_MAP: Record<number, Chain>;
4009
+
4010
+ /** Shape of the kontext.config.json file */
4011
+ interface KontextConfigFile {
4012
+ $schema?: string;
4013
+ projectId: string;
4014
+ agentId?: string;
4015
+ environment?: Environment;
4016
+ wallets?: string[];
4017
+ tokens?: Token[];
4018
+ chains?: Chain[];
4019
+ rpcEndpoints?: Partial<Record<Chain, string>>;
4020
+ mode?: 'post-send' | 'pre-send' | 'both';
4021
+ corridors?: {
4022
+ from?: string;
4023
+ to?: string;
4024
+ };
4025
+ thresholds?: {
4026
+ alertAmount?: string;
4027
+ ctrAmount?: string;
4028
+ };
4029
+ apiKey?: string;
4030
+ }
4031
+ /**
4032
+ * Discover and load kontext.config.json by walking up from startDir.
4033
+ * Returns the parsed config file contents, or null if not found.
4034
+ */
4035
+ declare function loadConfigFile(startDir?: string): KontextConfigFile | null;
4036
+
4037
+ export { type ActionLog, type AgentCard, type AgentData, type AgentIdentity, AgentIdentityRegistry, type AgentLink, type AgentSession, type AggregatedScreeningResult, type AnchorResult, type AnchorVerification, type AnomalyCallback, type AnomalyDetectionConfig, AnomalyDetector, type AnomalyEvent, type AnomalyRuleType, type AnomalySeverity, type AnomalyThresholds, type AttestationDecision, type AttestationPayload, type AttestationRequest, type AttestationResponse, type AttestationSignature, type BehavioralEmbedding, BehavioralFingerprinter, CHAIN_ID_MAP, CURRENCY_REQUIRED_LISTS, type Chain, ChainalysisFreeAPIProvider, ChainalysisOracleProvider, type CheckpointStatus, type ClusteringEvidence, type ClusteringHeuristic, type ComplianceCertificate, type ComplianceCheckResult, type ComplianceReport, type ConfirmTaskInput, type ConsensusStrategy, ConsoleExporter, type CounterpartyAttestation, type CounterpartyConfig, type CreateCheckpointInput, type CreateSessionInput, type CreateTaskInput, CrossSessionLinker, type CrossSessionLinkerConfig, type DateRange, DigestChain, type DigestLink, type DigestVerification, type ERC8021Attribution, type ERC8021Config, type EntityStatus, type EntityType, type Environment, type EventExporter, type ExportFormat, type ExportOptions, type ExportResult, type ExporterResult, type FeatureFlag, type FeatureFlagConfig, FeatureFlagManager, FileStorage, type FinancialFeatures, type FlagPlanTargeting, type FlagScope, type FlagTargeting, type GatedFeature, type GenerateComplianceCertificateInput, type HumanAttestation, JsonFileExporter, type Jurisdiction, KONTEXT_BUILDER_CODE, type KYAConfidenceLevel, type KYAConfidenceScore, KYAConfidenceScorer, type KYAConfidenceScorerConfig, type KYAEnvelope, type KYAScoreComponent, type KYCProviderReference, type KYCStatus, Kontext, type KontextConfig, KontextError, KontextErrorCode, type KontextMode, type LimitEvent, type LinkSignal, type LinkStatus, type LogActionInput, type LogLevel, type LogReasoningInput, type LogTransactionInput, type MatchType, MemoryStorage, type MetadataValidator, type NetworkFeatures, NoopExporter, OFACAddressProvider, OFACEntityProvider, type OnChainAnchorConfig, OnChainExporter, OpenSanctionsLocalProvider, OpenSanctionsProvider, type OperationalFeatures, PLAN_LIMITS, PaymentCompliance, type PlanConfig, PlanManager, type PlanTier, type PlanUsage, type PolicyConfig, type PrecisionTimestamp, type ProvenanceAction, type ProvenanceAttestor, type ProvenanceBundle, type ProvenanceBundleVerification, type ProvenanceCheckpoint, ProvenanceManager, type QueryType, type ReasoningEntry, type RegisterIdentityInput, type ReportOptions, type ReportType, type RiskFactor, STABLECOIN_CONTRACTS, type SanctionsCheckResult, type SanctionsList, ScreeningAggregator, type ScreeningAggregatorConfig, type ScreeningConfig, type ScreeningContext, type ScreeningMatch, type ScreeningProvider, type ScreeningResult, type SessionConstraints, type SessionStatus, type StorageAdapter, TOKEN_REQUIRED_LISTS, type Task, type TaskEvidence, type TaskStatus, type TemporalFeatures, type Token, type TransactionEvaluation, type TransactionRecord, type TrustFactor, type TrustScore, TrustScorer, UKOFSIProvider, type UpdateIdentityInput, UsdcCompliance, type UsdcComplianceCheck, type VerificationKey, type VerifyInput, type VerifyResult, ViemComplianceError, type ViemInstrumentationOptions, type WalletClientLike, type WalletCluster, WalletClusterer, type WalletClusteringConfig, type WalletMapping, WalletMonitor, type WalletMonitoringConfig, anchorDigest, encodeERC8021Suffix, exchangeAttestation, fetchAgentCard, fetchTransactionAttribution, getAnchor, getRequiredLists, isBlockchainAddress, isCryptoTransaction, isFeatureAvailable, loadConfigFile, parseERC8021Suffix, providerSupportsQuery, requirePlan, verifyAnchor, verifyExportedChain, withKontextCompliance };
package/dist/index.d.ts CHANGED
@@ -434,6 +434,24 @@ interface KontextConfig {
434
434
  * $10K CTR, $50K large transaction).
435
435
  */
436
436
  policy?: PolicyConfig;
437
+ /**
438
+ * Default agent ID for verify/log calls when not specified per-call.
439
+ * Set automatically when loading from kontext.config.json.
440
+ */
441
+ agentId?: string;
442
+ /**
443
+ * Wallet monitoring configuration. When provided, SDK watches these
444
+ * addresses on-chain for stablecoin transfers and auto-calls verify().
445
+ * Requires viem as a peer dependency.
446
+ */
447
+ walletMonitoring?: WalletMonitoringConfig;
448
+ /**
449
+ * Viem interceptor mode for withKontextCompliance() (default: 'post-send').
450
+ * - 'post-send': verify() runs after tx succeeds, never blocks
451
+ * - 'pre-send': verify() runs before tx, throws if non-compliant
452
+ * - 'both': pre-send screening + post-send full verify
453
+ */
454
+ interceptorMode?: 'post-send' | 'pre-send' | 'both';
437
455
  }
438
456
  /** Screening configuration for pluggable multi-provider sanctions screening */
439
457
  interface ScreeningConfig {
@@ -473,6 +491,15 @@ interface PolicyConfig {
473
491
  /** When true, refuse verify() if no screening provider is configured (default: false) */
474
492
  requireScreening?: boolean;
475
493
  }
494
+ /** Wallet monitoring configuration for on-chain event listening */
495
+ interface WalletMonitoringConfig {
496
+ /** Wallet addresses to watch for outgoing stablecoin transfers */
497
+ wallets: string[];
498
+ /** RPC endpoints per chain (required for on-chain listening) */
499
+ rpcEndpoints: Partial<Record<Chain, string>>;
500
+ /** Polling interval in ms for HTTP transports (default: 12000) */
501
+ pollingIntervalMs?: number;
502
+ }
476
503
  /**
477
504
  * Interface for metadata validation. Compatible with Zod schemas and any
478
505
  * validator that implements a `parse` method.
@@ -1713,6 +1740,45 @@ declare class FeatureFlagManager {
1713
1740
  private triggerBackgroundRefresh;
1714
1741
  }
1715
1742
 
1743
+ /** Minimal Kontext interface needed by the monitor */
1744
+ interface KontextForMonitor {
1745
+ verify(input: VerifyInput): Promise<VerifyResult>;
1746
+ }
1747
+ /**
1748
+ * Watches monitored wallets on-chain for stablecoin Transfer events.
1749
+ * Uses viem's watchEvent with HTTP polling (works with any RPC endpoint).
1750
+ */
1751
+ declare class WalletMonitor {
1752
+ private readonly kontext;
1753
+ private readonly config;
1754
+ private readonly agentId;
1755
+ private readonly tokens;
1756
+ private readonly unwatchers;
1757
+ private running;
1758
+ /** Shared dedup set — tracks recently verified txHashes (populated by both layers) */
1759
+ readonly verifiedTxHashes: Set<string>;
1760
+ private cleanupTimer;
1761
+ private readonly txTimestamps;
1762
+ constructor(kontext: KontextForMonitor, config: WalletMonitoringConfig, options?: {
1763
+ agentId?: string;
1764
+ tokens?: Token[];
1765
+ });
1766
+ /**
1767
+ * Mark a txHash as already verified (called by the viem interceptor layer).
1768
+ * The monitor will skip this tx if it later sees it on-chain.
1769
+ */
1770
+ markVerified(txHash: string): void;
1771
+ /**
1772
+ * Start watching all configured chains for stablecoin transfers.
1773
+ * Dynamically imports viem — requires viem as a peer dependency.
1774
+ */
1775
+ start(): Promise<void>;
1776
+ /** Stop all watchers and cleanup */
1777
+ stop(): void;
1778
+ isRunning(): boolean;
1779
+ private handleTransferLog;
1780
+ }
1781
+
1716
1782
  /** Entity type for an agent identity */
1717
1783
  type EntityType = 'individual' | 'organization' | 'bot' | 'unknown';
1718
1784
  /** KYC verification status */
@@ -2337,6 +2403,7 @@ declare class Kontext {
2337
2403
  private readonly trustScorer;
2338
2404
  private readonly anomalyDetector;
2339
2405
  private readonly screeningAggregator;
2406
+ private walletMonitor;
2340
2407
  private provenanceManager;
2341
2408
  private identityRegistry;
2342
2409
  private walletClusterer;
@@ -2373,7 +2440,7 @@ declare class Kontext {
2373
2440
  * });
2374
2441
  * ```
2375
2442
  */
2376
- static init(config: KontextConfig): Kontext;
2443
+ static init(config?: KontextConfig): Kontext;
2377
2444
  /**
2378
2445
  * Get the current operating mode.
2379
2446
  */
@@ -2863,7 +2930,12 @@ declare class Kontext {
2863
2930
  */
2864
2931
  getFeatureFlagManager(): FeatureFlagManager | null;
2865
2932
  /**
2866
- * Gracefully shut down the SDK, flushing any pending data.
2933
+ * Get the wallet monitor instance (or null if not configured).
2934
+ * Used by the viem interceptor for dedup registration.
2935
+ */
2936
+ getWalletMonitor(): WalletMonitor | null;
2937
+ /**
2938
+ * Gracefully shut down the SDK, flushing any pending data and stopping watchers.
2867
2939
  */
2868
2940
  destroy(): Promise<void>;
2869
2941
  }
@@ -3854,4 +3926,112 @@ declare class ScreeningAggregator {
3854
3926
  private buildResult;
3855
3927
  }
3856
3928
 
3857
- export { type ActionLog, type AgentCard, type AgentData, type AgentIdentity, AgentIdentityRegistry, type AgentLink, type AgentSession, type AggregatedScreeningResult, type AnchorResult, type AnchorVerification, type AnomalyCallback, type AnomalyDetectionConfig, AnomalyDetector, type AnomalyEvent, type AnomalyRuleType, type AnomalySeverity, type AnomalyThresholds, type AttestationDecision, type AttestationPayload, type AttestationRequest, type AttestationResponse, type AttestationSignature, type BehavioralEmbedding, BehavioralFingerprinter, CURRENCY_REQUIRED_LISTS, type Chain, ChainalysisFreeAPIProvider, ChainalysisOracleProvider, type CheckpointStatus, type ClusteringEvidence, type ClusteringHeuristic, type ComplianceCertificate, type ComplianceCheckResult, type ComplianceReport, type ConfirmTaskInput, type ConsensusStrategy, ConsoleExporter, type CounterpartyAttestation, type CounterpartyConfig, type CreateCheckpointInput, type CreateSessionInput, type CreateTaskInput, CrossSessionLinker, type CrossSessionLinkerConfig, type DateRange, DigestChain, type DigestLink, type DigestVerification, type ERC8021Attribution, type ERC8021Config, type EntityStatus, type EntityType, type Environment, type EventExporter, type ExportFormat, type ExportOptions, type ExportResult, type ExporterResult, type FeatureFlag, type FeatureFlagConfig, FeatureFlagManager, FileStorage, type FinancialFeatures, type FlagPlanTargeting, type FlagScope, type FlagTargeting, type GatedFeature, type GenerateComplianceCertificateInput, type HumanAttestation, JsonFileExporter, type Jurisdiction, KONTEXT_BUILDER_CODE, type KYAConfidenceLevel, type KYAConfidenceScore, KYAConfidenceScorer, type KYAConfidenceScorerConfig, type KYAEnvelope, type KYAScoreComponent, type KYCProviderReference, type KYCStatus, Kontext, type KontextConfig, KontextError, KontextErrorCode, type KontextMode, type LimitEvent, type LinkSignal, type LinkStatus, type LogActionInput, type LogLevel, type LogReasoningInput, type LogTransactionInput, type MatchType, MemoryStorage, type MetadataValidator, type NetworkFeatures, NoopExporter, OFACAddressProvider, OFACEntityProvider, type OnChainAnchorConfig, OnChainExporter, OpenSanctionsLocalProvider, OpenSanctionsProvider, type OperationalFeatures, PLAN_LIMITS, PaymentCompliance, type PlanConfig, PlanManager, type PlanTier, type PlanUsage, type PolicyConfig, type PrecisionTimestamp, type ProvenanceAction, type ProvenanceAttestor, type ProvenanceBundle, type ProvenanceBundleVerification, type ProvenanceCheckpoint, ProvenanceManager, type QueryType, type ReasoningEntry, type RegisterIdentityInput, type ReportOptions, type ReportType, type RiskFactor, type SanctionsCheckResult, type SanctionsList, ScreeningAggregator, type ScreeningAggregatorConfig, type ScreeningConfig, type ScreeningContext, type ScreeningMatch, type ScreeningProvider, type ScreeningResult, type SessionConstraints, type SessionStatus, type StorageAdapter, TOKEN_REQUIRED_LISTS, type Task, type TaskEvidence, type TaskStatus, type TemporalFeatures, type Token, type TransactionEvaluation, type TransactionRecord, type TrustFactor, type TrustScore, TrustScorer, UKOFSIProvider, type UpdateIdentityInput, UsdcCompliance, type UsdcComplianceCheck, type VerificationKey, type VerifyInput, type VerifyResult, type WalletCluster, WalletClusterer, type WalletClusteringConfig, type WalletMapping, anchorDigest, encodeERC8021Suffix, exchangeAttestation, fetchAgentCard, fetchTransactionAttribution, getAnchor, getRequiredLists, isBlockchainAddress, isCryptoTransaction, isFeatureAvailable, parseERC8021Suffix, providerSupportsQuery, requirePlan, verifyAnchor, verifyExportedChain };
3929
+ /** Minimal WalletClient shape avoids hard type dependency on viem */
3930
+ interface WalletClientLike {
3931
+ sendTransaction: (args: any) => Promise<`0x${string}`>;
3932
+ writeContract?: (args: any) => Promise<`0x${string}`>;
3933
+ chain?: {
3934
+ id: number;
3935
+ name?: string;
3936
+ };
3937
+ account?: {
3938
+ address: `0x${string}`;
3939
+ };
3940
+ extend: <T>(fn: (client: any) => T) => any;
3941
+ }
3942
+ /** Minimal Kontext interface needed by the interceptor */
3943
+ interface KontextForInterceptor {
3944
+ verify(input: VerifyInput): Promise<VerifyResult>;
3945
+ getConfig(): {
3946
+ agentId?: string;
3947
+ interceptorMode?: string;
3948
+ policy?: {
3949
+ allowedTokens?: Token[];
3950
+ };
3951
+ };
3952
+ getWalletMonitor?(): WalletMonitor | null;
3953
+ }
3954
+ /** Options for the viem auto-instrumentation decorator */
3955
+ interface ViemInstrumentationOptions {
3956
+ /** Agent ID to attribute transactions to */
3957
+ agentId?: string;
3958
+ /** Session ID for grouping transactions */
3959
+ sessionId?: string;
3960
+ /** Tokens to instrument (default: all known) */
3961
+ tokens?: Token[];
3962
+ /** Chains to instrument (default: all known) */
3963
+ chains?: Chain[];
3964
+ /** Compliance mode (default: reads from config, falls back to 'post-send') */
3965
+ mode?: 'post-send' | 'pre-send' | 'both';
3966
+ /** Called after verify() succeeds */
3967
+ onVerify?: (result: VerifyResult, txHash: string) => void | Promise<void>;
3968
+ /** Called when verify() fails */
3969
+ onError?: (error: Error, txHash: string) => void | Promise<void>;
3970
+ /** Additional metadata for every verify() call */
3971
+ metadata?: Record<string, unknown>;
3972
+ }
3973
+ /**
3974
+ * Thrown in pre-send mode when compliance screening fails.
3975
+ */
3976
+ declare class ViemComplianceError extends Error {
3977
+ readonly result: VerifyResult;
3978
+ readonly from: string;
3979
+ readonly to: string;
3980
+ readonly amount: string;
3981
+ constructor(message: string, result: VerifyResult, details: {
3982
+ from: string;
3983
+ to: string;
3984
+ amount: string;
3985
+ });
3986
+ }
3987
+ /**
3988
+ * Wraps a viem WalletClient with Kontext auto-instrumentation.
3989
+ * Every stablecoin transfer is automatically compliance-checked via verify().
3990
+ *
3991
+ * Reads defaults from kontext.getConfig() — options override config values.
3992
+ */
3993
+ declare function withKontextCompliance<TClient extends WalletClientLike>(client: TClient, kontext: KontextForInterceptor, options?: Partial<ViemInstrumentationOptions>): TClient;
3994
+
3995
+ interface StablecoinContractInfo {
3996
+ token: Token;
3997
+ chain: Chain;
3998
+ decimals: number;
3999
+ }
4000
+ /**
4001
+ * Known stablecoin contract addresses indexed by lowercased address.
4002
+ * Used for O(1) detection of whether a transaction targets a stablecoin.
4003
+ */
4004
+ declare const STABLECOIN_CONTRACTS: Record<string, StablecoinContractInfo>;
4005
+ /**
4006
+ * Maps viem chain IDs to Kontext Chain strings.
4007
+ */
4008
+ declare const CHAIN_ID_MAP: Record<number, Chain>;
4009
+
4010
+ /** Shape of the kontext.config.json file */
4011
+ interface KontextConfigFile {
4012
+ $schema?: string;
4013
+ projectId: string;
4014
+ agentId?: string;
4015
+ environment?: Environment;
4016
+ wallets?: string[];
4017
+ tokens?: Token[];
4018
+ chains?: Chain[];
4019
+ rpcEndpoints?: Partial<Record<Chain, string>>;
4020
+ mode?: 'post-send' | 'pre-send' | 'both';
4021
+ corridors?: {
4022
+ from?: string;
4023
+ to?: string;
4024
+ };
4025
+ thresholds?: {
4026
+ alertAmount?: string;
4027
+ ctrAmount?: string;
4028
+ };
4029
+ apiKey?: string;
4030
+ }
4031
+ /**
4032
+ * Discover and load kontext.config.json by walking up from startDir.
4033
+ * Returns the parsed config file contents, or null if not found.
4034
+ */
4035
+ declare function loadConfigFile(startDir?: string): KontextConfigFile | null;
4036
+
4037
+ export { type ActionLog, type AgentCard, type AgentData, type AgentIdentity, AgentIdentityRegistry, type AgentLink, type AgentSession, type AggregatedScreeningResult, type AnchorResult, type AnchorVerification, type AnomalyCallback, type AnomalyDetectionConfig, AnomalyDetector, type AnomalyEvent, type AnomalyRuleType, type AnomalySeverity, type AnomalyThresholds, type AttestationDecision, type AttestationPayload, type AttestationRequest, type AttestationResponse, type AttestationSignature, type BehavioralEmbedding, BehavioralFingerprinter, CHAIN_ID_MAP, CURRENCY_REQUIRED_LISTS, type Chain, ChainalysisFreeAPIProvider, ChainalysisOracleProvider, type CheckpointStatus, type ClusteringEvidence, type ClusteringHeuristic, type ComplianceCertificate, type ComplianceCheckResult, type ComplianceReport, type ConfirmTaskInput, type ConsensusStrategy, ConsoleExporter, type CounterpartyAttestation, type CounterpartyConfig, type CreateCheckpointInput, type CreateSessionInput, type CreateTaskInput, CrossSessionLinker, type CrossSessionLinkerConfig, type DateRange, DigestChain, type DigestLink, type DigestVerification, type ERC8021Attribution, type ERC8021Config, type EntityStatus, type EntityType, type Environment, type EventExporter, type ExportFormat, type ExportOptions, type ExportResult, type ExporterResult, type FeatureFlag, type FeatureFlagConfig, FeatureFlagManager, FileStorage, type FinancialFeatures, type FlagPlanTargeting, type FlagScope, type FlagTargeting, type GatedFeature, type GenerateComplianceCertificateInput, type HumanAttestation, JsonFileExporter, type Jurisdiction, KONTEXT_BUILDER_CODE, type KYAConfidenceLevel, type KYAConfidenceScore, KYAConfidenceScorer, type KYAConfidenceScorerConfig, type KYAEnvelope, type KYAScoreComponent, type KYCProviderReference, type KYCStatus, Kontext, type KontextConfig, KontextError, KontextErrorCode, type KontextMode, type LimitEvent, type LinkSignal, type LinkStatus, type LogActionInput, type LogLevel, type LogReasoningInput, type LogTransactionInput, type MatchType, MemoryStorage, type MetadataValidator, type NetworkFeatures, NoopExporter, OFACAddressProvider, OFACEntityProvider, type OnChainAnchorConfig, OnChainExporter, OpenSanctionsLocalProvider, OpenSanctionsProvider, type OperationalFeatures, PLAN_LIMITS, PaymentCompliance, type PlanConfig, PlanManager, type PlanTier, type PlanUsage, type PolicyConfig, type PrecisionTimestamp, type ProvenanceAction, type ProvenanceAttestor, type ProvenanceBundle, type ProvenanceBundleVerification, type ProvenanceCheckpoint, ProvenanceManager, type QueryType, type ReasoningEntry, type RegisterIdentityInput, type ReportOptions, type ReportType, type RiskFactor, STABLECOIN_CONTRACTS, type SanctionsCheckResult, type SanctionsList, ScreeningAggregator, type ScreeningAggregatorConfig, type ScreeningConfig, type ScreeningContext, type ScreeningMatch, type ScreeningProvider, type ScreeningResult, type SessionConstraints, type SessionStatus, type StorageAdapter, TOKEN_REQUIRED_LISTS, type Task, type TaskEvidence, type TaskStatus, type TemporalFeatures, type Token, type TransactionEvaluation, type TransactionRecord, type TrustFactor, type TrustScore, TrustScorer, UKOFSIProvider, type UpdateIdentityInput, UsdcCompliance, type UsdcComplianceCheck, type VerificationKey, type VerifyInput, type VerifyResult, ViemComplianceError, type ViemInstrumentationOptions, type WalletClientLike, type WalletCluster, WalletClusterer, type WalletClusteringConfig, type WalletMapping, WalletMonitor, type WalletMonitoringConfig, anchorDigest, encodeERC8021Suffix, exchangeAttestation, fetchAgentCard, fetchTransactionAttribution, getAnchor, getRequiredLists, isBlockchainAddress, isCryptoTransaction, isFeatureAvailable, loadConfigFile, parseERC8021Suffix, providerSupportsQuery, requirePlan, verifyAnchor, verifyExportedChain, withKontextCompliance };