$ USE CASES
See how Kontext fits into real agent workflows — stablecoin payments, micropayments, treasury ops, on-chain anchoring, and agent-to-agent attestation. Every example uses the actual SDK API.
USDC Payments
The bread and butter. Your agent moves USDC on Base or Ethereum, and you need a compliance trail that actually holds up. One call to verify() logs the transaction, runs OFAC and threshold checks, computes a trust score, and chains it all into a tamper-evident digest. No config files, no infrastructure — just an npm install and you're logging.
- Tamper-evident audit trail for every USDC transfer with SHA-256 digest chaining
- Built-in OFAC screening, Travel Rule ($3K), and CTR ($10K) threshold checks
- Trust scoring per agent based on transaction history and behavioral patterns
- Exportable compliance reports (JSON out of the box, CSV on Pro)
import { Kontext } from 'kontext-sdk';
const ctx = Kontext.init({
projectId: 'my-payment-agent',
environment: 'production',
});
// One call: compliance check + transaction log + digest chain
const result = await ctx.verify({
txHash: '0xabc123...',
chain: 'base',
amount: '5000',
token: 'USDC',
from: '0xAgentWallet...abc',
to: '0xVendor...def',
agentId: 'payment-agent-v2',
});
if (result.compliant) {
console.log('Risk level:', result.riskLevel); // 'low'
console.log('Trust score:', result.trustScore.score); // 87
console.log('Checks passed:', result.checks.length);
} else {
// result.checks tells you exactly what failed
// result.recommendations tells you what to do about it
console.log('Blocked:', result.recommendations);
}x402 Protocol
HTTP-native micropayments where agents pay per-request. Drop Kontext into your x402 middleware and every micropayment gets compliance-checked before it hits your handler. High-frequency, low-friction — the SDK handles the volume without slowing things down.
- Per-request compliance verification that slots into any HTTP middleware stack
- Every micropayment logged with sender, amount, and resource metadata
- Anomaly detection across high-frequency payment streams (velocity, amount spikes)
- Audit trail linking payments to specific API resources and request methods
import { Kontext } from 'kontext-sdk';
const ctx = Kontext.init({
projectId: 'x402-gateway',
environment: 'production',
});
// x402 middleware -- verify every micropayment
export function x402KontextMiddleware(handler) {
return async (req, res) => {
const payment = req.headers['x-402-payment'];
if (payment) {
const result = await ctx.verify({
txHash: payment.txHash,
chain: 'base',
amount: payment.amount,
token: 'USDC',
from: payment.payer,
to: payment.payee,
agentId: payment.agentId || 'unknown',
metadata: {
resource: req.url,
method: req.method,
},
});
if (!result.compliant) {
return res.status(402).json({
error: 'Payment failed compliance check',
checks: result.checks.filter(c => !c.passed),
});
}
req.kontextResult = result;
}
return handler(req, res);
};
}Stripe Agentic Commerce
Your agent creates Stripe payment intents, and you need to know it is not going off the rails. Verify with Kontext first, then embed the digest proof right in Stripe's metadata. When someone asks "why did this agent charge that card?" you have a cryptographically linked answer.
- Pre-payment compliance gate — block untrusted agents before any charge is created
- Digest proof embedded in Stripe payment metadata for end-to-end traceability
- Trust scoring gates payment creation — low-trust agents get stopped automatically
- Full audit trail mapping Kontext digests to Stripe payment intent IDs
import { Kontext } from 'kontext-sdk';
import Stripe from 'stripe';
const ctx = Kontext.init({
projectId: 'stripe-agent',
environment: 'production',
});
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
async function handleAgentPayment(agentId: string, amount: number) {
// Verify with Kontext before creating payment intent
const result = await ctx.verify({
amount: String(amount / 100),
currency: 'USD',
from: agentId,
to: 'merchant-account',
agentId,
paymentMethod: 'card',
metadata: { provider: 'stripe', type: 'payment_intent' },
});
if (!result.compliant) {
throw new Error('Payment blocked by compliance checks');
}
// Embed Kontext proof in Stripe metadata for traceability
const intent = await stripe.paymentIntents.create({
amount,
currency: 'usd',
metadata: {
kontext_digest: result.digestProof.terminalDigest,
kontext_trust_score: String(result.trustScore.score),
agent_id: agentId,
},
});
return intent;
}Treasury Management
AI agents managing corporate treasury with real money need guardrails that actually work. Kontext gives you anomaly detection for unusual patterns, trust scoring that learns from history, and human-in-the-loop approval for transfers above your threshold. Your CFO gets a Slack ping, not a surprise.
- Human-in-the-loop approval for transfers exceeding configurable thresholds
- Anomaly detection for unusual amounts, new destinations, and frequency spikes
- Agent reasoning logged alongside every transfer decision (the "why" for auditors)
- Trust scoring based on agent history — new agents start cautious, build trust over time
import { Kontext } from 'kontext-sdk';
const ctx = Kontext.init({
apiKey: process.env.KONTEXT_KEY,
projectId: 'treasury-ops',
environment: 'production',
plan: 'payg',
});
// Enable anomaly detection for treasury movements
ctx.enableAnomalyDetection({
rules: ['unusualAmount', 'frequencySpike', 'newDestination'],
thresholds: { maxAmount: '50000', maxFrequency: 10 },
});
ctx.onAnomaly((event) => {
// Alert finance team on Slack/PagerDuty
notifyFinanceTeam(event);
});
async function executeTreasuryTransfer(params) {
const result = await ctx.verify({
txHash: params.txHash,
chain: 'base',
amount: params.amount,
token: 'USDC',
from: params.treasuryWallet,
to: params.destinationWallet,
agentId: 'treasury-manager-v3',
reasoning: `Transfer for ${params.purpose}. Within ${params.department} budget.`,
confidence: 0.92,
});
if (!result.compliant) {
throw new Error('Transfer blocked by compliance checks');
}
// Human-in-the-loop for large transfers
if (parseFloat(params.amount) > 50000) {
const task = await ctx.createTask({
description: `Approve $${params.amount} USDC to ${params.destinationWallet}`,
agentId: 'treasury-manager-v3',
requiredEvidence: ['txHash', 'budget_approval'],
});
console.log('Awaiting CFO approval, task:', task.id);
}
console.log('Trust score:', result.trustScore.score);
console.log('Risk level:', result.riskLevel);
}On-Chain Anchoring
The digest chain already gives you tamper-evident logging at the software level. On-chain anchoring takes it further — after verify() runs, the terminal digest gets written to a smart contract on Base. Now you have a publicly verifiable, immutable proof that your compliance checks ran at a specific block height. Anyone can verify it independently, no trust required.
- Terminal digest anchored on-chain after every verify() call — immutable proof on Base
- Block number and timestamp provide a public, verifiable compliance checkpoint
- Independent verification — anyone with the contract address can check the anchor
- Complements the software digest chain with hardware-level tamper-evidence
import { Kontext } from 'kontext-sdk';
const ctx = Kontext.init({
projectId: 'anchored-compliance',
environment: 'production',
});
// verify() with on-chain anchoring -- writes your digest to Base
const result = await ctx.verify({
txHash: '0xdef456...',
chain: 'base',
amount: '25000',
token: 'USDC',
from: '0xTreasury...abc',
to: '0xVendor...def',
agentId: 'payment-agent-v4',
reasoning: 'Monthly vendor payment, pre-approved in budget cycle',
anchor: {
rpcUrl: process.env.BASE_RPC_URL,
contractAddress: '0xKontextAnchor...abc',
privateKey: process.env.ANCHOR_SIGNER_KEY,
},
});
// The anchor proof is included in the result
if (result.anchorProof) {
console.log('Digest anchored on-chain');
console.log('Anchor tx:', result.anchorProof.txHash);
console.log('Block:', result.anchorProof.blockNumber);
console.log('Digest:', result.anchorProof.digest);
}
// Anyone can independently verify the anchor later
// Zero dependencies -- uses native fetch() + ABI encoding
import { verifyAnchor } from 'kontext-sdk';
const verification = await verifyAnchor(
process.env.BASE_RPC_URL,
'0xKontextAnchor...abc',
result.anchorProof.digest,
);
console.log('Anchor verified:', verification.anchored); // trueA2A Attestation
When two agents transact, both sides need proof that the other ran compliance. Pass a counterparty config to verify() and the SDK handles the handshake automatically — your agent sends its digest to the counterparty, gets theirs back, and both get linked in their respective audit trails. Bilateral compliance proof, zero coordination overhead.
- Bilateral compliance proof — both agents prove they ran checks before transacting
- Automatic agent card discovery via /.well-known/kontext.json (like robots.txt for compliance)
- Digest exchange links both audit trails cryptographically — tamper-evident on both sides
- Configurable timeout and agent ID verification for the attestation handshake
import { Kontext } from 'kontext-sdk';
const ctx = Kontext.init({
projectId: 'buyer-agent',
environment: 'production',
});
// verify() with counterparty attestation -- bilateral compliance proof
const result = await ctx.verify({
txHash: '0xabc789...',
chain: 'base',
amount: '10000',
token: 'USDC',
from: '0xBuyerAgent...abc',
to: '0xSellerAgent...def',
agentId: 'buyer-agent-v2',
reasoning: 'Purchase order #1234, seller verified in allowlist',
counterparty: {
endpoint: 'https://seller-agent.example.com',
agentId: 'seller-agent-v3',
timeoutMs: 5000,
},
});
// Both sides now have cryptographic proof the other ran compliance
if (result.counterparty?.attested) {
console.log('Seller attested:', result.counterparty.agentId);
console.log('Seller digest:', result.counterparty.digest);
console.log('Attested at:', result.counterparty.timestamp);
}
// The seller agent exposes /.well-known/kontext.json (agent card)
// and a /kontext/attest endpoint. The SDK handles the handshake --
// your agent sends its digest, the seller sends theirs back,
// and both get linked in their respective audit trails.Agent Forensics
When multiple agents share wallets or one entity operates many wallets, you need to know. Agent forensics maps wallets to agent identities, detects multi-wallet clustering with 5 heuristics, and computes identity confidence scores. Answer the question regulators will ask: who controls what?
- Wallet-to-agent mapping — register identities and link wallets with evidence
- 5 clustering heuristics: shared-owner, temporal-correlation, funding-chain, amount-pattern, network-overlap
- Identity confidence scoring (0-100) with component-level breakdown
- Exportable forensics data via getKYAExport() for compliance reporting
import { Kontext } from 'kontext-sdk';
const ctx = Kontext.init({
apiKey: process.env.KONTEXT_KEY,
projectId: 'forensics-dashboard',
environment: 'production',
plan: 'payg',
});
// Register agent identities with wallet mappings
ctx.registerAgentIdentity({
agentId: 'treasury-agent-v2',
displayName: 'Treasury Agent',
entityType: 'autonomous',
wallets: [
{ address: '0xTreasury...abc', chain: 'base', label: 'primary' },
{ address: '0xReserve...def', chain: 'base', label: 'reserve' },
],
});
// Detect wallet clusters across all registered agents
const clusters = ctx.getWalletClusters();
// [{ wallets: ['0xTreasury...abc', '0xReserve...def'],
// heuristics: ['shared-owner', 'funding-chain'],
// evidence: [...] }]
// Confidence score: how certain is the identity?
const score = ctx.getKYAConfidenceScore('treasury-agent-v2');
// { score: 82, level: 'high', components: [...] }Ready to add compliance to your agents?
Install the SDK and start logging agent transactions in under 5 minutes. Open source and free to start.