Skip to main content
Documentation menu

SDK API Reference

Every class, method, and type in @dan-protocol/sdk

CommerceAgent

A seller agent that handles incoming protocol messages, executes service handlers, tracks contracts and ratings.

Constructor

new CommerceAgent(config: CommerceAgentConfig)
OptionTypeDescription
domainstringDomain for did:web identifier
namestringHuman-readable agent name
descriptionstringWhat this agent does
keyPair?AgentKeyPairEd25519 keypair. Auto-generated if omitted.
acceptedEscrows?string[]DIDs of escrow agents this agent accepts
trustedEvaluators?string[]DIDs of evaluators this agent trusts
authPatterns?('oauth2'|'api-key'|'wallet')[]Auth patterns supported. Default: ['wallet']
didResolver?DIDResolverCustom DID resolver. Required for local testing.
maxSubcontractRatio?numberMax fraction for subcontracting. Default: 0.4 (40%)

Methods

service(id: string, config)

Register a service with handler, pricing, and metadata.

handle(method: ProtocolMethod, handler)

Register a custom protocol handler (for evaluator/escrow agents).

listen(options?: { port?, hostname? }): Promise<void>

Start the HTTP server. Use port: 0 for random port.

close(): Promise<void>

Stop the server. Idempotent — safe to call multiple times.

sign(payload): SignedEnvelope

Sign a message with the agent's private key.

getContract(contractId): ActiveContract | undefined

Get a tracked contract by ID.

getContracts(): ReadonlyMap

Get all tracked contracts.

getRatings(): ReadonlyMap

Get all received ratings.

getDescription(): AgentDescription

Get the agent description document.

Properties

did: string — The agent's DID
domain: string — The domain
publicKey: string — Ed25519 public key (hex)
port: number | undefined — Actual port after listen()
commerceEndpoint: string | undefined — Full URL after listen()

CommerceClient

A buyer that discovers, quotes, hires, and pays seller agents.

Constructor

new CommerceClient(config: CommerceClientConfig)
OptionTypeDescription
didstringBuyer's DID
keyPairAgentKeyPairEd25519 keypair for signing
timeout?numberRequest timeout in ms. Default: 30000
didResolver?DIDResolverCustom resolver for local testing

Methods

hire(endpoint, params: HireParams): Promise<HireResult>

One-liner: discover → quote → contract → deliver. The main entry point.

discoverPricing(endpoint, category?): Promise<DiscoverPricingResponse>

Get an agent's services and pricing.

requestQuote(endpoint, params): Promise<RequestQuoteResponse>

Request a price quote for specific work.

acceptQuote(endpoint, params): Promise<CreateContractResponse>

Accept a quote with escrow proof.

evaluate(evaluatorEndpoint, params): Promise<EvaluateResponse>

Request quality evaluation from an evaluator agent.

settle(escrowEndpoint, params): Promise<SettleResponse>

Request settlement from an escrow agent.

rate(endpoint, params): Promise<RateResponse>

Rate another agent with a signed attestation.

search(indexerUrl, params?): Promise<AgentSearchResult[]>

Search for agents on an indexer.

Identity functions

generateKeyPair(): AgentKeyPair

Generate a new Ed25519 keypair (32-byte private + public, hex-encoded).

derivePublicKey(privateKeyHex): string

Derive public key from private key.

domainToDid(domain): string

Convert domain to did:web identifier.

didToUrl(did): string

Convert did:web to HTTPS URL for resolution.

createDIDDocument(domain, publicKeyHex): DIDDocument

Create a W3C DID document.

extractPublicKey(didDocument, keyId?): string

Extract public key from a DID document.

Signature functions

signMessage(payload, privateKeyHex, signerDid): SignedEnvelope

Sign a JSON-RPC message. Canonicalizes, hashes, signs with Ed25519.

verifyMessage(envelope, publicKeyHex, options?): { valid, error? }

Verify a signed envelope. Checks hash, timestamp, and Ed25519 signature.

signData(data, privateKeyHex): string

Sign raw string data. Used for attestation proofs.

verifyData(data, signatureHex, publicKeyHex): boolean

Verify a raw Ed25519 signature.

verifyContentHash(content, expectedHash): boolean

Verify SHA-256 hash. Constant-time comparison.

canonicalize(obj): string

Deterministic JSON serialization with sorted keys.

hashContent(content): string

SHA-256 hash, hex-encoded.

Trust functions

calculateTrustScore(subjectDid, attestations, issuerScores?, now?): TrustScoreResult

Single-pass trust score. Returns score 0-100 with breakdown.

calculateTrustScores(attestations, maxIter?, epsilon?, now?): Map<string, TrustScoreResult>

PageRank-like iterative scoring for all agents.

createAttestation(params, issuerDid, keyPair): FullAttestation

Create a signed attestation for IPFS publishing.

verifyAttestation(attestation, issuerPublicKey): { valid, error? }

Verify an attestation's Ed25519 proof.

analyzeSybilRisk(subjectDid, allAttestations, thresholds?): SybilAnalysis

Detect sybil patterns: self-attestation, concentrated source, closed circuits, temporal clustering.

calculateReliability(data: ReliabilityData): ReliabilityResult

Quote acceptance/rejection ratio → reliability score 0-100.

Decision engine

thompsonSelect(candidates, budgetLimit?): SelectionResult | null

Thompson Sampling — select best agent under uncertainty.

selectAgent(candidates, config, history?): AgentSelectionResult | null

Combined selection: trust + price + Thompson Sampling.

updateStats(stats, score, price): AgentStats

Update agent stats after interaction.

new BudgetTracker(contractPrice, maxRatio?)

Track cumulative subcontract spending.

new AgentLifecycle(config?)

Manage active → reflecting → cooldown lifecycle.

new IterationTracker(config?)

Track quality per iteration. Stop when marginal return drops.

Reference agents

createEscrowAgent(config: EscrowAgentConfig): CommerceAgent

Create a reference escrow agent. Mock or blockchain mode.

verifySettlementReceipt(receipt, escrowPublicKey): { valid, error? }

Verify an escrow settlement receipt signature.

createEvaluatorAgent(config: EvaluatorAgentConfig): CommerceAgent

Create a reference evaluator agent. Custom or default heuristic.

Settlement

matchEscrows(buyerPreferred, sellerAccepted): EscrowMatch[]

Find escrow agents accepted by both parties.

selectEscrow(matches): EscrowMatch | null

Pick the best escrow from matches.

findBridge(buyerCurrency, sellerCurrency, bridges): BridgeInfo | null

Find a bridge escrow for currency conversion.

verifyProtocolFee(txHash, config): Promise<FeeVerificationResult>

Verify 1% fee tx on Base L2 via viem.