@wzrd_sol/sdk
v0.4.7
Published
Trust + receipt layer for agentic x402 payments: free preflight, free merchant_card wash refuse default, portable Ed25519 receipts, and an agent loop. Settles on Solana today; also ships Liquid Attention protocol builders. Primary trust/MCP surface: twzrd
Maintainers
Readme
@wzrd_sol/sdk
TypeScript SDK for agentic x402 payments: vet-before-pay trust gates, portable signed receipts, and an agent loop. Settles on Solana today.
The primary trust + MCP surface is twzrd-agent-intel (https://intel.twzrd.xyz). This SDK carries the same trust/receipt layer plus the Solana Liquid Attention protocol builders.
The agent loop
Every paid agent action runs the same four steps - only step 3 touches a chain:
- Discover - find a seller/resource you might pay (any x402 endpoint).
- Preflight -
intelPreflight(seller)returns a free ReadinessCard;decision: 'block'means stop. (chain-agnostic HTTP) - Pay -
fetchIntelTrust(seller, { fetchImpl: x402Fetch })settles the x402 payment. (USDC on Solana today) - Verify -
verifyReceipt(resp.twzrd_receipt)checks the Ed25519 signature + keccak leaf offline. (chain-agnostic crypto)
preSpendGate() wraps all four in a single call. The receipt is the unit of value: a portable proof your agent vetted the counterparty before money moved.
Try it in 30 seconds (no wallet, no signup)
npx @wzrd_sol/sdkFetches a live signed receipt from intel.twzrd.xyz and verifies it offline: recomputes the keccak leaf from the preimage, checks the Ed25519 signature against TWZRD's published key. No env vars, no arguments. (After npm install the same command is available as twzrd-verify.)
Expected output:
{
"valid": true,
"leafValid": true,
"signatureValid": true,
"trustedPubkey": "9V6Pn19kiUA5Rn6JpQfNduanvGt2aXGwsarosNfa2Ldf",
"errors": []
}followed by Live receipt verified offline (leaf + Ed25519 signature against the published key).
From there, run a free preflight on any seller before paying (repo example — the published package ships the verify bin + library; clone this repo to run examples/):
# Preflight TWZRD's own intel service wallet (free, no USDC needed)
npx tsx examples/pre-spend-gate.ts # defaults to the TWZRD seller wallet, or pass any pubkeySDK Version Lines
The package is published with two dist-tags:
latest(0.4.0+): The active line. Full protocol surface + agent rail (AgentLoop,ModelSelector, agent auth/report) + trust/receipt layer (preSpendGate,intelPreflight, signed receipts,verifyReceipt, etc.).v0-1(pinned at 0.1.4): Legacy protocol-only maintenance line. Core PDAs, parsers,deposit_market/settle_market,claim_global(v1 + v2). No agent primitives, no x402/trust, no staking/stream/prediction builders.
npm view @wzrd_sol/sdk dist-tags
# v0-1: 0.1.4 (legacy, pinned) | latest: the active 0.4.x line - run the command for the exact current patchWhy the split exists: The 0.1.x line is a maintenance backport for legacy/pinned integrations that have not migrated to the agent + trust surface. 0.1.3/0.1.4 were cut specifically to keep those consumers and external/old-SDK E2E flows unblocked. All new work lands on latest.
Repo-only builders (present only on latest): createStakeChannel*, createClaimChannelRewards*, createMintSharesIx / createRedeemSharesIx, createSettlePredictionIx, createPublishStreamRootIx / createClaimStream*. These target instructions that are not dispatched by the immutable mainnet AO binary (they return Custom 101). They are annotated as such in the source and should only be used for local development or future on-chain modules.
New work and the demand wedge (agentic paid attention, x402 receipts, portable verifiable reputation) live on latest. The token loop (CCM yield) is a maintenance surface only.
See the root CLAUDE.md "Live vs Future (on-chain modules)" for the current dispatcher matrix on the immutable program.
One-call pre-spend gate
preSpendGate() wraps the whole discover -> preflight -> (pay) -> verify loop in a
single call. Run it before paying any x402 seller:
import { preSpendGate } from '@wzrd_sol/sdk';
const gate = await preSpendGate(
{ seller_wallet: sellerPubkey, price_usdc: 0.25, agent_intent: 'swap_quote' },
{ escalateAboveUsdc: 0.2, fetchImpl: x402Fetch }, // escalate big spends to a signed receipt
);
if (!gate.allow) throw new Error(`blocked: ${gate.reason}`);
// gate.decision / gate.trustScore / gate.receipt / gate.receiptValidFail-open by default: a real block blocks the spend, but a gate outage allows it
with gateAvailable=false so a trust-service blip never silently halts payments.
See examples/pre-spend-gate.ts.
Install
npm install @wzrd_sol/sdk @solana/web3.js@solana/web3.js is a peer dependency, so install it alongside the SDK.
Quick Start
Earn: Prove You Vetted A Seller (Receipt Loop)
The canonical earning mechanism: free preflight → paid receipt → offline verify.
import { intelPreflight, fetchIntelTrust, verifyReceipt } from '@wzrd_sol/sdk';
const seller = 'JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4'; // example: Jupiter
// 1. Preflight (free - no wallet, no USDC, no signup)
const pf = await intelPreflight({
seller_wallet: seller,
price_usdc: 0.05,
agent_intent: 'swap_quote',
});
const card = pf.readiness_card;
if (card?.decision === 'block') {
console.log('Seller flagged:', card.caveats); // abort the payment
} else {
// 2. Pay (0.05 USDC via x402 - Solana today). Pass an x402-capable fetchImpl
// (e.g. AgentCash); plain fetch throws IntelPaymentRequiredError
// carrying the 402 payment requirements.
const resp = await fetchIntelTrust(seller, { fetchImpl: x402Fetch });
// 3. Verify offline (trust nothing but the bytes + the published key)
const result = await verifyReceipt(resp.twzrd_receipt!);
console.log('Receipt valid:', result.valid); // true = portable proof of vetting
}Runnable end-to-end version: tsx examples/preflight-and-receipt.ts <sellerPubkey>.
The receipt is the unit of value: every vet-before-pay decision produces a portable, Ed25519-signed proof that your agent checked the counterparty before money moved. No token to hold, no position to manage - the receipt itself is the asset.
Agent Loop (Advanced)
For agents running the full auth → pick → infer → report → claim cycle:
import { AgentLoop } from '@wzrd_sol/sdk';
import { Keypair } from '@solana/web3.js';
const keypair = Keypair.fromSecretKey(/* your secret key bytes */);
const loop = new AgentLoop({
keypair,
tasks: ['code', 'chat', 'reasoning'],
cycleSeconds: 300,
claim: true,
});
loop.start();This runs the full external-agent flow: auth, pick, infer, report, and gasless claim. Requires on-chain agent registration.
Example Scripts
From the repo root:
npm run build --workspace=sdk
npm run typecheck:examples --workspace=sdkRunnable examples:
tsx examples/verify-live-receipt.ts— fetch a real signed receipt from intel.twzrd.xyz and verify it offline (no wallet, no mocks; the verifiability wedge)tsx examples/preflight-and-receipt.ts <sellerPubkey> [priceUsdc]— full loop: preflight free, pay for receipt, verify offlinetsx examples/pre-spend-gate.ts <sellerPubkey> [priceUsdc]— one-call pre-spend gate (wraps the loop above)npm run example:deposit --workspace=sdk— token loop: deposit USDC for vLOFInpm run example:claim --workspace=sdk— token loop: claim CCM from merkle proof
The receipt examples need no env vars (preflight + offline verify are free; the paid step prints x402 requirements without a payer). The token-loop examples expect:
SOLANA_RPC_URLWZRD_KEYPAIR_PATH
The deposit example also expects:
WZRD_MARKET_IDWZRD_DEPOSIT_USDC
Quick Reference
Verify a Receipt Offline (Trust Nothing)
import { verifyReceipt } from '@wzrd_sol/sdk';
// Fetch a real receipt from https://intel.twzrd.xyz/v1/intel/trust/<pubkey>
// (requires x402 payment), then verify locally:
const result = await verifyReceipt(receipt); // defaults to the published TWZRD key
// result.valid === true means the receipt was signed by TWZRD and not tampered with.
// Pin the key out-of-band: verifyReceipt(receipt, { trustedPubkey: TRUSTED_RECEIPT_PUBKEY })Rail-agnostic. Verification is pure keccak-256 + Ed25519 — no Solana RPC, no
chain client. The receipt leaf folds the payer and settlement tx through
rail-neutral byte fallbacks, so verifyReceipt validates a receipt that references
a payment on any rail (Solana today, Base/x402, etc.), not just Solana. This is
enforced by a test that signs and verifies a Base/EVM-referencing receipt
end-to-end (src/intel.test.ts → "rail-agnostic receipts"). Settlement is Solana
USDC today; the portable proof is not.
Fetch an Intel Trust Receipt (Paid)
import { fetchIntelTrust, IntelPaymentRequiredError } from '@wzrd_sol/sdk';
// Inject an x402-capable fetch (e.g. AgentCash) to settle the 0.05 USDC payment.
// With plain fetch this throws IntelPaymentRequiredError carrying the 402 requirements.
const resp = await fetchIntelTrust('JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4', {
fetchImpl: x402Fetch,
});
// resp.trust = the renormalized trust model; resp.twzrd_receipt = the signed V5 receiptFree Preflight Check (Before Paying)
import { intelPreflight } from '@wzrd_sol/sdk';
const pf = await intelPreflight({
seller_wallet: 'JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4',
price_usdc: 0.05,
agent_intent: 'swap_quote',
});
// pf.readiness_card: { decision: 'allow'|'warn'|'block', trust_score, can_spend, caveats[], ... }Read On-Chain State
import { fetchMarketVault, fetchOnChainPosition, fetchTokenBalance } from '@wzrd_sol/sdk';
const vault = await fetchMarketVault(connection, 6);
console.log('Total deposited:', vault?.totalDeposited);
const pos = await fetchOnChainPosition(connection, wallet.publicKey, 6);
console.log('My deposit:', pos?.depositedAmount, 'Multiplier:', pos?.attentionMultiplierBps);Token Loop (Legacy — Maintenance Only)
The on-chain token earning mechanism (CCM yield on vLOFI deposits) is a maintenance surface. New applications should use the receipt loop above.
PDA Derivation
import {
getProtocolStatePDA,
getMarketVaultPDA,
getUserPositionPDA,
getGlobalRootConfigPDA,
getClaimStatePDA,
PROGRAM_ID,
} from '@wzrd_sol/sdk';
const protocolState = getProtocolStatePDA();
const marketVault = getMarketVaultPDA(protocolState, 6); // market ID 6
const position = getUserPositionPDA(marketVault, walletPubkey);Deposit USDC → Receive vLOFI
import { Connection, Keypair, VersionedTransaction, TransactionMessage } from '@solana/web3.js';
import { createDepositMarketIx } from '@wzrd_sol/sdk';
const connection = new Connection('https://api.mainnet-beta.solana.com');
const wallet = Keypair.fromSecretKey(/* your key */);
// Build instructions for a 1 USDC deposit into market 6
const ixs = await createDepositMarketIx(connection, wallet.publicKey, 6, 1_000_000n);
const { blockhash } = await connection.getLatestBlockhash();
const message = new TransactionMessage({
payerKey: wallet.publicKey,
recentBlockhash: blockhash,
instructions: ixs,
}).compileToV0Message();
const tx = new VersionedTransaction(message);
tx.sign([wallet]);
const sig = await connection.sendTransaction(tx);
console.log('Deposit tx:', sig);Claim CCM via Merkle Proof
import { createClaimGlobalV2Ix, fetchClaimProof } from '@wzrd_sol/sdk';
// Public proof fetch — no wallet session (SIWS) required. Any caller who knows
// the wallet address can fetch its proof and build the claim locally.
const claim = await fetchClaimProof(wallet.publicKey.toBase58());
const ixs = await createClaimGlobalV2Ix(
connection,
wallet.publicKey,
claim.rootSeq,
claim.baseYield,
claim.attentionBonus,
claim.proof, // hex-encoded [u8; 32] nodes
);
// Build, sign, send as abovefetchClaimProof calls the public GET /v1/claims/:pubkey/proof endpoint and
throws ClaimProofNotFoundError if the wallet has no attention accrual yet.
Settle a Matured Position
import { createSettleMarketIx } from '@wzrd_sol/sdk';
const ixs = await createSettleMarketIx(connection, wallet.publicKey, 6);
// Build, sign, send as abovesettle_market returns USDC from reserve and burns vLOFI. It does not mint CCM; CCM is claimed via merkle proof (claim_global / claim_global_v2).
Exports
Constants
| Export | Description |
|--------|-------------|
| PROGRAM_ID | Mainnet program ID (GnGz...) |
| DEVNET_PROGRAM_ID | Devnet program ID (GmGX...) |
| TOKEN_PROGRAM_ID | SPL Token program |
| TOKEN_2022_PROGRAM_ID | Token-2022 program (CCM uses this) |
PDA Derivation
| Function | Seeds |
|----------|-------|
| getProtocolStatePDA() | ["protocol_state"] |
| getMarketVaultPDA(protocolState, marketId) | ["market_vault", protocolState, marketId] |
| getUserPositionPDA(marketVault, user) | ["market_position", marketVault, user] |
| getGlobalRootConfigPDA(ccmMint) | ["global_root", ccmMint] |
| getClaimStatePDA(ccmMint, claimer) | ["claim_global", ccmMint, claimer] |
Instruction Builders
| Function | On-chain instruction |
|----------|---------------------|
| createDepositMarketIx(conn, user, marketId, amount) | deposit_market |
| createSettleMarketIx(conn, user, marketId) | settle_market |
| createClaimGlobalV2Ix(conn, claimer, rootSeq, baseYield, attentionBonus, proof) | claim_global_v2 |
| createInitializeMarketVaultIx(admin, marketId, ...) | initialize_market_vault |
Repo-only / future builders (latest only, annotated @deprecated in source): createStakeChannelIx*, createClaimChannelRewardsIx, createMintSharesIx/createRedeemSharesIx, createSettlePredictionIx, createPublishStreamRootIx/createClaimStream*. These target instructions not present on the immutable mainnet binary. See "SDK Version Lines" above.
Account Parsers
| Function | Account type |
|----------|-------------|
| parseMarketVault(data) | MarketVault |
| parseProtocolState(data) | ProtocolState |
| parseUserMarketPosition(data) | UserMarketPosition |
| fetchMarketVault(conn, marketId) | Fetch + parse |
| fetchOnChainPosition(conn, user, marketId) | Fetch + parse |
| fetchTokenBalance(conn, ata) | Raw token balance |
Key Addresses
| Asset | Mint | Token Program |
|-------|------|---------------|
| USDC | EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v | SPL Token |
| vLOFI | E9Kt33axpCy3ve2PCY9BSrbPhcR9wdDsWQECAahzw2dS | SPL Token |
| CCM | Dxk8mAb3C7AM8JN6tAJfVuSja5yidhZM5sEKW3SRX2BM | Token-2022 |
