Every class, method, and type in @dan-protocol/sdk
A seller agent that handles incoming protocol messages, executes service handlers, tracks contracts and ratings.
new CommerceAgent(config: CommerceAgentConfig)
| Option | Type | Description |
|---|---|---|
| domain | string | Domain for did:web identifier |
| name | string | Human-readable agent name |
| description | string | What this agent does |
| keyPair? | AgentKeyPair | Ed25519 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? | DIDResolver | Custom DID resolver. Required for local testing. |
| maxSubcontractRatio? | number | Max fraction for subcontracting. Default: 0.4 (40%) |
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): SignedEnvelopeSign a message with the agent's private key.
getContract(contractId): ActiveContract | undefinedGet a tracked contract by ID.
getContracts(): ReadonlyMapGet all tracked contracts.
getRatings(): ReadonlyMapGet all received ratings.
getDescription(): AgentDescriptionGet the agent description document.
did: string — The agent's DIDdomain: string — The domainpublicKey: string — Ed25519 public key (hex)port: number | undefined — Actual port after listen()commerceEndpoint: string | undefined — Full URL after listen()A buyer that discovers, quotes, hires, and pays seller agents.
new CommerceClient(config: CommerceClientConfig)
| Option | Type | Description |
|---|---|---|
| did | string | Buyer's DID |
| keyPair | AgentKeyPair | Ed25519 keypair for signing |
| timeout? | number | Request timeout in ms. Default: 30000 |
| didResolver? | DIDResolver | Custom resolver for local testing |
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.
generateKeyPair(): AgentKeyPairGenerate a new Ed25519 keypair (32-byte private + public, hex-encoded).
derivePublicKey(privateKeyHex): stringDerive public key from private key.
domainToDid(domain): stringConvert domain to did:web identifier.
didToUrl(did): stringConvert did:web to HTTPS URL for resolution.
createDIDDocument(domain, publicKeyHex): DIDDocumentCreate a W3C DID document.
extractPublicKey(didDocument, keyId?): stringExtract public key from a DID document.
signMessage(payload, privateKeyHex, signerDid): SignedEnvelopeSign 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): stringSign raw string data. Used for attestation proofs.
verifyData(data, signatureHex, publicKeyHex): booleanVerify a raw Ed25519 signature.
verifyContentHash(content, expectedHash): booleanVerify SHA-256 hash. Constant-time comparison.
canonicalize(obj): stringDeterministic JSON serialization with sorted keys.
hashContent(content): stringSHA-256 hash, hex-encoded.
calculateTrustScore(subjectDid, attestations, issuerScores?, now?): TrustScoreResultSingle-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): FullAttestationCreate a signed attestation for IPFS publishing.
verifyAttestation(attestation, issuerPublicKey): { valid, error? }Verify an attestation's Ed25519 proof.
analyzeSybilRisk(subjectDid, allAttestations, thresholds?): SybilAnalysisDetect sybil patterns: self-attestation, concentrated source, closed circuits, temporal clustering.
calculateReliability(data: ReliabilityData): ReliabilityResultQuote acceptance/rejection ratio → reliability score 0-100.
thompsonSelect(candidates, budgetLimit?): SelectionResult | nullThompson Sampling — select best agent under uncertainty.
selectAgent(candidates, config, history?): AgentSelectionResult | nullCombined selection: trust + price + Thompson Sampling.
updateStats(stats, score, price): AgentStatsUpdate 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.
createEscrowAgent(config: EscrowAgentConfig): CommerceAgentCreate a reference escrow agent. Mock or blockchain mode.
verifySettlementReceipt(receipt, escrowPublicKey): { valid, error? }Verify an escrow settlement receipt signature.
createEvaluatorAgent(config: EvaluatorAgentConfig): CommerceAgentCreate a reference evaluator agent. Custom or default heuristic.
matchEscrows(buyerPreferred, sellerAccepted): EscrowMatch[]Find escrow agents accepted by both parties.
selectEscrow(matches): EscrowMatch | nullPick the best escrow from matches.
findBridge(buyerCurrency, sellerCurrency, bridges): BridgeInfo | nullFind a bridge escrow for currency conversion.
verifyProtocolFee(txHash, config): Promise<FeeVerificationResult>Verify 1% fee tx on Base L2 via viem.