@ghostspeak/sdk
Version:
TypeScript SDK for GhostSpeak AI Agent Commerce Protocol - Production Ready Beta
1,598 lines (1,553 loc) • 78.9 kB
TypeScript
import { Address as Address$1 } from '@solana/addresses';
import { ReadonlyUint8Array, Option, Address, Decoder, EncodedAccount, Account, MaybeEncodedAccount, MaybeAccount, fetchEncodedAccount, FetchAccountConfig, FixedSizeDecoder, AccountMeta, Instruction, InstructionWithData, InstructionWithAccounts, WritableAccount, WritableSignerAccount, AccountSignerMeta, ReadonlyAccount, Commitment as Commitment$1, Rpc, GetLatestBlockhashApi, SendTransactionApi, GetAccountInfoApi, SimulateTransactionApi, GetFeeForMessageApi, GetProgramAccountsApi, GetEpochInfoApi, GetSignatureStatusesApi, GetMultipleAccountsApi, RpcSubscriptions, SignatureNotificationsApi, SlotNotificationsApi, AccountRole, TransactionSigner, Signature as Signature$1 } from '@solana/kit';
import { I as IPFSConfig, G as GovernanceProposal, n as ProposalTypeArgs, E as ExecutionParamsArgs, o as CategoryReputation, B as BadgeType, J as JobPerformance, a as ReputationCalculationResult, p as ReputationTier, b as ReputationMetrics, c as TagScore, q as TagCategory, d as TagFilters, e as TagQueryResult } from './reputation-types-Yebf0Rm_.js';
import { ParticipantType } from './types.js';
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
/** Access tiers based on GHOST token stake amount */
declare enum AccessTier {
None = 0,
Basic = 1,
Verified = 2,
Pro = 3,
Whale = 4
}
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
/** Agent lifecycle status (Ghost Identity) */
declare enum AgentStatus {
Unregistered = 0,
Registered = 1,
Claimed = 2,
Verified = 3
}
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
/** Cross-platform identity mapping */
type ExternalIdentifier = {
platform: string;
externalId: string;
verified: boolean;
verifiedAt: bigint;
};
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
/**
* MultisigType defines the governance layer a multisig belongs to.
* Different types have different permissions and requirements.
*/
declare enum MultisigType {
Protocol = 0,
Dao = 1,
Dispute = 2,
AgentConsortium = 3,
AgentTreasury = 4,
Custom = 5
}
type MultisigTypeArgs = MultisigType;
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
type MultisigTypeConfigArgs = {
/** The multisig type */
multisigType: MultisigTypeArgs;
/** Required timelock duration in seconds (0 = no timelock) */
timelockSeconds: number | bigint;
/** Minimum number of signers allowed */
minSigners: number;
/** Maximum number of signers allowed */
maxSigners: number;
/** Minimum reputation score required (0-10000 basis points) */
minReputationScore: number;
/** Whether signers must hold governance tokens */
requiresTokenHoldings: boolean;
/** Minimum token balance required (if requires_token_holdings) */
minTokenBalance: number | bigint;
};
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
declare enum PricingModel$1 {
Fixed = 0,
Hourly = 1,
PerTask = 2,
Subscription = 3,
Auction = 4,
Dynamic = 5,
RevenueShare = 6,
Tiered = 7
}
type PricingModelArgs = PricingModel$1;
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
/** Reputation component for multi-source Ghost Score */
type ReputationComponent = {
sourceType: ReputationSourceType;
score: bigint;
weight: number;
lastUpdated: bigint;
dataPoints: bigint;
};
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
/** Multi-source reputation types for Ghost Score */
declare enum ReputationSourceType {
AccountAge = 0,
X402Transactions = 1,
UserReviews = 2,
ElizaOSReputation = 3,
CrossmintVerification = 4,
EndpointReliability = 5,
JobCompletions = 6,
SkillEndorsements = 7
}
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
type Agent = {
discriminator: ReadonlyUint8Array;
owner: Option<Address>;
status: AgentStatus;
agentId: string;
firstTxSignature: string;
firstSeenTimestamp: bigint;
discoverySource: string;
claimedAt: Option<bigint>;
agentType: number;
name: string;
description: string;
capabilities: Array<string>;
pricingModel: PricingModel$1;
reputationScore: number;
totalJobsCompleted: number;
totalEarnings: bigint;
isActive: boolean;
createdAt: bigint;
updatedAt: bigint;
originalPrice: bigint;
genomeHash: string;
isReplicable: boolean;
replicationFee: bigint;
serviceEndpoint: string;
isVerified: boolean;
verificationTimestamp: bigint;
metadataUri: string;
frameworkOrigin: string;
supportedTokens: Array<Address>;
cnftMint: Option<Address>;
merkleTree: Option<Address>;
supportsA2a: boolean;
transferHook: Option<Address>;
parentAgent: Option<Address>;
generation: number;
x402Enabled: boolean;
x402PaymentAddress: Address;
x402AcceptedTokens: Array<Address>;
x402PricePerCall: bigint;
x402ServiceEndpoint: string;
x402TotalPayments: bigint;
x402TotalCalls: bigint;
lastPaymentTimestamp: bigint;
externalIdentifiers: Array<ExternalIdentifier>;
ghostScore: bigint;
reputationComponents: Array<ReputationComponent>;
didAddress: Option<Address>;
credentials: Array<Address>;
apiSpecUri: string;
apiVersion: string;
bump: number;
};
/** Gets the decoder for {@link Agent} account data. */
declare function getAgentDecoder(): Decoder<Agent>;
declare function decodeAgent<TAddress extends string = string>(encodedAccount: EncodedAccount<TAddress>): Account<Agent, TAddress>;
declare function decodeAgent<TAddress extends string = string>(encodedAccount: MaybeEncodedAccount<TAddress>): MaybeAccount<Agent, TAddress>;
declare function fetchAgent<TAddress extends string = string>(rpc: Parameters<typeof fetchEncodedAccount>[0], address: Address<TAddress>, config?: FetchAccountConfig): Promise<Account<Agent, TAddress>>;
declare function fetchMaybeAgent<TAddress extends string = string>(rpc: Parameters<typeof fetchEncodedAccount>[0], address: Address<TAddress>, config?: FetchAccountConfig): Promise<MaybeAccount<Agent, TAddress>>;
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
type StakingAccount = {
discriminator: ReadonlyUint8Array;
/** Owner of this staking account (can register multiple agents) */
owner: Address;
/** Amount of GHOST tokens staked */
amountStaked: bigint;
/** Timestamp when staking started */
stakedAt: bigint;
/** Lock duration in seconds (minimum 30 days) */
lockDuration: bigint;
/** Timestamp when unlock is available */
unlockAt: bigint;
/** Reputation boost percentage (in basis points, e.g., 500 = 5%) */
reputationBoostBps: number;
/** Whether agent has "Verified" badge */
hasVerifiedBadge: boolean;
/** Whether agent has premium listing benefits */
hasPremiumBenefits: boolean;
/** Total slashed amount (never recoverable) */
totalSlashed: bigint;
/** Current access tier based on stake amount */
tier: AccessTier;
/** Daily API calls remaining (resets every 24h) */
apiCallsRemaining: number;
/** Last API quota reset timestamp */
lastQuotaReset: bigint;
/** Voting power for governance (equals amount_staked) */
votingPower: bigint;
/** Bump for PDA */
bump: number;
};
/** Gets the decoder for {@link StakingAccount} account data. */
declare function getStakingAccountDecoder(): FixedSizeDecoder<StakingAccount>;
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
type StakingConfig = {
discriminator: ReadonlyUint8Array;
/** Authority who can update staking parameters */
authority: Address;
/** Minimum stake amount (1,000 GHOST) */
minStake: bigint;
/** Minimum lock duration (30 days in seconds) */
minLockDuration: bigint;
/** Slash percentage for fraud (50% = 5000 bps) */
fraudSlashBps: number;
/** Slash percentage for dispute loss (10% = 1000 bps) */
disputeSlashBps: number;
/** Treasury account for slashed tokens */
treasury: Address;
bump: number;
};
/** Gets the decoder for {@link StakingConfig} account data. */
declare function getStakingConfigDecoder(): FixedSizeDecoder<StakingConfig>;
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
declare const GHOSTSPEAK_MARKETPLACE_PROGRAM_ADDRESS: Address<"4wHjA2a5YC4twZb4NQpwZpixo5FgxxzuJUrCG7UnF9pB">;
/**
* This code was AUTOGENERATED using the Codama library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun Codama to update it.
*
* @see https://github.com/codama-idl/codama
*/
type InitializeGovernanceProposalInstruction<TProgram extends string = typeof GHOSTSPEAK_MARKETPLACE_PROGRAM_ADDRESS, TAccountProposal extends string | AccountMeta<string> = string, TAccountProposer extends string | AccountMeta<string> = string, TAccountSystemProgram extends string | AccountMeta<string> = "11111111111111111111111111111111", TRemainingAccounts extends readonly AccountMeta<string>[] = []> = Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array> & InstructionWithAccounts<[
TAccountProposal extends string ? WritableAccount<TAccountProposal> : TAccountProposal,
TAccountProposer extends string ? WritableSignerAccount<TAccountProposer> & AccountSignerMeta<TAccountProposer> : TAccountProposer,
TAccountSystemProgram extends string ? ReadonlyAccount<TAccountSystemProgram> : TAccountSystemProgram,
...TRemainingAccounts
]>;
/**
* CacheManager - Slot-aware RPC result caching
*
* Reduces RPC calls by caching account data and PDA derivations
* with commitment-level aware TTLs.
*
* @module CacheManager
*/
/**
* Cache configuration options
*/
interface CacheConfig {
/** Enable caching (default: false, opt-in) */
enabled?: boolean;
/** Maximum cache entries (default: 1000) */
maxSize?: number;
/** Custom TTL overrides (milliseconds) */
ttlOverrides?: {
processed?: number;
confirmed?: number;
finalized?: number;
};
}
/**
* CacheManager handles slot-aware caching for RPC results
*
* Features:
* - Commitment-level TTLs (finalized=30s, confirmed=2s, processed=500ms)
* - Indefinite PDA caching (deterministic addresses)
* - LRU eviction policy
* - Opt-in (disabled by default)
*/
declare class CacheManager {
private accountCache;
private pdaCache;
private config;
private ttls;
constructor(config?: CacheConfig);
/**
* Check if caching is enabled
*/
isEnabled(): boolean;
/**
* Get cached account data
*
* @param address - Account address
* @param commitment - Commitment level
* @param currentSlot - Current blockchain slot (for staleness check)
* @returns Cached data or undefined
*/
getAccount<T>(address: Address$1, commitment: Commitment$1, currentSlot?: number): T | undefined;
/**
* Cache account data
*
* @param address - Account address
* @param data - Account data to cache
* @param commitment - Commitment level
* @param slot - Blockchain slot when data was fetched
*/
setAccount<T>(address: Address$1, data: T, commitment: Commitment$1, slot: number): void;
/**
* Get cached PDA
*
* PDAs are cached indefinitely as they're deterministic.
*
* @param seeds - Serialized seed components
* @returns Cached PDA or undefined
*/
getPDA(seeds: string): Address$1 | undefined;
/**
* Cache PDA derivation
*
* @param seeds - Serialized seed components (use JSON.stringify for consistency)
* @param pda - Derived PDA address
*/
setPDA(seeds: string, pda: Address$1): void;
/**
* Invalidate account cache entry
*
* @param address - Account address to invalidate
* @param commitment - Optional commitment level (invalidates all if not specified)
*/
invalidateAccount(address: Address$1, commitment?: Commitment$1): void;
/**
* Clear all caches
*/
clear(): void;
/**
* Get cache statistics
*
* @returns Cache size and hit/miss stats
*/
getStats(): {
accountCache: {
size: number;
max: number;
};
pdaCache: {
size: number;
max: number;
};
};
}
type RpcApi = Rpc<GetLatestBlockhashApi & SendTransactionApi & GetAccountInfoApi & SimulateTransactionApi & GetFeeForMessageApi & GetProgramAccountsApi>;
type ExtendedRpcApi = RpcApi & Rpc<GetEpochInfoApi & GetSignatureStatusesApi & GetMultipleAccountsApi>;
type RpcSubscriptionApi = RpcSubscriptions<SignatureNotificationsApi & SlotNotificationsApi>;
type Commitment = 'processed' | 'confirmed' | 'finalized';
interface GhostSpeakConfig {
programId?: Address$1;
rpc: ExtendedRpcApi;
rpcSubscriptions?: RpcSubscriptionApi;
commitment?: Commitment;
transactionTimeout?: number;
defaultFeePayer?: Address$1;
retryConfig?: RetryConfig;
cluster?: 'mainnet-beta' | 'devnet' | 'testnet' | 'localnet';
rpcEndpoint?: string;
wsEndpoint?: string;
/** Optional logger for debug output */
logger?: {
info: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
};
/** Cache configuration for RPC result caching */
cache?: CacheConfig;
/** Token 2022 configuration options */
token2022?: Token2022Config;
/** IPFS configuration for large content storage */
ipfsConfig?: IPFSConfig;
/** Credential configuration for Crossmint sync */
credentials?: CredentialConfig;
}
interface CredentialConfig {
crossmintApiKey?: string;
crossmintEnvironment?: 'staging' | 'production';
crossmintChain?: 'base-sepolia' | 'polygon-amoy' | 'base' | 'polygon';
templates?: {
agentIdentity?: string;
reputation?: string;
jobCompletion?: string;
};
}
interface Token2022Config {
/** Enable Token 2022 features by default */
enabled?: boolean;
/** Default behavior for transfer fees */
defaultExpectTransferFees?: boolean;
/** Maximum transfer fee slippage (basis points) */
maxFeeSlippageBasisPoints?: number;
/** Enable confidential transfers by default */
enableConfidentialTransfers?: boolean;
/** Default Token 2022 program address (for custom deployments) */
programAddress?: Address$1;
/** Cache token program detection results for this many seconds */
tokenProgramCacheTtl?: number;
}
interface RetryConfig {
maxRetries?: number;
baseDelay?: number;
maxDelay?: number;
backoffMultiplier?: number;
retryableErrors?: string[];
}
interface AgentWithAddress {
address: Address$1;
data: Agent;
}
interface AgentRegistrationData {
agentId: string;
name: string;
description: string;
metadataUri: string;
agentType: number;
}
interface AgentAccount {
owner: Address$1;
name: string;
description: string;
capabilities: string[];
metadataUri: string;
serviceEndpoint: string;
isActive: boolean;
registeredAt: bigint;
reputation: number;
totalEarnings: bigint;
totalJobs: number;
successRate: number;
bump: number;
}
declare enum PricingModel {
Fixed = "Fixed",
Hourly = "Hourly",
PerTask = "PerTask",
Subscription = "Subscription",
Auction = "Auction"
}
declare class GhostSpeakError extends Error {
code?: string | undefined;
constructor(message: string, code?: string | undefined);
}
interface RegisterAgentParams {
agentData: AgentRegistrationData;
}
interface RpcResponse<T> {
value: T | null;
}
interface RpcAccountInfo {
executable: boolean;
lamports: bigint;
owner: Address$1;
rentEpoch: bigint;
space: bigint;
data: string | Uint8Array;
}
interface RpcProgramAccount {
pubkey: Address$1;
account: RpcAccountInfo;
}
interface RpcProgramAccountsResponse {
value: RpcProgramAccount[] | null;
}
interface RpcAccountInfoResponse {
value: RpcAccountInfo | null;
}
interface RpcMultipleAccountsResponse {
value: (RpcAccountInfo | null)[];
}
interface TransactionResponse {
signature: string;
confirmationStatus?: Commitment;
err?: unknown | null;
}
interface SimulatedTransactionResponse {
value: {
err?: unknown | null;
logs?: string[];
unitsConsumed?: number;
};
}
interface SolanaRpcClient {
getAccountInfo(address: Address$1, options?: {
commitment?: Commitment;
encoding?: string;
}): Promise<RpcAccountInfoResponse>;
getMultipleAccounts(addresses: Address$1[], options?: {
commitment?: Commitment;
encoding?: string;
}): Promise<RpcMultipleAccountsResponse>;
getProgramAccounts(programId: Address$1, options?: {
commitment?: Commitment;
encoding?: string;
filters?: unknown[];
}): Promise<RpcProgramAccountsResponse>;
sendTransaction(transaction: unknown, options?: {
commitment?: Commitment;
}): Promise<TransactionResponse>;
simulateTransaction(transaction: unknown, options?: {
commitment?: Commitment;
}): Promise<SimulatedTransactionResponse>;
}
interface EmergencyConfig {
emergencyDelay?: bigint;
emergencyThreshold?: number;
emergencySigners?: Address$1[];
canEmergencyPause?: boolean;
emergencyContact?: string;
}
/**
* Developer Tools for GhostSpeak SDK
*
* Provides debugging, inspection, and development utilities
*/
/**
* Transaction analysis result
*/
interface TransactionAnalysis {
instructions: InstructionAnalysis[];
totalAccounts: number;
signerCount: number;
writableAccounts: Address$1[];
readonlyAccounts: Address$1[];
estimatedSize: number;
estimatedComputeUnits: bigint;
estimatedFee: bigint;
warnings: string[];
}
/**
* Individual instruction analysis
*/
interface InstructionAnalysis {
index: number;
programId: Address$1;
accountCount: number;
dataSize: number;
humanReadable: string;
accounts: AccountInfo[];
}
/**
* Account information in instruction
*/
interface AccountInfo {
address: Address$1;
isWritable: boolean;
isSigner: boolean;
role: AccountRole;
}
/**
* Type for instruction-like objects from generated code
*/
type InstructionLike = {
programAddress: Address$1;
accounts?: readonly unknown[];
data?: unknown;
};
/**
* Unified instruction builder that eliminates duplication across all instruction classes.
* This is the single source of truth for instruction execution patterns.
*/
declare class InstructionBuilder {
private rpcClient;
private config;
private devTools;
private debugMode;
constructor(config: GhostSpeakConfig);
/**
* Execute a single instruction with unified error handling and transaction patterns
*/
execute<T = string>(instructionName: string, instructionGetter: () => Promise<InstructionLike> | InstructionLike, signers: TransactionSigner[], options?: {
simulate?: boolean;
returnDetails?: boolean;
skipPreflight?: boolean;
maxRetries?: number;
}): Promise<T>;
/**
* Execute multiple instructions in a single transaction
*/
executeBatch<T = string>(batchName: string, instructionGetters: (() => Promise<InstructionLike> | InstructionLike)[], signers: TransactionSigner[], options?: {
simulate?: boolean;
returnDetails?: boolean;
skipPreflight?: boolean;
}): Promise<T>;
/**
* Get and decode account data with unified error handling
*/
getAccount<T>(address: Address$1, decoderImportName: string): Promise<T | null>;
/**
* Get multiple accounts with unified pattern
*/
getAccounts<T>(addresses: Address$1[], decoderImportName: string): Promise<(T | null)[]>;
/**
* Get program accounts with filters
*/
getProgramAccounts<T>(decoderImportName: string, filters?: ({
dataSize: bigint;
} | {
memcmp: {
offset: bigint;
bytes: string;
encoding?: 'base58' | 'base64';
};
})[]): Promise<{
address: Address$1;
data: T;
}[]>;
/**
* Enable debug mode for next transaction
*/
enableDebug(): this;
/**
* Debug transaction - analyze without executing
*/
debug(instructionName: string, instructionGetters: (() => Promise<InstructionLike> | InstructionLike)[]): Promise<TransactionAnalysis>;
/**
* Get human-readable explanation of transaction
*/
explain(instructionName: string, instructionGetters: (() => Promise<InstructionLike> | InstructionLike)[]): Promise<string>;
/**
* Estimate transaction cost
*/
estimateCost(instructionGetters: (() => Promise<InstructionLike> | InstructionLike)[]): Promise<bigint>;
private sendAndConfirm;
private simulateInstruction;
private simulateBatch;
private estimateTransactionSize;
private extractRawData;
/**
* Create a communication session instruction
*/
createCommunicationSession(_params: {
sessionId: bigint;
initiator: Address$1;
initiatorType: ParticipantType;
responder: Address$1;
responderType: ParticipantType;
sessionType: string;
metadata: string;
expiresAt: bigint;
}): Promise<InstructionLike>;
/**
* Send a communication message instruction
*/
sendCommunicationMessage(_sessionAddress: Address$1, _params: {
messageId: bigint;
senderType: unknown;
content: string;
messageType: string;
attachments: string[];
}): Promise<InstructionLike>;
/**
* Update participant status instruction
*/
updateParticipantStatus(_params: {
participant: Address$1;
participantType: unknown;
servicesOffered: string[];
availability: boolean;
reputationScore: number;
}): Promise<InstructionLike>;
}
/**
* Solana cluster types for URL generation
*/
type SolanaCluster = 'mainnet-beta' | 'devnet' | 'testnet' | 'localnet';
/**
* Transaction result with verification URLs
*/
interface TransactionResult {
signature: string | Signature$1;
cluster: SolanaCluster;
urls: {
solanaExplorer: string;
solscan: string;
solanaFM: string;
xray: string;
};
commitment: Commitment;
timestamp: number;
}
type Signature = string;
type IInstruction = Instruction;
/**
* Base class for all instruction modules using the unified InstructionBuilder.
* This replaces the old BaseInstructions class with a much simpler pattern.
*/
declare abstract class BaseModule {
protected builder: InstructionBuilder;
protected config: GhostSpeakConfig;
protected logger?: {
info: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
};
protected cacheManager: CacheManager;
private _debugMode;
constructor(config: GhostSpeakConfig);
/**
* Enable debug mode for next operation
*/
debug(): this;
/**
* Execute a single instruction
*/
protected execute(instructionName: string, instructionGetter: () => Promise<IInstruction> | IInstruction, signers: TransactionSigner[]): Promise<string>;
/**
* Execute a single instruction with detailed result
*/
protected executeWithDetails(instructionName: string, instructionGetter: () => Promise<IInstruction> | IInstruction, signers: TransactionSigner[]): Promise<TransactionResult>;
/**
* Execute multiple instructions in a batch
*/
protected executeBatch(batchName: string, instructionGetters: (() => Promise<IInstruction> | IInstruction)[], signers: TransactionSigner[]): Promise<Signature>;
/**
* Simulate an instruction
*/
protected simulate(instructionName: string, instructionGetter: () => Promise<IInstruction> | IInstruction, signers: TransactionSigner[]): Promise<unknown>;
/**
* Simulate an instruction (public accessor)
*/
simulateInstruction(instructionName: string, instructionGetter: () => Promise<IInstruction> | IInstruction, signers: TransactionSigner[]): Promise<unknown>;
/**
* Estimate transaction cost
*/
protected estimateCost(instructionGetters: (() => Promise<IInstruction> | IInstruction)[]): Promise<bigint>;
/**
* Get cost estimation for an instruction
*/
getCost(instructionName: string, instructionGetter: () => Promise<IInstruction> | IInstruction): Promise<bigint>;
/**
* Get human-readable explanation
*/
explain(instructionName: string, instructionGetter: () => Promise<IInstruction> | IInstruction): Promise<string>;
/**
* Debug analyze without executing
*/
analyze(instructionName: string, instructionGetter: () => Promise<IInstruction> | IInstruction): Promise<unknown>;
/**
* Get decoded account (with optional caching)
*/
protected getAccount<T>(address: Address$1, decoderImportName: string): Promise<T | null>;
/**
* Get multiple decoded accounts (with optional caching)
*/
protected getAccounts<T>(addresses: Address$1[], decoderImportName: string): Promise<(T | null)[]>;
/**
* Get program accounts
*/
protected getProgramAccounts<T>(decoderImportName: string, filters?: ({
dataSize: bigint;
} | {
memcmp: {
offset: bigint;
bytes: string;
encoding?: 'base58' | 'base64';
};
})[]): Promise<{
address: Address$1;
data: T;
}[]>;
/**
* Get program ID
*/
protected get programId(): Address$1;
/**
* Get program ID (public accessor)
*/
getProgramId(): Address$1;
/**
* Get commitment level
*/
protected get commitment(): Commitment;
/**
* Get commitment level (public accessor)
*/
getCommitment(): Commitment;
/**
* Invalidate cache for specific account
*/
invalidateCache(address: Address$1): void;
/**
* Clear all caches
*/
clearCache(): void;
/**
* Get cache statistics
*/
getCacheStats(): {
accountCache: {
size: number;
max: number;
};
pdaCache: {
size: number;
max: number;
};
};
}
/**
* Simplified agent management using unified instruction pattern
*/
declare class AgentModule extends BaseModule {
private ipfsUtils;
constructor(config: GhostSpeakConfig & {
ipfsConfig?: IPFSConfig;
});
/**
* Register a new agent
*/
register(signer: TransactionSigner, params: {
agentType: number;
name: string;
description: string;
metadataUri: string;
agentId: string;
pricingModel?: PricingModel$1;
skipSimulation?: boolean;
}): Promise<string>;
/**
* Register a compressed agent (5000x cheaper)
*/
registerCompressed(signer: TransactionSigner, params: {
agentType: number;
name: string;
description: string;
metadataUri: string;
agentId: string;
merkleTree: Address$1;
treeConfig?: Address$1;
pricingModel?: PricingModel$1;
}): Promise<string>;
/**
* Update agent metadata
*/
update(signer: TransactionSigner, params: {
agentAddress: Address$1;
metadataUri: string;
agentType: number;
agentId: string;
name?: string | null;
description?: string | null;
pricingModel?: PricingModel$1;
}): Promise<string>;
/**
* Verify an agent
*/
verify(signer: TransactionSigner, params: {
agentAddress: Address$1;
agentPubkey: Address$1;
serviceEndpoint: string;
supportedCapabilities: Array<number | bigint>;
verifiedAt: number | bigint;
}): Promise<string>;
/**
* Deactivate an agent
*/
deactivate(signer: TransactionSigner, params: {
agentAddress: Address$1;
agentId: string;
}): Promise<string>;
/**
* Activate an agent
*/
activate(signer: TransactionSigner, params: {
agentAddress: Address$1;
agentId: string;
}): Promise<string>;
/**
* Get agent account
*/
getAgentAccount(address: Address$1): Promise<Agent | null>;
/**
* Get all agents
*/
getAllAgents(): Promise<{
address: Address$1;
data: Agent;
}[]>;
/**
* Get agents by type
*/
getAgentsByType(agentType: number): Promise<{
address: Address$1;
data: Agent;
}[]>;
/**
* Get user's agents
*/
getUserAgents(authority: Address$1): Promise<{
address: Address$1;
data: Agent;
}[]>;
/**
* Batch get multiple agent accounts
*
* Uses efficient batching (100 accounts per RPC call) with optional caching.
*
* @param addresses - Agent addresses to fetch
* @param onProgress - Optional progress callback
* @returns Array of agent accounts (null for non-existent)
*
* @example
* ```typescript
* const agents = await client.agents.batchGetAgents(
* ['agent1...', 'agent2...', 'agent3...'],
* (completed, total) => console.log(`${completed}/${total}`)
* )
* ```
*/
batchGetAgents(addresses: Address$1[], onProgress?: (completed: number, total: number) => void): Promise<(Agent | null)[]>;
/**
* Batch get only existing agent accounts
*
* Filters out non-existent addresses.
*
* @param addresses - Agent addresses to fetch
* @param onProgress - Optional progress callback
* @returns Array of existing agents with their addresses
*
* @example
* ```typescript
* const existingAgents = await client.agents.batchGetExistingAgents(['addr1', 'addr2'])
* // Returns: [{ address: 'addr1', account: Agent }, ...]
* ```
*/
batchGetExistingAgents(addresses: Address$1[], onProgress?: (completed: number, total: number) => void): Promise<Array<{
address: Address$1;
account: Agent;
}>>;
/**
* Batch get and map agents to a simplified format
*
* Useful for creating agent summaries or lists.
*
* @param addresses - Agent addresses to fetch
* @param mapper - Transform function
* @returns Array of mapped results
*
* @example
* ```typescript
* const summaries = await client.agents.batchGetAndMapAgents(
* addresses,
* (agent, address) => agent ? {
* address,
* name: agent.name,
* type: agent.agentType,
* active: agent.isActive
* } : null
* )
* ```
*/
batchGetAndMapAgents<R>(addresses: Address$1[], mapper: (agent: Agent | null, address: Address$1, index: number) => R): Promise<R[]>;
private deriveAgentPda;
private deriveUserRegistryPda;
private deriveTreeConfigPda;
private get systemProgramId();
private get compressionProgramId();
}
/**
* Ghost Module - Claim and manage external AI agents
*
* This module provides methods for claiming "Ghost" agents (external agents
* registered on x402 facilitators like PayAI) using the Solana Attestation
* Service (SAS) for trustless ownership verification.
*/
/**
* Network identifier for DID generation
*/
type Network = 'devnet' | 'testnet' | 'mainnet-beta' | 'localnet';
/**
* Parameters for claiming a Ghost
*/
interface ClaimGhostParams {
/** Agent account address (the external agent to claim) */
agentAddress: Address$1;
/** x402 payment address of the agent (used for PDA derivation) */
x402PaymentAddress: Address$1;
/** SAS Credential address (issuer) */
sasCredential: Address$1;
/** SAS Schema address (defines attestation structure) */
sasSchema: Address$1;
/** Network identifier for DID (e.g., "devnet", "mainnet-beta") */
network: Network;
/** Optional IPFS metadata URI (ipfs://...) */
ipfsMetadataUri?: string;
/** Optional GitHub username for social proof */
githubUsername?: string;
/** Optional Twitter handle for social proof */
twitterHandle?: string;
}
/**
* Result of preparing a Ghost claim
*/
interface PreparedClaimResult {
/** Derived attestation PDA */
attestationPda: Address$1;
/** Derived DID document PDA */
didDocumentPda: Address$1;
/** Attestation bump seed */
attestationBump: number;
/** DID document bump seed */
didDocumentBump: number;
}
/**
* Ghost Module - Manage external agent claims
*/
declare class GhostModule extends BaseModule {
constructor(config: GhostSpeakConfig);
/**
* Claim ownership of a Ghost using SAS attestation
*
* This method performs the complete claim flow:
* 1. Derives required PDAs (attestation, DID document)
* 2. Builds the claim_ghost instruction
* 3. Executes the transaction
*
* **Prerequisites:**
* - The claimer must have already created a SAS attestation proving ownership
* of the agent's x402_payment_address
* - The agent must be in Unregistered or Registered status (not already claimed)
*
* **Results:**
* - Agent status transitions to Claimed
* - DID document is auto-created with did:sol:<network>:<address>
* - Claimer becomes the owner of the agent
*
* @param claimer - Transaction signer (must own the SAS attestation)
* @param params - Claim parameters
* @returns Transaction signature
*
* @example
* ```typescript
* const signature = await client.ghosts.claim(signer, {
* agentAddress: 'GhostAgent123...',
* x402PaymentAddress: 'PaymentAddr456...',
* sasCredential: 'SASCredential789...',
* sasSchema: 'SASSchema012...',
* network: 'devnet',
* ipfsMetadataUri: 'ipfs://QmHash...',
* githubUsername: 'myusername'
* })
* ```
*/
claim(claimer: TransactionSigner, params: ClaimGhostParams): Promise<string>;
/**
* Prepare a Ghost claim by deriving all required PDAs
*
* This is useful for:
* - Pre-flight validation (checking if PDAs are correct)
* - Building custom transactions with manual PDA management
* - Debugging claim issues
*
* @param params - Claim parameters
* @returns Prepared claim data with derived PDAs
*
* @example
* ```typescript
* const prepared = await client.ghosts.prepareClaim({
* agentAddress: 'GhostAgent123...',
* x402PaymentAddress: 'PaymentAddr456...',
* sasCredential: 'SASCredential789...',
* sasSchema: 'SASSchema012...',
* network: 'devnet'
* })
*
* console.log('Attestation PDA:', prepared.attestationPda)
* console.log('DID Document PDA:', prepared.didDocumentPda)
* ```
*/
prepareClaim(params: ClaimGhostParams): Promise<PreparedClaimResult>;
/**
* Get Ghost agent account
*
* @param address - Agent account address
* @returns Agent account data or null if not found
*/
getGhostAgent(address: Address$1): Promise<Agent | null>;
/**
* Get all Ghost agents (agents with type 10 - external x402 agents)
*
* @returns Array of Ghost agents
*/
getAllGhosts(): Promise<{
address: Address$1;
data: Agent;
}[]>;
/**
* Get Ghost agents by type
*
* @param agentType - Agent type filter (default: 10 for x402 ghosts)
* @returns Array of matching Ghost agents
*/
getGhostsByType(agentType?: number): Promise<{
address: Address$1;
data: Agent;
}[]>;
/**
* Get claimed Ghosts by owner
*
* @param owner - Owner address
* @returns Array of Ghost agents owned by the address
*/
getClaimedGhosts(owner: Address$1): Promise<{
address: Address$1;
data: Agent;
}[]>;
/**
* Validate claim parameters
*
* Performs pre-flight checks to ensure claim will succeed:
* - Agent exists and is in correct status
* - Agent is not already claimed
* - PDAs are correctly derived
*
* @param params - Claim parameters
* @returns Validation result with error messages if any
*/
validateClaim(params: ClaimGhostParams): Promise<{
valid: boolean;
errors: string[];
warnings: string[];
}>;
/**
* Derive DID document PDA
*
* Pattern: ['did_document', x402_payment_address]
*
* @param x402PaymentAddress - Agent's x402 payment address
* @returns [DID document PDA, bump]
*/
private deriveDidDocumentPda;
private get systemProgramId();
}
interface ProposalType {
kind: 'ConfigChange' | 'Treasury' | 'Protocol' | 'Emergency';
data?: Record<string, unknown>;
}
interface ExecutionParams {
instructions: string[];
accounts: Address$1[];
targetProgram: Address$1;
executeAfter?: bigint;
}
interface CreateProposalParams {
title: string;
description: string;
proposalType: ProposalType;
executionParams: ExecutionParams;
proposalId: bigint;
}
/**
* Governance management module
*
* Provides high-level access to governance operations including:
* - Proposal creation and management
*
* NOTE: Voting, delegation, and execution are handled through protocol_config + multisig
*/
declare class GovernanceModule extends BaseModule {
/**
* Get initialize governance proposal instruction
*/
getInitializeGovernanceProposalInstruction(params: {
proposal?: Address$1;
proposer: TransactionSigner;
title: string;
description: string;
proposalType: any;
executionParams: any;
proposalId: number | bigint;
}): Promise<InitializeGovernanceProposalInstruction<Address$1<"4wHjA2a5YC4twZb4NQpwZpixo5FgxxzuJUrCG7UnF9pB">, string, string, string, []>>;
/**
* Create a new governance proposal
*/
createProposal(params: {
signer: TransactionSigner;
title: string;
description: string;
proposalType: 'parameter_change' | 'upgrade' | 'treasury';
votingDuration: number;
executionDelay?: number;
}): Promise<string>;
/**
* Get governance proposal account
*/
getProposal(address: Address$1): Promise<GovernanceProposal | null>;
/**
* Get all active proposals
*/
getActiveProposals(): Promise<{
address: Address$1;
data: GovernanceProposal;
}[]>;
/**
* Get proposals by proposer
*/
getProposalsByProposer(proposer: Address$1): Promise<{
address: Address$1;
data: GovernanceProposal;
}[]>;
/**
* Get proposals by status
*/
getProposalsByStatus(_status: 'draft' | 'voting' | 'succeeded' | 'defeated' | 'executed'): Promise<{
address: Address$1;
data: GovernanceProposal;
}[]>;
private deriveProposalPda;
}
interface CreateMultisigParams {
multisigId: bigint;
threshold: number;
signers: Address$1[];
config?: Partial<MultisigTypeConfigArgs>;
owner: TransactionSigner;
}
interface MultisigProposalParams {
multisigAddress: Address$1;
title: string;
description: string;
proposalType: ProposalTypeArgs;
executionParams: ExecutionParamsArgs;
proposalId: bigint;
proposer: TransactionSigner;
}
interface ExecuteProposalParams {
proposalAddress: Address$1;
executor: TransactionSigner;
targetProgram: Address$1;
}
declare class MultisigModule extends BaseModule {
/**
* Create a new multisig account
*/
createMultisig(params: CreateMultisigParams): Promise<string>;
/**
* Create a proposal (Uses Governance Protocol)
*
* Note: This creates a GovernanceProposal. The proposer must be a signer.
*/
createProposal(params: MultisigProposalParams): Promise<string>;
/**
* Execute a proposal (Note: Approval/voting removed, use protocol_config instead)
*/
executeProposal(params: ExecuteProposalParams): Promise<string>;
}
/**
* GhostSpeak DID (Decentralized Identifier) Types
*
* Implements the did:sol method for Solana-based DIDs following W3C standards.
* Based on Identity.com's did:sol specification v3.0.
*/
/**
* Verification method type for DIDs
*/
declare enum VerificationMethodType {
/** Ed25519 verification key (Solana native) */
Ed25519VerificationKey2020 = "Ed25519VerificationKey2020",
/** X25519 key agreement for encryption */
X25519KeyAgreementKey2020 = "X25519KeyAgreementKey2020",
/** Secp256k1 verification key (Ethereum compatibility) */
EcdsaSecp256k1VerificationKey2019 = "EcdsaSecp256k1VerificationKey2019"
}
/**
* Verification relationship types
*/
declare enum VerificationRelationship {
/** Key can authenticate as the DID */
Authentication = "authentication",
/** Key can assert claims (issue credentials) */
AssertionMethod = "assertionMethod",
/** Key can perform key agreement (encryption) */
KeyAgreement = "keyAgreement",
/** Key can invoke capabilities (update DID document) */
CapabilityInvocation = "capabilityInvocation",
/** Key can delegate capabilities */
CapabilityDelegation = "capabilityDelegation"
}
/**
* Service endpoint type
*/
declare enum ServiceEndpointType {
/** AI agent service endpoint */
AIAgentService = "AIAgentService",
/** Messaging service endpoint (DIDComm) */
DIDCommMessaging = "DIDCommMessaging",
/** Credential repository */
CredentialRepository = "CredentialRepository",
/** Linked domains verification */
LinkedDomains = "LinkedDomains",
/** Custom service type */
Custom = "Custom"
}
/**
* Verification method for DID document
*
* Represents a cryptographic key that can be used to verify
* signatures or perform other cryptographic operations
*/
interface VerificationMethod {
/** Method identifier (e.g., "key-1") */
id: string;
/** Type of verification method */
methodType: VerificationMethodType;
/** DID of the controller (usually the DID itself) */
controller: string;
/** Public key in multibase format (base58btc) */
publicKeyMultibase: string;
/** Verification relationships this key has */
relationships: VerificationRelationship[];
/** Creation timestamp */
createdAt: number;
/** Revoked flag */
revoked: boolean;
}
/**
* Service endpoint in DID document
*/
interface ServiceEndpoint {
/** Service identifier (e.g., "agent-api") */
id: string;
/** Type of service */
serviceType: ServiceEndpointType;
/** Service endpoint URI */
serviceEndpoint: string;
/** Optional description */
description: string;
}
/**
* DID Document - main account for storing decentralized identifiers
*
* Follows W3C DID Core specification and did:sol method
*/
interface DidDocument {
/** The DID string (e.g., "did:sol:devnet:HN7cABqLq46Es1jh92dQQisAq662SmxELLLsHHe4YWrH") */
did: string;
/** Controller of the DID (can update the document) */
controller: Address$1;
/** Verification methods (public keys) */
verificationMethods: VerificationMethod[];
/** Service endpoints */
serviceEndpoints: ServiceEndpoint[];
/** Context URIs (for W3C compatibility) */
context: string[];
/** Also known as (alternative DIDs) */
alsoKnownAs: string[];
/** DID document creation timestamp */
createdAt: number;
/** Last update timestamp */
updatedAt: number;
/** Version number (incremented on each update) */
version: number;
/** Deactivated flag */
deactivated: boolean;
/** Deactivation timestamp (if deactivated) */
deactivatedAt?: number;
/** PDA bump */
bump: number;
}
/**
* DID Resolution Metadata
*
* Additional metadata for DID resolution
*/
interface DidResolutionMetadata {
/** DID being resolved */
did: string;
/** Pointer to the DID document account */
didDocument: Address$1;
/** Resolution timestamp */
resolvedAt: number;
/** Content type (application/did+json) */
contentType: string;
/** DID document version at resolution time */
version: number;
/** PDA bump */
bump: number;
}
/**
* W3C DID Document format for export
* Compliant with W3C DID Core specification
*/
interface W3CDidDocument {
'@context': string[];
id: string;
controller?: string | string[];
verificationMethod: Array<{
id: string;
type: string;
controller: string;
publicKeyMultibase: string;
}>;
authentication?: Array<string | {
id: string;
type: string;
controller: string;
publicKeyMultibase: string;
}>;
assertionMethod?: string[];
keyAgreement?: string[];
capabilityInvocation?: string[];
capabilityDelegation?: string[];
service?: Array<{
id: string;
type: string;
serviceEndpoint: string;
description?: string;
}>;
alsoKnownAs?: string[];
}
/**
* Parameters for creating a DID document
*/
interface CreateDidDocumentParams {
/** Controller public key */
controller: Address$1;
/** Initial verification methods */
verificationMethods?: VerificationMethod[];
/** Initial service endpoints */
serviceEndpoints?: ServiceEndpoint[];
/** Network (mainnet, devnet, testnet) */
network?: 'mainnet' | 'devnet' | 'testnet';
}
/**
* Parameters for updating a DID document
*/
interface UpdateDidDocumentParams {
/** DID document address */
didDocument: Address$1;
/** Verification method to add */
addVerificationMethod?: VerificationMethod;
/** Verification method ID to remove */
removeVerificationMethodId?: string;
/** Service endpoint to add */
addServiceEndpoint?: ServiceEndpoint;
/** Service endpoint ID to remove */
removeServiceEndpointId?: string;
}
/**
* Parameters for deactivating a DID document
*/
interface DeactivateDidDocumentParams {
/** DID document address */
didDocument: Address$1;
}
/**
* Parameters for resolving a DID document
*/
interface ResolveDidDocumentParams {
/** DID string or controller address */
did: string | Address$1;
}
/**
* DID-related errors
*/
declare enum DidError {
AlreadyDeactivated = "AlreadyDeactivated",
TooManyVerificationMethods = "TooManyVerificationMethods",
TooManyServiceEndpoints = "TooManyServiceEndpoints",
DuplicateMethodId = "DuplicateMethodId",
DuplicateServiceId = "DuplicateServiceId",
MethodNotFound = "MethodNotFound",
ServiceNotFound = "ServiceNotFound",
InvalidDidFormat = "InvalidDidFormat",
UnauthorizedDidOperation = "UnauthorizedDidOperation",
DidDeactivated = "DidDeactivated"
}
/**
* DID Error class
*/
declare class DidErrorClass extends Error {
code: DidError;
constructor(code: DidError, message?: string);
}
/**
* GhostSpeak DID Helpers
*
* Utility functions for DID operations, validation, and W3C export
*/
/**
* Derive DID document PDA
* Pattern: ['did_document', controller]
*/
declare function deriveDidDocumentPda(programId: Address$1, controller: Address$1): Promise<[Address$1, number]>;
/**
* Generate a did:sol string from network and public key
*
* @param network - Solana network (mainnet, devnet, testnet, localnet)
* @param pubkey - Public key to use as the DID identifier
* @returns DID string in the format "did:sol:network:pubkey"
*
* @example
* ```typescript
* const did = generateDidString('devnet', '5VKz...')
* // Returns: "did:sol:devnet:5VKz..."
* ```
*/
declare function generateDidString(network: 'mainnet' | 'devnet' | 'testnet' | 'localnet', pubkey: Address$1 | string): string;
/**
* Validate DID string format
*
* @param did - DID string to validate
* @thr