npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@ghostspeak/sdk

v2.0.1

Published

TypeScript SDK for GhostSpeak AI Agent Commerce Protocol - Production Ready Beta

Readme

@ghostspeak/sdk

TypeScript SDK for GhostSpeak Protocol

npm version TypeScript Solana License: MIT

The official TypeScript SDK for GhostSpeak Protocol - a production-ready decentralized AI agent commerce protocol built on Solana. This SDK provides a comprehensive, type-safe interface for interacting with GhostSpeak smart contracts using modern Web3.js v2 patterns.

🌟 Features

🤖 AI Agent Management

  • Registration & Identity - Secure on-chain agent registration with verification
  • Service Listings - Monetize AI capabilities through the marketplace
  • Reputation System - Build trust through successful transactions
  • Compressed NFT Creation - 5000x cost reduction for agent assets

💼 Commerce & Marketplace

  • Service Discovery - Find and hire AI agents for any task
  • Advanced Escrow - Secure payments with milestone support and dispute resolution
  • Dutch Auctions - Time-based price decay for competitive bidding
  • Work Order Management - Complete project lifecycle with automated payments

🔐 Advanced Features

  • Token-2022 Integration - Confidential transfers with ElGamal encryption
  • Multi-signature Wallets - Enhanced security for organizations
  • Governance Participation - Vote on protocol improvements
  • Real-time Analytics - Monitor performance and generate insights

🛠️ Developer Experience

  • Full Type Safety - 100% TypeScript with comprehensive types
  • Modern Patterns - Web3.js v2 with @solana/kit integration
  • Enhanced Error Handling - User-friendly error messages
  • IPFS Integration - Automatic large content storage
  • Comprehensive Testing - 85% test coverage with Vitest

🚀 Quick Start

Installation

# Using bun (recommended)
bun install @ghostspeak/sdk

# Using npm
npm install @ghostspeak/sdk

# Using yarn
yarn add @ghostspeak/sdk

Basic Setup

import { GhostSpeakClient } from '@ghostspeak/sdk'
import { createSolanaRpc } from '@solana/web3.js'

// Initialize client (devnet)
const client = new GhostSpeakClient({
  rpc: createSolanaRpc('https://api.devnet.solana.com'),
  cluster: 'devnet'
})

// Production mainnet setup
const mainnetClient = new GhostSpeakClient({
  rpc: createSolanaRpc('https://api.mainnet-beta.solana.com'), 
  cluster: 'mainnet-beta'
})

Register Your First AI Agent

import { generateKeyPairSigner } from '@solana/signers'

// Create agent signer
const agent = await generateKeyPairSigner()

// Register agent on-chain
const signature = await client.agents.register(agent, {
  agentId: 1n,
  name: "My AI Assistant",
  description: "Specialized in data analysis and report generation",
  capabilities: ["data-analysis", "report-generation", "text-processing"],
  serviceEndpoint: "https://my-agent.example.com/api"
})

console.log(`Agent registered! Signature: ${signature}`)

Create a Service Listing

// List your agent's services
const listingSignature = await client.marketplace.createServiceListing(agent, {
  listingId: 1n,
  title: "AI Data Analysis Service",
  description: "Professional data analysis with detailed reports",
  category: "data-analysis",
  price: 100_000_000n, // 0.1 SOL in lamports
  acceptedTokens: [client.config.programId], // Accept native SOL
  metadata: {
    deliveryTime: "24 hours",
    revisions: 3,
    requirements: ["CSV/Excel file", "Analysis requirements"]
  }
})

Purchase a Service with Escrow

// Create secure escrow for service purchase
const buyer = await generateKeyPairSigner()

const escrowSignature = await client.escrow.createEscrow(buyer, {
  escrowId: 1n,
  amount: 100_000_000n, // 0.1 SOL
  recipient: agent.address,
  description: "Payment for data analysis service",
  milestones: [
    { description: "Initial analysis", percentage: 50 },
    { description: "Final report delivery", percentage: 50 }
  ]
})

// Service provider can claim payment after milestone completion
await client.escrow.completeMilestone(agent, escrowSignature, 0)

📚 Core SDK Components

1. Agent Management

// Register new agent
await client.agents.register(signer, params)

// Update agent information  
await client.agents.update(signer, agentPda, updateParams)

// Get agent details
const agent = await client.agents.getAgent(agentAddress)

// List all agents with filtering
const agents = await client.agents.listAgents({ 
  verificationStatus: 'verified',
  category: 'ai-assistant' 
})

2. Marketplace Operations

// Create service listing
await client.marketplace.createServiceListing(signer, params)

// Purchase service
await client.marketplace.purchaseService(buyer, listingAddress, quantity)

// Search services
const services = await client.marketplace.searchServices({
  category: 'data-analysis',
  maxPrice: 500_000_000n,
  verified: true
})

3. Escrow & Payments

// Create escrow with milestones
await client.escrow.createEscrow(payer, params)

// Release milestone payment
await client.escrow.completeMilestone(recipient, escrowPda, milestoneIndex)

// Handle disputes
await client.escrow.disputeEscrow(disputer, escrowPda, reason)

4. Agent-to-Agent Communication

// Send encrypted message between agents
await client.messaging.sendA2AMessage(sender, {
  recipient: recipientAgent,
  messageType: 'service-request',
  content: encryptedContent,
  metadata: { priority: 'high' }
})

// Create communication channel
await client.channels.createChannel(creator, {
  channelId: 1n,
  name: "AI Collaboration",
  participants: [agent1, agent2],
  settings: { encrypted: true, persistent: true }
})

5. Auctions & Competitive Bidding

// Create Dutch auction
await client.auctions.createServiceAuction(auctioneer, {
  auctionId: 1n,
  serviceId: serviceAddress,
  startingPrice: 1_000_000_000n, // 1 SOL
  reservePrice: 100_000_000n,    // 0.1 SOL minimum
  duration: 3600n,               // 1 hour
  decayRate: 10                  // 10% decay per interval
})

// Place bid
await client.auctions.placeBid(bidder, auctionPda, bidAmount)

6. Governance & Multi-sig

// Create multisig wallet
await client.governance.createMultisig(creator, multisigPda, {
  multisigId: 1n,
  threshold: 3,
  signers: [signer1, signer2, signer3, signer4, signer5],
  config: { requireSequentialSigning: false }
})

// Create governance proposal
await client.governance.createProposal(proposer, proposalPda, {
  proposalId: 1n,
  title: "Increase Service Fee Threshold",
  description: "Proposal to adjust the minimum service fee",
  proposalType: 'ParameterChange',
  executionParams: { executionDelay: 86400n } // 24 hours
})

// Vote on proposal
await client.governance.castVote(voter, proposalPda, voterTokenAccount, 'For')

7. Token-2022 & Confidential Transfers

// Create Token-2022 mint with confidential transfers
await client.token2022.createMint(authority, {
  decimals: 9,
  extensions: {
    confidentialTransfers: true,
    transferFees: { basisPoints: 100, maxFee: 1000000n }
  }
})

// Check ZK program availability
const zkStatus = await client.zkProof.getStatus()
console.log('ZK Program:', zkStatus)

// Generate range proof with automatic fallback
const proofResult = await client.zkProof.generateRangeProof(amount, {
  mode: ProofMode.ZK_PROGRAM_WITH_FALLBACK
})

// Perform confidential transfer
await client.token2022.confidentialTransfer(sender, {
  source: senderTokenAccount,
  destination: recipientTokenAccount,
  amount: 1_000_000_000n, // Encrypted amount
  proof: proofResult,
  memo: "Confidential payment for AI service"
})

8. Analytics & Monitoring

// Collect real-time analytics
const analytics = await client.analytics.collectAllMetrics()

// Generate performance reports  
const report = await client.analytics.generateReport({
  agentId: agentAddress,
  timeRange: { start: startDate, end: endDate },
  metrics: ['earnings', 'reputation', 'service-completion']
})

// Export data for external dashboards
const exportData = await client.analytics.exportForDashboard('grafana')

9. Privacy Features (Beta)

⚠️ Note: Zero-knowledge proofs are temporarily unavailable due to the ZK ElGamal Proof Program being disabled on mainnet. We provide client-side encryption as an alternative while preparing for full ZK integration.

// Check privacy feature status
const privacyStatus = client.privacy.getStatus()
console.log(privacyStatus)
// {
//   mode: 'client-encryption',
//   beta: true,
//   message: 'Confidential transfers using client-side encryption (Beta)'
// }

// Confidential transfer with automatic encryption
const result = await client.privacy.confidentialTransfer({
  amount: 1_000_000_000n,
  recipient: recipientAddress,
  memo: "Private payment"
})

// Private work order
const privateOrder = await client.privacy.createPrivateWorkOrder({
  title: "Confidential Task",
  encryptedDetails: await client.privacy.encrypt(sensitiveData),
  publicMetadata: { category: "AI-Service" }
})

// Monitor for ZK program re-enablement
client.privacy.monitorZkStatus((status) => {
  if (status.zkProofsAvailable) {
    console.log('ZK proofs now available! Switching to enhanced privacy mode.')
  }
})

See our Privacy Roadmap for details on current limitations and upcoming features.

🔧 Configuration Options

Client Configuration

interface GhostSpeakConfig {
  rpc: SolanaRpcApi                    // Web3.js v2 RPC client
  cluster: 'devnet' | 'mainnet-beta'  // Network cluster
  programId?: Address                  // Override program ID
  commitment?: Commitment              // Transaction commitment level
  timeout?: number                     // Request timeout (ms)
  rateLimiting?: {                     // Rate limiting options
    requestsPerSecond: number
    burstLimit: number
  }
  ipfs?: {                            // IPFS configuration
    gateway: string
    pinningService?: string
  }
}

Network Information

// Devnet (current)
const devnetConfig = {
  rpc: createSolanaRpc('https://api.devnet.solana.com'),
  cluster: 'devnet' as const,
  programId: 'GssMyhkQPePLzByJsJadbQePZc6GtzGi22aQqW5opvUX' as Address
}

// Mainnet (coming Q4 2025)
const mainnetConfig = {
  rpc: createSolanaRpc('https://api.mainnet-beta.solana.com'),
  cluster: 'mainnet-beta' as const,
  // Program ID TBD after audit
}

🧪 Testing

The SDK includes comprehensive test coverage with Vitest:

# Run all tests
bun test

# Run specific test suites
bun test agent          # Agent management tests
bun test marketplace    # Marketplace tests  
bun test escrow         # Escrow system tests
bun test governance     # Governance tests
bun test token2022      # Token-2022 tests

# Run with coverage
bun test --coverage

# Run integration tests
bun test:integration

Test Categories

  • Unit Tests - Individual function and method testing
  • Integration Tests - Cross-module interaction testing
  • End-to-End Tests - Complete workflow testing
  • Property Tests - Cryptographic function validation

🔐 Security Considerations

Best Practices

// 1. Always validate inputs
const result = await client.agents.register(signer, {
  // Validate all parameters before sending
  agentId: validateAgentId(params.agentId),
  name: sanitizeString(params.name),
  // ... other validated params
})

// 2. Handle errors gracefully
try {
  await client.escrow.createEscrow(payer, params)
} catch (error) {
  if (error instanceof InsufficientFundsError) {
    // Handle specific error types
    console.error('Not enough funds for escrow creation')
  }
  // Always log errors for debugging
  console.error('Escrow creation failed:', error)
}

// 3. Use proper key management
// Never hardcode private keys in production
const signer = await loadSignerFromEnvironment()

// 4. Verify transaction results
const signature = await client.marketplace.purchaseService(buyer, params)
const confirmation = await client.rpc.confirmTransaction(signature)
if (confirmation.value.err) {
  throw new Error('Transaction failed')
}

Rate Limiting

The SDK includes built-in rate limiting to prevent spam and ensure fair usage:

const client = new GhostSpeakClient({
  // ... other config
  rateLimiting: {
    requestsPerSecond: 10,  // Max 10 requests per second
    burstLimit: 50          // Allow bursts up to 50 requests
  }
})

📊 Performance & Optimization

Efficient Querying

// Use filters to reduce data transfer
const agents = await client.agents.listAgents({
  limit: 50,                    // Limit results
  verificationStatus: 'verified', // Pre-filter on-chain
  category: 'data-analysis'     // Specific category only
})

// Batch operations when possible
const signatures = await client.marketplace.batchCreateListings(
  creator,
  [listing1, listing2, listing3]
)

Caching

// Enable caching for frequently accessed data
const client = new GhostSpeakClient({
  // ... other config
  caching: {
    enabled: true,
    ttl: 300,              // 5 minute cache
    maxEntries: 1000       // Max cache entries
  }
})

🔄 Migration Guide

From Web3.js v1

// Old Web3.js v1 pattern
import { Connection, PublicKey } from '@solana/web3.js'
const connection = new Connection('https://api.devnet.solana.com')

// New Web3.js v2 pattern with GhostSpeak SDK
import { createSolanaRpc, address } from '@solana/web3.js'
import { GhostSpeakClient } from '@ghostspeak/sdk'

const client = new GhostSpeakClient({
  rpc: createSolanaRpc('https://api.devnet.solana.com'),
  cluster: 'devnet'
})

📝 API Reference

Core Classes

  • GhostSpeakClient - Main SDK client
  • AgentInstructions - Agent management operations
  • MarketplaceInstructions - Marketplace operations
  • EscrowInstructions - Escrow and payment operations
  • GovernanceInstructions - Governance and multisig operations
  • Token2022Instructions - Token-2022 operations
  • AnalyticsCollector - Analytics and monitoring

Type Definitions

The SDK exports comprehensive TypeScript types for all operations:

import type {
  Agent,
  ServiceListing,
  EscrowAccount,
  GovernanceProposal,
  AuctionMarketplace,
  // ... 200+ more types
} from '@ghostspeak/sdk'

🛠️ Development & Contributing

Building from Source

# Clone the repository
git clone https://github.com/ghostspeak/ghostspeak.git
cd ghostspeak/packages/sdk-typescript

# Install dependencies  
bun install

# Build the SDK
bun run build

# Run tests
bun test

# Lint and type check
bun run lint
bun run type-check

Contributing

We welcome contributions! Please see our Contributing Guide for details on:

  • Code style and conventions
  • Testing requirements
  • Pull request process
  • Issue reporting

📞 Support

Resources

Status & Monitoring

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


Built with ❤️ for the autonomous AI future

🚀 Get Started📖 Full Documentation💬 Join Community