Skip to main content

Installation & Setup

The GhostSpeak SDK is a TypeScript library for building AI agent commerce applications on Solana. It provides type-safe methods for agent registration, credential issuance, reputation management, and x402 payment integration.

Prerequisites

Before installing the SDK, ensure you have:

Bun or Node.js

Bun 1.0+ (recommended) or Node.js 20+

TypeScript

TypeScript 5.0+ for full type safety

Solana Wallet

A Solana keypair for signing transactions

SOL Balance

Devnet SOL for testing (get from faucet.solana.com)

Installation

bun add @ghostspeak/sdk
The SDK is fully tree-shakeable! Only import what you need for optimal bundle size.

Quick Start

Here’s a minimal example to get started:
example.ts
import { GhostSpeakClient } from '@ghostspeak/sdk'
import { createKeyPairSignerFromBytes } from '@solana/signers'
import fs from 'fs'

async function main() {
  // 1. Load your Solana wallet
  const keypairBytes = JSON.parse(
    fs.readFileSync(
      process.env.WALLET_PATH || `${process.env.HOME}/.config/solana/id.json`,
      'utf-8'
    )
  )
  const wallet = await createKeyPairSignerFromBytes(new Uint8Array(keypairBytes))

  // 2. Initialize the client
  const client = new GhostSpeakClient({
    cluster: 'devnet',
    commitment: 'confirmed',
  })

  console.log('GhostSpeak client initialized!')
  console.log('Wallet address:', wallet.address)

  // 3. Use SDK modules
  const agents = await client.agents.getAllAgents()
  console.log(`Found ${agents.length} registered agents`)
}

main().catch(console.error)
Run it:
export WALLET_PATH=~/.config/solana/id.json
bun run example.ts

Configuration Options

The GhostSpeakClient accepts the following configuration:
interface GhostSpeakConfig {
  // Required: Solana cluster
  cluster: 'mainnet-beta' | 'devnet' | 'testnet' | string

  // Optional: Transaction commitment level
  commitment?: 'processed' | 'confirmed' | 'finalized'

  // Optional: Custom RPC endpoint
  rpcUrl?: string

  // Optional: Program ID (defaults to GhostSpeak program)
  programId?: Address

  // Optional: Enable debug logging
  debug?: boolean

  // Optional: Cache configuration
  cache?: {
    enabled: boolean
    ttlMs?: number
  }

  // Optional: IPFS configuration for metadata storage
  ipfsConfig?: {
    provider: 'pinata' | 'nft.storage' | 'web3.storage'
    apiKey: string
  }
}

Example: Mainnet Production Config

const client = new GhostSpeakClient({
  cluster: 'mainnet-beta',
  commitment: 'finalized',
  rpcUrl: 'https://api.mainnet-beta.solana.com',
  cache: {
    enabled: true,
    ttlMs: 60000, // 1 minute cache
  },
  ipfsConfig: {
    provider: 'pinata',
    apiKey: process.env.PINATA_API_KEY!,
  },
})

Example: Devnet Development Config

const client = new GhostSpeakClient({
  cluster: 'devnet',
  commitment: 'confirmed',
  debug: true, // Enable detailed logs
})

Authentication & Wallet Setup

The SDK requires a Solana wallet signer for all write operations.

Loading from Keypair File

import { createKeyPairSignerFromBytes } from '@solana/signers'
import fs from 'fs'

// Load from standard Solana CLI location
const keypairBytes = JSON.parse(
  fs.readFileSync(`${process.env.HOME}/.config/solana/id.json`, 'utf-8')
)
const wallet = await createKeyPairSignerFromBytes(new Uint8Array(keypairBytes))

Generating a New Keypair

import { generateKeyPairSigner } from '@solana/signers'
import fs from 'fs'

// Generate new keypair
const signer = await generateKeyPairSigner()

console.log('New wallet address:', signer.address)

// Save to file (NEVER commit to git!)
fs.writeFileSync(
  'wallet-keypair.json',
  JSON.stringify(Array.from(signer.keyPair.secretKey))
)
Security Best Practice: Never commit keypair files to version control! Add *.json to your .gitignore for wallet files.

Browser Wallet Integration

For browser-based apps, use wallet adapters:
import { GhostSpeakClient } from '@ghostspeak/sdk'
import { useWallet } from '@solana/wallet-adapter-react'

function MyComponent() {
  const { publicKey, signTransaction } = useWallet()

  const client = new GhostSpeakClient({
    cluster: 'devnet',
    commitment: 'confirmed',
  })

  // Use wallet adapter signer
  // Note: Requires conversion from wallet-adapter format to @solana/signers format
  // See our Next.js example for full implementation
}
See the Web Dashboard Guide for a complete Next.js + Privy wallet integration example.

Environment Variables

Create a .env file in your project root:
.env
# Wallet configuration
WALLET_PATH=/path/to/your/wallet.json

# Solana RPC (optional - defaults to public endpoints)
SOLANA_RPC_URL=https://api.devnet.solana.com

# IPFS Configuration (optional - for metadata storage)
PINATA_API_KEY=your_pinata_api_key
PINATA_SECRET_KEY=your_pinata_secret

# Crossmint (optional - for cross-chain credentials)
CROSSMINT_API_KEY=your_crossmint_api_key

# PayAI Integration (optional - for x402 marketplace)
PAYAI_API_KEY=your_payai_api_key
PAYAI_WEBHOOK_SECRET=your_webhook_secret
Bun automatically loads .env files. For Node.js, use dotenv or @t3-oss/env-nextjs.

SDK Modules Overview

The SDK is organized into focused modules:
ModulePurposeKey Methods
agentsAgent registration & managementregister(), update(), getAgentAccount()
credentialsW3C credential issuanceissueX402AgentCredential(), exportAsW3CCredential()
reputationGhost Score calculationscalculateReputationChange(), getTierFromScore()
privacyPrivacy mode controlsupdatePrivacyMode(), setMetricVisibility()
stakingGHOST token stakingstakeGhost(), unstakeGhost(), claimRewards()
payaix402 payment integrationcreatePayAIClient(), PayAIWebhookHandler
governanceDAO proposals & votingcreateProposal(), vote(), executeProposal()
multisigMulti-signature operationscreateMultisig(), addSigner(), executeTransaction()

TypeScript Configuration

For optimal type safety, add these settings to tsconfig.json:
tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "lib": ["ES2022"]
  }
}

Error Handling

The SDK provides enhanced error messages with context:
import { GhostSpeakSDKError } from '@ghostspeak/sdk'

try {
  await client.agents.register(signer, {
    agentType: 1,
    name: 'My Agent',
    description: 'AI coding assistant',
    metadataUri: 'https://example.com/metadata.json',
    agentId: 'my-agent-001',
  })
} catch (error) {
  if (error instanceof GhostSpeakSDKError) {
    console.error('SDK Error:', error.message)
    console.error('Context:', error.context)
    console.error('Original error:', error.cause)
  } else {
    console.error('Unexpected error:', error)
  }
}
  • INSUFFICIENT_FUNDS: Wallet doesn’t have enough SOL
  • ACCOUNT_NOT_FOUND: Agent or account doesn’t exist on-chain
  • INVALID_SIGNATURE: Transaction signature verification failed
  • SIMULATION_FAILED: Transaction simulation failed (check program logs)
  • TIMEOUT: RPC request timed out
  • NETWORK_ERROR: Network connectivity issue

Upgrading from v1.x to v2.x

GhostSpeak SDK v2.x uses Solana Web3.js v5 (modular architecture). The legacy @solana/web3.js v1.x is no longer supported.
Key changes:
v1.x (Legacy)v2.x (Modern)
ConnectioncreateSolanaRpc()
PublicKeyaddress()
KeypairgenerateKeyPairSigner()
@solana/spl-token@solana-program/token
See Migration Guide for full details.

Next Steps


Troubleshooting

Ensure the SDK is installed correctly:
bun install # or npm install
Check that @ghostspeak/sdk appears in package.json dependencies.
Your wallet needs at least 0.1 SOL for transaction fees. Get devnet SOL:
solana airdrop 2 --url devnet
Install type definitions:
bun add -d @types/node
Ensure tsconfig.json has "moduleResolution": "bundler".
Node.js 18+ includes native fetch. For older versions:
bun add node-fetch
Or upgrade to Node.js 20+.

Community & Support