UNPKG

@ghostspeak/sdk

Version:

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

1,770 lines (1,696 loc) 118 kB
import { Address, Option, ReadonlyUint8Array, 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 { Address as Address$1 } from '@solana/addresses'; /** * 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 */ /** Types of execution conditions */ declare enum ConditionType { TimeDelay = 0, TokenBalance = 1, PriceThreshold = 2, VoteCount = 3, ExternalOracle = 4, CustomLogic = 5 } type ConditionTypeArgs = ConditionType; /** * 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 */ /** Vote delegation information */ type DelegationInfo = { /** Original delegator */ delegator: Address; /** Delegation timestamp */ delegatedAt: bigint; /** Delegation scope */ scope: DelegationScope; /** Delegation expiry */ expiresAt: Option<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 */ /** Scope of vote delegation */ type DelegationScope = { __kind: "All"; } | { __kind: "ProposalType"; fields: readonly [ProposalType]; } | { __kind: "SingleProposal"; } | { __kind: "Limited"; }; /** * 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 */ /** Execution conditions for transactions */ type ExecutionCondition = { /** Condition type */ conditionType: ConditionType; /** Target value/threshold */ targetValue: bigint; /** Current value */ currentValue: bigint; /** Condition met */ met: boolean; /** Condition description */ description: string; }; type ExecutionConditionArgs = { /** Condition type */ conditionType: ConditionTypeArgs; /** Target value/threshold */ targetValue: number | bigint; /** Current value */ currentValue: number | bigint; /** Condition met */ met: boolean; /** Condition description */ description: string; }; /** * 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 */ /** Execution parameters for proposals */ type ExecutionParams = { /** Instructions to execute if passed */ instructions: Array<ProposalInstruction>; /** Time delay before execution */ executionDelay: bigint; /** Execution conditions */ executionConditions: Array<ExecutionCondition>; /** Can be cancelled after approval */ cancellable: boolean; /** Automatic execution enabled */ autoExecute: boolean; /** Required execution authority */ executionAuthority: Address; }; type ExecutionParamsArgs = { /** Instructions to execute if passed */ instructions: Array<ProposalInstructionArgs>; /** Time delay before execution */ executionDelay: number | bigint; /** Execution conditions */ executionConditions: Array<ExecutionConditionArgs>; /** Can be cancelled after approval */ cancellable: boolean; /** Automatic execution enabled */ autoExecute: boolean; /** Required execution authority */ executionAuthority: Address; }; /** * 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 { Fixed = 0, Hourly = 1, PerTask = 2, Subscription = 3, Auction = 4, Dynamic = 5, RevenueShare = 6, Tiered = 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 */ /** Account specification for proposal instruction */ type ProposalAccount = { /** Account public key */ pubkey: Address; /** Is signer required */ isSigner: boolean; /** Is writable */ isWritable: boolean; /** Account description */ description: string; }; type ProposalAccountArgs = ProposalAccount; /** * 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 */ /** Individual instruction in proposal */ type ProposalInstruction = { /** Target program */ programId: Address; /** Accounts required */ accounts: Array<ProposalAccount>; /** Instruction data */ data: ReadonlyUint8Array; /** Instruction description */ description: string; }; type ProposalInstructionArgs = { /** Target program */ programId: Address; /** Accounts required */ accounts: Array<ProposalAccountArgs>; /** Instruction data */ data: ReadonlyUint8Array; /** Instruction description */ description: string; }; /** * 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 */ /** Proposal metadata */ type ProposalMetadata = { /** IPFS hash for detailed proposal */ ipfsHash: Option<string>; /** External references */ externalReferences: Array<string>; /** Proposal tags */ tags: Array<string>; /** Risk assessment */ riskAssessment: Option<string>; /** Impact analysis */ impactAnalysis: Option<string>; /** Implementation timeline */ implementationTimeline: Option<string>; }; /** * 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 */ /** Proposal execution status */ declare enum ProposalStatus { Draft = 0, Active = 1, Passed = 2, Failed = 3, Executed = 4, Cancelled = 5, Expired = 6, Queued = 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 */ /** Types of governance proposals */ declare enum ProposalType { ParameterUpdate = 0, ProtocolUpgrade = 1, TreasuryOperation = 2, FeeUpdate = 3, SecurityUpdate = 4, GovernanceUpdate = 5, EmergencyAction = 6, Custom = 7 } type ProposalTypeArgs = ProposalType; /** * 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 */ /** Methods for calculating quorum */ declare enum QuorumMethod { Absolute = 0, Relative = 1, Weighted = 2, Dynamic = 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 */ /** Quorum requirements for proposals */ type QuorumRequirements = { /** Minimum participation rate (0-100) */ minimumParticipation: number; /** Approval threshold (0-100) */ approvalThreshold: number; /** Super majority required */ superMajorityRequired: boolean; /** Minimum total voting power */ minimumVotingPower: bigint; /** Quorum calculation method */ quorumMethod: QuorumMethod; }; /** * 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 */ /** Individual vote record */ type Vote = { /** Voter public key */ voter: Address; /** Vote choice */ choice: VoteChoice; /** Voting power used */ votingPower: bigint; /** Vote timestamp */ votedAt: bigint; /** Vote reasoning (optional) */ reasoning: Option<string>; /** Delegation info (if delegated vote) */ delegationInfo: Option<DelegationInfo>; }; /** * 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 */ /** Vote choices */ declare enum VoteChoice { For = 0, Against = 1, Abstain = 2 } /** * 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 */ /** Voting results for proposal */ type VotingResults = { /** Total votes for */ votesFor: bigint; /** Total votes against */ votesAgainst: bigint; /** Total votes abstain */ votesAbstain: bigint; /** Total voting power */ totalVotingPower: bigint; /** Participation rate */ participationRate: number; /** Individual votes */ individualVotes: Array<Vote>; /** Weighted voting enabled */ weightedVoting: boolean; /** Quorum reached */ quorumReached: boolean; /** Approval threshold met */ approvalThresholdMet: boolean; }; /** * 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$1 = { 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; 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; }; /** * 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 GovernanceProposal = { discriminator: ReadonlyUint8Array; /** Proposal ID */ proposalId: bigint; /** Proposer */ proposer: Address; /** Proposal title */ title: string; /** Proposal description */ description: string; /** Proposal type */ proposalType: ProposalType; /** Creation timestamp */ createdAt: bigint; /** Voting start timestamp */ votingStartsAt: bigint; /** Voting end timestamp */ votingEndsAt: bigint; /** Execution timestamp (if approved) */ executionTimestamp: Option<bigint>; /** Proposal status */ status: ProposalStatus; /** Voting results */ votingResults: VotingResults; /** Execution parameters */ executionParams: ExecutionParams; /** Quorum requirements */ quorumRequirements: QuorumRequirements; /** Proposal metadata */ metadata: ProposalMetadata; /** Reserved space */ reserved: ReadonlyUint8Array; }; /** * 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; }; /** * 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; }; /** * 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; }; }; } /** * IPFS configuration and types for GhostSpeak SDK */ /** * IPFS provider configuration */ interface IPFSProviderConfig { /** Provider name */ name: 'pinata' | 'infura' | 'ipfs-http-client' | 'web3-storage' | 'custom' | 'test'; /** API endpoint URL */ endpoint?: string; /** API key for authentication */ apiKey?: string; /** API secret for authentication */ apiSecret?: string; /** JWT token for authentication */ jwt?: string; /** Custom headers */ headers?: Record<string, string>; /** Request timeout in milliseconds */ timeout?: number; } /** * IPFS client configuration */ interface IPFSConfig { /** Primary provider */ provider: IPFSProviderConfig; /** Fallback providers */ fallbackProviders?: IPFSProviderConfig[]; /** Default IPFS gateway for retrieving content */ gateway?: string; /** Additional gateways for redundancy */ gateways?: string[]; /** Whether to automatically pin uploaded content */ autoPinning?: boolean; /** Content size threshold for IPFS (bytes) - content above this will use IPFS */ sizeThreshold?: number; /** Maximum retry attempts for failed operations */ maxRetries?: number; /** Retry delay in milliseconds */ retryDelay?: number; /** Enable caching of IPFS content */ enableCache?: boolean; /** Cache TTL in milliseconds */ cacheTTL?: number; } /** * Reputation Tags System * * Granular tagging system for agent reputation with confidence scoring. * Tags are automatically assigned based on metrics and evidence strength. * * Three tag categories: * - Skill Tags: Technical capabilities and domain expertise * - Behavior Tags: Service quality patterns and reliability * - Compliance Tags: Regulatory and security compliance status */ /** * Tag confidence score (basis points) * 0-10000 where 10000 = 100% confidence */ interface TagScore { /** Tag identifier (e.g., "fast-responder", "defi-expert") */ tagName: string; /** Confidence level in basis points (0-10000) */ confidence: number; /** Number of supporting data points */ evidenceCount: number; /** Timestamp when tag was last updated */ lastUpdated: number; } /** * Tag categories for organization */ declare enum TagCategory { Skill = "skill", Behavior = "behavior", Compliance = "compliance" } /** * Reputation metrics for tag evaluation */ interface ReputationMetrics { successfulPayments: bigint; failedPayments: bigint; totalResponseTime: bigint; responseTimeCount: bigint; totalDisputes: number; disputesResolved: number; totalRating: number; totalRatingsCount: number; createdAt: number; updatedAt: number; avgResponseTime: number; successRate: number; avgRating: number; disputeResolutionRate: number; } /** * Tag filtering options */ interface TagFilters { /** Filter by category */ category?: TagCategory; /** Minimum confidence threshold */ minConfidence?: number; /** Maximum age in seconds */ maxAge?: number; /** Include only active tags */ activeOnly?: boolean; } /** * Tag query result */ interface TagQueryResult { /** All tags */ allTags: string[]; /** Skill tags */ skillTags: string[]; /** Behavior tags */ behaviorTags: string[]; /** Compliance tags */ complianceTags: string[]; /** Tag scores */ tagScores: TagScore[]; /** Last updated timestamp */ lastUpdated: number; } /** * Privacy mode for reputation display * * Determines how much reputation information is publicly visible. */ declare enum PrivacyMode { /** Full disclosure - all reputation data is public */ Public = "Public", /** Show only reputation tier (Bronze/Silver/Gold/Platinum) */ TierOnly = "TierOnly", /** Show score range bucket (e.g., 750-850) */ RangeOnly = "RangeOnly", /** Custom selective disclosure */ Custom = "Custom", /** Fully confidential - ZK proofs required */ Confidential = "Confidential" } /** * Visibility level for individual metrics */ declare enum VisibilityLevel { /** Visible to everyone */ Public = "Public", /** Visible only to authorized viewers */ Private = "Private", /** Visible only with ZK proof */ ZKProof = "ZKProof" } /** * Reputation tier levels (for tier-only privacy mode) */ declare enum ReputationTier$1 { None = "None", Bronze = "Bronze", Silver = "Silver", Gold = "Gold", Platinum = "Platinum" } /** * Score range buckets (for range-only privacy mode) */ declare enum ScoreRange { VeryLow = "VeryLow",// 0-2000 Low = "Low",// 2000-5000 Medium = "Medium",// 5000-7500 High = "High",// 7500-9000 VeryHigh = "VeryHigh" } /** * Selective disclosure settings for individual metrics */ interface MetricVisibility { /** Show exact Ghost Score */ showScore: VisibilityLevel; /** Show total jobs completed */ showJobsCompleted: VisibilityLevel; /** Show success rate percentage */ showSuccessRate: VisibilityLevel; /** Show average response time */ showResponseTime: VisibilityLevel; /** Show dispute statistics */ showDisputes: VisibilityLevel; /** Show earnings/payment data */ showEarnings: VisibilityLevel; /** Show client ratings */ showRatings: VisibilityLevel; /** Show badges earned */ showBadges: VisibilityLevel; } /** * Privacy settings for an agent's reputation */ interface PrivacySettings { /** Agent public key */ agent: Address$1; /** Current privacy mode */ mode: PrivacyMode; /** Metric-specific visibility settings */ metricVisibility: MetricVisibility; /** List of addresses with viewing permission */ authorizedViewers: Address$1[]; /** Auto-grant access to clients who pay */ autoGrantClients: boolean; /** Last updated timestamp */ updatedAt: number; } /** * Privacy preset configurations */ interface PrivacyPreset { /** Preset name */ name: string; /** Privacy mode */ mode: PrivacyMode; /** Metric visibility settings */ metricVisibility: MetricVisibility; /** Auto-grant to clients */ autoGrantClients: boolean; } /** * Visible reputation data (filtered by privacy settings) * * This is the client-side type returned when fetching reputation * with privacy filters applied. */ interface VisibleReputation { /** Agent public key */ agent: Address$1; /** Privacy mode applied */ privacyMode: PrivacyMode; /** Exact score (only if visible) */ exactScore?: number; /** Reputation tier (always visible in TierOnly mode) */ tier?: ReputationTier$1; /** Score range (visible in RangeOnly mode) */ scoreRange?: ScoreRange; /** Total jobs completed (if visible) */ totalJobsCompleted?: number; /** Success rate percentage (if visible) */ successRate?: number; /** Average response time in ms (if visible) */ avgResponseTime?: number; /** Dispute statistics (if visible) */ disputes?: { total: number; resolved: number; }; /** Total earnings (if visible) */ totalEarnings?: number; /** Average rating (if visible) */ avgRating?: number; /** Badges earned (if visible) */ badges?: string[]; /** Whether viewer has full access */ hasFullAccess: boolean; } /** * Parameters for initializing privacy settings */ interface InitializePrivacyParams { /** Agent address to enable privacy for */ agentAddress: Address$1; /** Initial privacy mode */ mode?: PrivacyMode; /** Metric visibility settings */ metricVisibility?: MetricVisibility; } /** * Parameters for updating privacy mode */ interface UpdatePrivacyModeParams { /** Agent address */ agentAddress: Address$1; /** New privacy mode */ mode: PrivacyMode; } /** * Parameters for setting metric visibility */ interface SetMetricVisibilityParams { /** Agent address */ agentAddress: Address$1; /** Metric visibility settings */ metricVisibility: MetricVisibility; } /** * Parameters for granting viewer access */ interface GrantAccessParams { /** Agent address */ agentAddress: Address$1; /** Viewer address to grant access */ viewer: Address$1; } /** * Parameters for revoking viewer access */ interface RevokeAccessParams { /** Agent address */ agentAddress: Address$1; /** Viewer address to revoke access */ viewer: Address$1; } /** * Parameters for applying a privacy preset */ interface ApplyPresetParams { /** Agent address */ agentAddress: Address$1; /** Preset to apply */ preset: PrivacyPreset; } /** * Comprehensive Type System for GhostSpeak SDK * * All types are exported as individual named exports using ES2015 module syntax * for better tree-shaking and compatibility with ESLint rules. */ /** * Agent entity */ interface Agent { address: Address$1; type: AgentType; owner: Address$1; metadata: AgentMetadata; reputation: Reputation; isActive: boolean; isVerified: boolean; createdAt: Date; } /** * Agent types */ declare enum AgentType { General = 0, Specialized = 1, Oracle = 2, Validator = 3 } /** * Agent metadata */ interface AgentMetadata { name: string; description: string; capabilities: string[]; avatar?: string; website?: string; socialLinks?: Record<string, string>; } /** * Reputation data */ interface Reputation { score: number; jobsCompleted: number; successRate: number; totalEarnings: bigint; ratings: Rating[]; } /** * Rating entry */ interface Rating { from: Address$1; score: number; comment?: string; timestamp: Date; } /** * Escrow entity */ interface Escrow { address: Address$1; buyer: Address$1; seller: Address$1; amount: bigint; status: EscrowStatus; description: string; milestones?: Milestone[]; createdAt: Date; completedAt?: Date; } /** * Escrow status */ declare enum EscrowStatus { Active = "active", Completed = "completed", Cancelled = "cancelled", Disputed = "disputed", Refunded = "refunded" } /** * Milestone for escrow */ interface Milestone { amount: bigint; description: string; completed: boolean; completedAt?: Date; } /** * Channel entity */ interface Channel { address: Address$1; name: string; description: string; type: ChannelType; creator: Address$1; members: Address$1[]; isPrivate: boolean; maxMembers: number; messageCount: number; createdAt: Date; } /** * Channel types */ declare enum ChannelType { Public = "public", Private = "private", Direct = "direct", Group = "group" } /** * SDK error with context */ interface SDKError { code: ErrorCode; message: string; context?: Record<string, unknown>; solution?: string; instruction?: string; } /** * Error codes */ declare enum ErrorCode { NETWORK_ERROR = "NETWORK_ERROR", RPC_ERROR = "RPC_ERROR", TIMEOUT = "TIMEOUT", INSUFFICIENT_BALANCE = "INSUFFICIENT_BALANCE", TRANSACTION_FAILED = "TRANSACTION_FAILED", SIMULATION_FAILED = "SIMULATION_FAILED", ACCOUNT_NOT_FOUND = "ACCOUNT_NOT_FOUND", INVALID_ACCOUNT = "INVALID_ACCOUNT", UNAUTHORIZED = "UNAUTHORIZED", INVALID_INPUT = "INVALID_INPUT", INVALID_ADDRESS = "INVALID_ADDRESS", INVALID_AMOUNT = "INVALID_AMOUNT", PROGRAM_ERROR = "PROGRAM_ERROR", INSTRUCTION_ERROR = "INSTRUCTION_ERROR", UNKNOWN_ERROR = "UNKNOWN_ERROR" } /** * Participant type enum for distinguishing between humans and agents */ declare enum ParticipantType { Human = "Human", Agent = "Agent" } 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[]; } /** * 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; 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; }): 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; }): 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$1 | null>; /** * Get all agents */ getAllAgents(): Promise<{ address: Address$1; data: Agent$1; }[]>; /** * Get agents by type */ getAgentsByType(agentType: number): Promise<{ address: Address$1; data: Agent$1; }[]>; /** * Get user's agents */ getUserAgents(authority: Address$1): Promise<{ address: Address$1; data: Agent$1; }[]>; /** * 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$1 | 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[], onProgres