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; }; /** * 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; /** Time delay before execution */ executionDelay: bigint; /** Execution conditions */ executionConditions: Array; /** 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; /** Time delay before execution */ executionDelay: number | bigint; /** Execution conditions */ executionConditions: Array; /** 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; /** Instruction data */ data: ReadonlyUint8Array; /** Instruction description */ description: string; }; type ProposalInstructionArgs = { /** Target program */ programId: Address; /** Accounts required */ accounts: Array; /** 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; /** External references */ externalReferences: Array; /** Proposal tags */ tags: Array; /** Risk assessment */ riskAssessment: Option; /** Impact analysis */ impactAnalysis: Option; /** Implementation timeline */ implementationTimeline: Option; }; /** * 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; /** Delegation info (if delegated vote) */ delegationInfo: Option; }; /** * 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; /** 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
; status: AgentStatus; agentId: string; firstTxSignature: string; firstSeenTimestamp: bigint; discoverySource: string; claimedAt: Option; agentType: number; name: string; description: string; capabilities: Array; 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
; cnftMint: Option
; merkleTree: Option
; supportsA2a: boolean; transferHook: Option
; parentAgent: Option
; generation: number; x402Enabled: boolean; x402PaymentAddress: Address; x402AcceptedTokens: Array
; x402PricePerCall: bigint; x402ServiceEndpoint: string; x402TotalPayments: bigint; x402TotalCalls: bigint; lastPaymentTimestamp: bigint; externalIdentifiers: Array; ghostScore: bigint; reputationComponents: Array; didAddress: Option
; credentials: Array
; 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; /** 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 = string, TAccountProposer extends string | AccountMeta = string, TAccountSystemProgram extends string | AccountMeta = "11111111111111111111111111111111", TRemainingAccounts extends readonly AccountMeta[] = []> = Instruction & InstructionWithData & InstructionWithAccounts<[ TAccountProposal extends string ? WritableAccount : TAccountProposal, TAccountProposer extends string ? WritableSignerAccount & AccountSignerMeta : TAccountProposer, TAccountSystemProgram extends string ? ReadonlyAccount : 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(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(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; /** 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; } /** * 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; 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; type ExtendedRpcApi = RpcApi & Rpc; type RpcSubscriptionApi = RpcSubscriptions; 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(instructionName: string, instructionGetter: () => Promise | InstructionLike, signers: TransactionSigner[], options?: { simulate?: boolean; returnDetails?: boolean; skipPreflight?: boolean; maxRetries?: number; }): Promise; /** * Execute multiple instructions in a single transaction */ executeBatch(batchName: string, instructionGetters: (() => Promise | InstructionLike)[], signers: TransactionSigner[], options?: { simulate?: boolean; returnDetails?: boolean; skipPreflight?: boolean; }): Promise; /** * Get and decode account data with unified error handling */ getAccount(address: Address$1, decoderImportName: string): Promise; /** * Get multiple accounts with unified pattern */ getAccounts(addresses: Address$1[], decoderImportName: string): Promise<(T | null)[]>; /** * Get program accounts with filters */ getProgramAccounts(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)[]): Promise; /** * Get human-readable explanation of transaction */ explain(instructionName: string, instructionGetters: (() => Promise | InstructionLike)[]): Promise; /** * Estimate transaction cost */ estimateCost(instructionGetters: (() => Promise | InstructionLike)[]): Promise; 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; /** * Send a communication message instruction */ sendCommunicationMessage(_sessionAddress: Address$1, _params: { messageId: bigint; senderType: unknown; content: string; messageType: string; attachments: string[]; }): Promise; /** * Update participant status instruction */ updateParticipantStatus(_params: { participant: Address$1; participantType: unknown; servicesOffered: string[]; availability: boolean; reputationScore: number; }): Promise; } /** * 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, signers: TransactionSigner[]): Promise; /** * Execute a single instruction with detailed result */ protected executeWithDetails(instructionName: string, instructionGetter: () => Promise | IInstruction, signers: TransactionSigner[]): Promise; /** * Execute multiple instructions in a batch */ protected executeBatch(batchName: string, instructionGetters: (() => Promise | IInstruction)[], signers: TransactionSigner[]): Promise; /** * Simulate an instruction */ protected simulate(instructionName: string, instructionGetter: () => Promise | IInstruction, signers: TransactionSigner[]): Promise; /** * Simulate an instruction (public accessor) */ simulateInstruction(instructionName: string, instructionGetter: () => Promise | IInstruction, signers: TransactionSigner[]): Promise; /** * Estimate transaction cost */ protected estimateCost(instructionGetters: (() => Promise | IInstruction)[]): Promise; /** * Get cost estimation for an instruction */ getCost(instructionName: string, instructionGetter: () => Promise | IInstruction): Promise; /** * Get human-readable explanation */ explain(instructionName: string, instructionGetter: () => Promise | IInstruction): Promise; /** * Debug analyze without executing */ analyze(instructionName: string, instructionGetter: () => Promise | IInstruction): Promise; /** * Get decoded account (with optional caching) */ protected getAccount(address: Address$1, decoderImportName: string): Promise; /** * Get multiple decoded accounts (with optional caching) */ protected getAccounts(addresses: Address$1[], decoderImportName: string): Promise<(T | null)[]>; /** * Get program accounts */ protected getProgramAccounts(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; /** * 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; /** * 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; /** * Verify an agent */ verify(signer: TransactionSigner, params: { agentAddress: Address$1; agentPubkey: Address$1; serviceEndpoint: string; supportedCapabilities: Array; verifiedAt: number | bigint; }): Promise; /** * Deactivate an agent */ deactivate(signer: TransactionSigner, params: { agentAddress: Address$1; agentId: string; }): Promise; /** * Activate an agent */ activate(signer: TransactionSigner, params: { agentAddress: Address$1; agentId: string; }): Promise; /** * Get agent account */ getAgentAccount(address: Address$1): Promise; /** * 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[], onProgress?: (completed: number, total: number) => void): Promise>; /** * 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(addresses: Address$1[], mapper: (agent: Agent$1 | null, address: Address$1, index: number) => R): Promise; 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::
* - 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; /** * 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; /** * Get Ghost agent account * * @param address - Agent account address * @returns Agent account data or null if not found */ getGhostAgent(address: Address$1): Promise; /** * Get all Ghost agents (agents with type 10 - external x402 agents) * * @returns Array of Ghost agents */ getAllGhosts(): Promise<{ address: Address$1; data: Agent$1; }[]>; /** * 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$1; }[]>; /** * 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$1; }[]>; /** * 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(); } /** * 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, 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; /** * Get governance proposal account */ getProposal(address: Address$1): Promise; /** * 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; 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; /** * Create a proposal (Uses Governance Protocol) * * Note: This creates a GovernanceProposal. The proposer must be a signer. */ createProposal(params: MultisigProposalParams): Promise; /** * Execute a proposal (Note: Approval/voting removed, use protocol_config instead) */ executeProposal(params: ExecuteProposalParams): Promise; } interface CrossmintClientOptions { apiKey: string; environment?: 'staging' | 'production'; chain?: 'base-sepolia' | 'polygon-amoy' | 'ethereum-sepolia' | 'base' | 'polygon' | 'ethereum'; } /** * 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; } /** * 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; 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; } /** * GhostSpeak DID Helpers * * Utility functions for DID operations, validation, and W3C export */ /** * Create a default Ed25519 verification method * * @param id - Method identifier (e.g., "key-1") * @param controller - Controller DID * @param publicKey - Public key (Address or base58 string) * @param relationships - Verification relationships * @returns Verification method object */ declare function createEd25519VerificationMethod(id: string, controller: string, publicKey: Address$1 | string, relationships?: VerificationRelationship[]): VerificationMethod; /** * Create a service endpoint * * @param id - Service identifier (e.g., "agent-api") * @param serviceType - Type of service * @param serviceEndpoint - Service endpoint URI * @param description - Optional description * @returns Service endpoint object */ declare function createServiceEndpoint(id: string, serviceType: string, serviceEndpoint: string, description?: string): ServiceEndpoint; /** * GhostSpeak DID Module * * Provides functionality for managing Decentralized Identifiers (DIDs) * following the W3C DID Core specification and did:sol method. */ /** * DidModule - Manage decentralized identifiers on Solana * * @example * ```typescript * const client = new GhostSpeakClient({ cluster: 'devnet' }) * const did = client.did * * // Create a DID * const signature = await did.create(signer, { * controller: signer.address, * network: 'devnet' * }) * * // Resolve a DID * const didDoc = await did.resolve(signer.address) * * // Export as W3C format * const w3c = await did.exportW3C(signer.address) * ``` */ declare class DidModule extends BaseModule { constructor(config: GhostSpeakConfig); /** * Create a new DID document * * @param signer - Transaction signer (will be the controller) * @param params - DID creation parameters * @returns Transaction signature * * @example * ```typescript * const signature = await didModule.create(signer, { * controller: signer.address, * network: 'devnet', * verificationMethods: [{ * id: 'key-1', * methodType: VerificationMethodType.Ed25519VerificationKey2020, * controller: 'did:sol:devnet:...', * publicKeyMultibase: 'z...', * relationships: [VerificationRelationship.Authentication], * createdAt: Date.now() / 1000, * revoked: false * }] * }) * ``` */ create(signer: TransactionSigner, params: CreateDidDocumentParams): Promise; /** * Update an existing DID document * * @param signer - Transaction signer (must be the controller) * @param params - Update parameters * @returns Transaction signature * * @example * ```typescript * const signature = await didModule.update(signer, { * didDocument: didPda, * addVerificationMethod: { * id: 'key-2', * methodType: VerificationMethodType.X25519KeyAgreementKey2020, * controller: 'did:sol:devnet:...', * publicKeyMultibase: 'z...', * relationships: [VerificationRelationship.KeyAgreement], * createdAt: Date.now() / 1000, * revoked: false * } * }) * ``` */ update(signer: TransactionSigner, params: UpdateDidDocumentParams): Promise; /** * Deactivate a DID document (irreversible) * * @param signer - Transaction signer (must be the controller) * @param params - Deactivation parameters * @returns Transaction signature * * @example * ```typescript * const signature = await didModule.deactivate(signer, { * didDocument: didPda * }) * ``` */ deactivate(signer: TransactionSigner, params: DeactivateDidDocumentParams): Promise; /** * Resolve a DID document * * @param didOrController - DID string or controller address * @returns DID document or null if not found * * @example * ```typescript * // Resolve by controller address * const didDoc = await didModule.resolve(controllerAddress) * * // Resolve by DID string * const didDoc = await didModule.resolve('did:sol:devnet:5VKz...') * ``` */ resolve(didOrController: string | Address$1): Promise; /** * Export a DID document as W3C-compliant JSON * * @param didOrController - DID string or controller address * @param pretty - Whether to pretty-print the JSON * @returns W3C DID document JSON string * * @example * ```typescript * const json = await didModule.exportW3C(controllerAddress, true) * console.log(json) * ``` */ exportW3C(didOrController: string | Address$1, pretty?: boolean): Promise; /** * Get W3C DID document object * * @param didOrController - DID string or controller address * @returns W3C DID document object or null */ getW3CDocument(didOrController: string | Address$1): Promise; /** * Derive DID document PDA for a controller * * @param controller - Controller address * @returns DID document PDA and bump */ deriveDidPda(controller: Address$1): Promise<[Address$1, number]>; /** * Generate a DID string for a controller * * @param controller - Controller address * @param network - Network identifier * @returns DID string */ generateDid(controller: Address$1, network?: 'mainnet' | 'devnet' | 'testnet'): string; /** * Validate a DID string * * @param did - DID string to validate * @returns True if valid, throws error if invalid */ validateDid(did: string): boolean; /** * Check if a DID is active * * @param didOrController - DID string or controller address * @returns True if active, false if deactivated or not found */ isActive(didOrController: string | Address$1): Promise; /** * Build create DID instruction manually * Note: This is temporary until DID instructions are generated from IDL */ private buildCreateDidInstruction; /** * Build update DID instruction manually * Note: This is temporary until DID instructions are generated from IDL */ private buildUpdateDidInstruction; /** * Build deactivate DID instruction manually * Note: This is temporary until DID instructions are generated from IDL */ private buildDeactivateDidInstruction; /** * Create an Ed25519 verification method */ static createVerificationMethod: typeof createEd25519VerificationMethod; /** * Create a service endpoint */ static createServiceEndpoint: typeof createServiceEndpoint; } /** * GhostSpeak Credential Module * * Provides functionality for creating, signing, and exporting * W3C-compatible Verifiable Credentials with DID integration. */ interface W3CVerifiableCredential { '@context': string[]; type: string[]; id: string; issuer: { id: string; name?: string; } | string; validFrom: string; validUntil?: string; credentialSubject: { id?: string; [key: string]: unknown; }; credentialSchema?: { id: string; type: 'JsonSchema'; }; credentialStatus?: { id: string; type: string; statusPurpose: 'revocation' | 'suspension'; }; relatedResource?: Array<{ id: string; digestMultibase?: string; }>; proof: { type: 'DataIntegrityProof'; created: string; verificationMethod: string; cryptosuite: 'eddsa-rdfc-2022'; proofPurpose: 'assertionMethod'; proofValue: string; }; } /** * Unified Credential Service * * Bridges GhostSpeak's native Solana credentials with Crossmint's EVM-based VCs. */ interface UnifiedCredentialConfig { programId?: Address$1; crossmint?: CrossmintClientOptions; crossmintTemplates?: { agentIdentity?: string; reputation?: string; jobCompletion?: string; }; } interface IssuedCredentialResult { solanaCredential: { credentialId: string; }; w3cCredential: W3CVerifiableCredential; crossmintSync?: { status: 'pending' | 'synced' | 'failed'; credentialId?: string; chain?: string; error?: string; }; } declare class UnifiedCredentialService { private config; private credentialModule; private crossmintClient?; constructor(config: UnifiedCredentialConfig); /** * Issue an Agent Identity credential. * Note: logic simplified for SDK usage (mocking the on-chain part for now as per original implementation) */ issueAgentIdentityCredential(params: { agentId: string; owner: string; name: string; capabilities: string[]; serviceEndpoint: string; frameworkOrigin: string; x402Enabled: boolean; registeredAt: number; verifiedAt: number; recipientEmail?: string; syncToCrossmint?: boolean; signature: Uint8Array; }): Promise; } /** * Reputation tier levels */ declare enum ReputationTier { None = "None", Bronze = "Bronze", Silver = "Silver", Gold = "Gold", Platinum = "Platinum" } /** * Badge types for reputation achievements */ declare enum BadgeType { FirstJob = "FirstJob", TenJobs = "TenJobs", HundredJobs = "HundredJobs", ThousandJobs = "ThousandJobs", PerfectRating = "PerfectRating", QuickResponder = "QuickResponder", HighEarner = "HighEarner", DisputeResolver = "DisputeResolver", CategoryExpert = "CategoryExpert", CrossCategoryMaster = "CrossCategoryMaster" } /** * Category-specific reputation data */ interface CategoryReputation { /** Category identifier (e.g., "defi", "nft", "gaming") */ category: string; /** Current reputation score in this category (basis points) */ score: number; /** Total completed jobs in this category */ completedJobs: number; /** Average completion time in seconds */ avgCompletionTime: number; /** Quality ratings sum */ qualitySum: number; /** Number of quality ratings */ qualityCount: number; /** Last activity timestamp */ lastActivity: number; /** Total earnings in this category */ totalEarnings: number; } /** * Job performance data for reputation calculation */ interface JobPerformance { /** Whether job was completed successfully */ completed: boolean; /** Quality rating (0-100) */ qualityRating: number; /** Expected duration in seconds */ expectedDuration: number; /** Actual duration in seconds */ actualDuration: number; /** Client satisfaction (0-100) */ clientSatisfaction: number; /** Whether there was a dispute */ hadDispute: boolean; /** Whether dispute was resolved favorably for agent */ disputeResolvedFavorably: boolean; /** Job category */ category: string; /** Payment amount */ paymentAmount: number; } /** * Reputation calculation result */ interface ReputationCalculationResult { /** New overall score */ overallScore: number; /** Score for this specific job */ jobScore: number; /** Category-specific score */ categoryScore: number; /** New reputation tier */ tier: ReputationTier; /** Badges earned from this update */ newBadges: BadgeType[]; /** Whether fraud was detected */ fraudDetected: boolean; /** Fraud risk score (0-100) */ fraudRiskScore: number; } /** * Simplified reputation data for module use */ interface ReputationData { agent: Address$1; overallScore: number; totalJobsCompleted: number; totalJobsFailed: number; avgResponseTime: number; disputesAgainst: number; disputesResolved: number; lastUpdated: number; categoryReputations: CategoryReputation[]; badges: Array<{ badgeType: BadgeType; earnedAt: number; }>; performanceHistory: Array<{ timestamp: number; score: number; jobsCompleted: number; avgQuality: number; }>; factors: { completionWeight: number; qualityWeight: number; timelinessWeight: number; satisfactionWeight: number; disputeWeight: number; }; } /** * Reputation module for managing reputation calculations */ declare class ReputationModule extends BaseModule { private calculator; private tagEngine; constructor(config: GhostSpeakConfig); /** * Calculate reputation change for a job */ calculateReputationChange(currentData: ReputationData, jobPerformance: JobPerformance): ReputationCalculationResult; /** * Get tier name from tier enum */ getTierName(tier: ReputationTier): string; /** * Get tier from score */ getTierFromScore(score: number): ReputationTier; /** * Get badge display name */ getBadgeName(badge: BadgeType): string; /** * Calculate estimated APY boost from reputation */ calculateApyBoost(score: number): number; /** * Get reputation tier color for UI */ getTierColor(tier: ReputationTier): string; /** * Create default reputation data for new agents */ createDefaultReputationData(agentAddress: Address$1): ReputationData; /** * Check if agent qualifies for a specific tier */ qualifiesForTier(score: number, tier: ReputationTier): boolean; /** * Calculate points needed for next tier */ pointsToNextTier(score: number): { nextTier: ReputationTier; pointsNeeded: number; } | null; /** * Record a PayAI payment event to update reputation * * Converts PayAI webhook data to JobPerformance format and * calculates reputation change. * * @param record - PayAI reputation record from webhook * @param currentData - Current agent reputation data (fetched from on-chain or cache) * @returns Reputation calculation result */ recordPayAIPayment(record: PayAIReputationRecordInput, currentData: ReputationData): ReputationCalculationResult; /** * Convert a PayAI reputation record to JobPerformance format * * PayAI provides basic payment data, so we derive quality metrics * from response time and success status. */ payAIRecordToJobPerformance(record: PayAIReputationRecordInput): JobPerformance; /** * Estimate quality rating from response time * * Fast responses (< 500ms) = 100 quality * Average responses (500ms-2s) = 70-90 quality * Slow responses (2s-10s) = 40-70 quality * Very slow responses (> 10s) = 20-40 quality */ private estimateQualityFromResponseTime; /** * Estimate expected duration based on payment amount * * Larger payments = longer expected processing time */ private estimateExpectedDuration; /** * Categorize payment by network */ private categorizeFromNetwork; /** * Create a PayAI-compatible performance snapshot * Useful for tracking payment patterns */ createPayAIPerformanceSnapshot(record: PayAIReputationRecordInput, reputationResult: ReputationCalculationResult): { timestamp: number; paymentId: string; network: string; amount: string; success: boolean; responseTimeMs: number; reputationChange: number; newScore: number; tier: string; }; /** * Calculate tags for an agent based on metrics * * Automatically evaluates all tag criteria and assigns tags * with appropriate confidence scores. * * @param metrics - Agent reputation metrics * @returns Array of tag scores */ calculateTagsForAgent(metrics: ReputationMetrics): Promise; /** * Get tags by category * * Filters tags to only those in the specified category. * * @param tags - All tag scores * @param category - Category to filter by * @returns Filtered tag scores */ getTagsByCategory(tags: TagScore[], category: TagCategory): TagScore[]; /** * Check if agent has a specific tag * * @param tags - Agent's tag scores * @param tagName - Tag to check for * @returns Whether the tag exists */ hasTag(tags: TagScore[], tagName: string): boolean; /** * Get tag confidence score * * @param tags - Agent's tag scores * @param tagName - Tag to check * @returns Confidence score or undefined if tag doesn't exist */ getTagConfidence(tags: TagScore[], tagName: string): number | undefined; /** * Filter tags by criteria * * @param tags - Tags to filter * @param filters - Filter criteria * @returns Filtered tags */ filterTags(tags: TagScore[], filters: TagFilters): TagScore[]; /** * Apply tag decay based on age * * Reduces confidence scores for old tags and removes stale tags. * * @param tags - Current tag scores * @param currentTimestamp - Current Unix timestamp (optional) * @returns Tags with decay applied */ applyTagDecay(tags: TagScore[], currentTimestamp?: number): TagScore[]; /** * Merge new tags with existing tags * * Updates existing tags or adds new ones, preferring higher confidence. * * @param existingTags - Current tags * @param newTags - New tags to merge * @returns Merged tag list */ mergeTags(existingTags: TagScore[], newTags: TagScore[]): TagScore[]; /** * Categorize tags by type * * Organizes tags into skill, behavior, and compliance categories. * * @param tags - Tags to categorize * @returns Categorized tag result */ categorizeTags(tags: TagScore[]): TagQueryResult; /** * Get top N tags by confidence * * @param tags - Tags to sort * @param count - Number of tags to return * @returns Top tags */ getTopTags(tags: TagScore[], count: number): TagScore[]; /** * Sort tags by confidence (descending) * * @param tags - Tags to sort * @returns Sorted tags */ sortTagsByConfidence(tags: TagScore[]): TagScore[]; /** * Sort tags by evidence count (descending) * * @param tags - Tags to sort * @returns Sorted tags */ sortTagsByEvidence(tags: TagScore[]): TagScore[]; /** * Sort tags by most recently updated * * @param tags - Tags to sort * @returns Sorted tags */ sortTagsByRecent(tags: TagScore[]): TagScore[]; /** * Get confidence level description * * @param confidence - Confidence score (0-10000) * @returns Human-readable confidence level */ getConfidenceLevel(confidence: number): string; /** * Validate tag name length * * @param tagName - Tag name to validate * @returns Whether tag name is valid */ validateTagName(tagName: string): boolean; /** * Validate confidence score * * @param confidence - Confidence to validate * @returns Whether confidence is valid (0-10000) */ validateConfidence(confidence: number): boolean; /** * Convert on-chain ReputationMetrics to TagEngine format * * Helper to convert blockchain data to the format needed for tag calculation. * * @param onChainMetrics - Metrics from blockchain * @returns Metrics in TagEngine format */ convertMetricsForTagging(onChainMetrics: { successfulPayments: bigint; failedPayments: bigint; totalResponseTime: bigint; responseTimeCount: bigint; totalDisputes: number; disputesResolved: number; totalRating: number; totalRatingsCount: number; createdAt: number; updatedAt: number; }): ReputationMetrics; } /** * Interface for PayAI reputation record input * Matches the PayAIReputationRecord from payai module */ interface PayAIReputationRecordInput { agentAddress: Address$1; paymentSignature: string; amount: bigint; success: boolean; responseTimeMs: number; payerAddress: string; timestamp: Date; network: string; } /** * Privacy module for managing reputation privacy settings */ declare class PrivacyModule extends BaseModule { constructor(config: GhostSpeakConfig); /** * Initialize privacy settings for an agent * * Sets up privacy controls for an agent's reputation data. * By default, starts in Public mode with all metrics visible. * * @param signer - Transaction signer (must be agent owner) * @param params - Initialization parameters * @returns Transaction signature * * @example * ```typescript * const signature = await privacyModule.initializePrivacy(signer, { * agentAddress: agentPda, * mode: PrivacyMode.TierOnly, * metricVisibility: { * showScore: VisibilityLevel.Private, * showJobsCompleted: VisibilityLevel.Public, * // ... other metrics * } * }) * ``` */ initializePrivacy(signer: TransactionSigner, params: InitializePrivacyParams): Promise; /** * Update privacy mode for an agent * * Changes how reputation data is displayed publicly. * * @param signer - Transaction signer (must be agent owner) * @param params - Update parameters * @returns Transaction signature * * @example * ```typescript * // Switch to tier-only mode * await privacyModule.updatePrivacyMode(signer, { * agentAddress: agentPda, * mode: PrivacyMode.TierOnly * }) * ``` */ updatePrivacyMode(signer: TransactionSigner, params: UpdatePrivacyModeParams): Promise; /** * Set metric visibility settings * * Configure selective disclosure for individual metrics. * Only works in Custom privacy mode. * * @param signer - Transaction signer (must be agent owner) * @param params - Metric visibility parameters * @returns Transaction signature * * @example * ```typescript * await privacyModule.setMetricVisibility(signer, { * agentAddress: agentPda, * metricVisibility: { * showScore: VisibilityLevel.Private, * showJobsCompleted: VisibilityLevel.Public, * showSuccessRate: VisibilityLevel.Public, * showResponseTime: VisibilityLevel.Public, * showDisputes: VisibilityLevel.Private, * showEarnings: VisibilityLevel.Private, * showRatings: VisibilityLevel.Public, * showBadges: VisibilityLevel.Public * } * }) * ``` */ setMetricVisibility(signer: TransactionSigner, params: SetMetricVisibilityParams): Promise; /** * Grant viewer access to private reputation data * * Adds an address to the authorized viewers list, giving them * full access to all private metrics. * * @param signer - Transaction signer (must be agent owner) * @param params - Grant access parameters * @returns Transaction signature * * @example * ```typescript * // Grant access to a client * await privacyModule.grantAccess(signer, { * agentAddress: agentPda, * viewer: clientAddress * }) * ``` */ grantAccess(signer: TransactionSigner, params: GrantAccessParams): Promise; /** * Revoke viewer access to private reputation data * * Removes an address from the authorized viewers list. * * @param signer - Transaction signer (must be agent owner) * @param params - Revoke access parameters * @returns Transaction signature * * @example * ```typescript * // Revoke access from a viewer * await privacyModule.revokeAccess(signer, { * agentAddress: agentPda, * viewer: viewerAddress * }) * ``` */ revokeAccess(signer: TransactionSigner, params: RevokeAccessParams): Promise; /** * Apply a privacy preset * * Quickly configure privacy settings using a predefined preset * (Conservative, Balanced, or Open). * * @param signer - Transaction signer (must be agent owner) * @param params - Preset parameters * @returns Transaction signature * * @example * ```typescript * // Apply balanced preset * await privacyModule.applyPreset(signer, { * agentAddress: agentPda, * preset: PrivacyPresets.BALANCED * }) * ``` */ applyPreset(signer: TransactionSigner, params: ApplyPresetParams): Promise; /** * Get privacy settings for an agent * * Fetches the current privacy configuration. * * @param agentAddress - Agent address * @returns Privacy settings or null if not initialized * * @example * ```typescript * const settings = await privacyModule.getPrivacySettings(agentPda) * if (settings) { * console.log('Privacy mode:', settings.mode) * console.log('Authorized viewers:', settings.authorizedViewers.length) * } * ``` */ getPrivacySettings(agentAddress: Address$1): Promise; /** * Get visible reputation data (privacy-filtered) * * Fetches reputation data and applies privacy filters based on * the viewer's access level. * * @param agentAddress - Agent address * @param viewerAddress - Viewer address (for access check) * @returns Privacy-filtered reputation data * * @example * ```typescript * // Get visible reputation for a specific viewer * const visibleRep = await privacyModule.getVisibleReputation( * agentPda, * viewerAddress * ) * * console.log('Tier:', visibleRep.tier) * console.log('Exact score:', visibleRep.exactScore) // Only if visible * console.log('Has full access:', visibleRep.hasFullAccess) * ``` */ getVisibleReputation(agentAddress: Address$1, viewerAddress: Address$1): Promise; /** * Validate privacy settings before applying * * @param settings - Privacy settings to validate * @returns Validation result */ validateSettings(settings: PrivacySettings): { valid: boolean; errors: string[]; }; /** * Get available privacy presets * * @returns Record of available presets */ getAvailablePresets(): Record; /** * Get default metric visibility for a privacy mode * * @param mode - Privacy mode * @returns Default metric visibility */ getDefaultVisibility(mode: PrivacyMode): MetricVisibility; /** * Calculate reputation tier from score * * @param score - Reputation score * @returns Reputation tier */ getTier(score: number): ReputationTier$1; /** * Calculate score range from score * * @param score - Reputation score * @returns Score range */ getRange(score: number): ScoreRange; private derivePrivacyPda; } /** * Agent Authorization System Types * * GhostSpeak's trustless authorization mechanism for agents to * pre-authorize reputation updates with cryptographic signatures. * * Built for secure, delegated reputation management across protocols. */ /** * Network types supported by GhostSpeak */ type SolanaNetwork = 'mainnet-beta' | 'devnet' | 'testnet' | 'localnet'; /** * Configuration for on-chain authorization storage * * On-chain storage provides an immutable audit trail for authorizations, * but costs ~0.002 SOL in rent. Off-chain storage (default) is free but * requires agents to share signed authorizations with facilitators. */ interface OnChainStorageConfig { /** Enable on-chain storage (default: false for cost efficiency) */ enabled: boolean; /** * Storage fee in lamports (default: 0.002 SOL = 2000000 lamports for rent) * This covers the account rent exemption cost on Solana */ storageFee?: bigint; /** * Who pays the storage fee * - true: Agent pays (stored authorization benefits agent's transparency) * - false: Facilitator pays (facilitator wants on-chain proof) * Default: true (agent pays for their own authorization storage) */ feePayedByAgent?: boolean; /** * Automatically store on-chain after creation * - true: Store immediately (requires funded wallet) * - false: Manual storage via storeAuthorizationOnChain() * Default: false (manual control) */ autoStore?: boolean; /** * Custom fee structure for different authorization durations * Maps duration in seconds to fee in lamports * Example: { 2592000: 1000000n } // 30 days = 0.001 SOL */ customFees?: Record; } /** * Reputation Authorization * * Allows an agent to pre-authorize a specific source (e.g., PayAI facilitator) * to update their reputation a limited number of times before expiration. */ interface ReputationAuthorization { /** Agent's public key (the one granting authorization) */ agentAddress: Address$1; /** Authorized source address (e.g., PayAI facilitator address) */ authorizedSource: Address$1; /** Maximum number of reputation updates allowed */ indexLimit: number; /** Unix timestamp when authorization expires */ expiresAt: number; /** Solana network this authorization is valid on */ network: SolanaNetwork; /** Ed25519 signature (64 bytes) proving agent's intent */ signature: Uint8Array; /** Optional nonce to prevent replay attacks */ nonce?: string; /** Optional metadata */ metadata?: AuthorizationMetadata; } /** * Authorization metadata (optional fields) */ interface AuthorizationMetadata { /** Human-readable description */ description?: string; /** Tags for categorization */ tags?: string[]; /** Custom data */ customData?: Record; /** Creation timestamp */ createdAt?: number; /** Version of authorization format */ version?: string; } /** * Authorization creation parameters */ interface CreateAuthorizationParams { /** Authorized source (e.g., PayAI facilitator) */ authorizedSource: Address$1; /** Maximum number of updates (default: 1000) */ indexLimit?: number; /** Expiration time in seconds from now (default: 30 days) */ expiresIn?: number; /** Specific expiration timestamp (overrides expiresIn) */ expiresAt?: number; /** Network (defaults to current cluster) */ network?: SolanaNetwork; /** Optional nonce for replay protection */ nonce?: string; /** Optional metadata */ metadata?: AuthorizationMetadata; /** * On-chain storage configuration * If not provided, defaults to off-chain (free) storage */ onChainStorage?: OnChainStorageConfig; } /** * Authorization status */ declare enum AuthorizationStatus { ACTIVE = "active", EXPIRED = "expired", EXHAUSTED = "exhausted",// Index limit reached REVOKED = "revoked", PENDING = "pending" } /** * Authorization with status */ interface AuthorizationWithStatus extends ReputationAuthorization { /** Current status */ status: AuthorizationStatus; /** Current usage count */ currentIndex: number; /** Remaining uses */ remainingUses: number; /** Whether currently valid */ isValid: boolean; /** Last used timestamp */ lastUsedAt?: number; /** Authorization ID (derived from signature or on-chain account) */ id: string; } /** * Authorization query filter */ interface AuthorizationFilter { /** Filter by agent address */ agentAddress?: Address$1; /** Filter by authorized source */ authorizedSource?: Address$1; /** Filter by status */ status?: AuthorizationStatus | AuthorizationStatus[]; /** Filter by network */ network?: SolanaNetwork; /** Filter by expiration (before/after timestamp) */ expiresAfter?: number; expiresBefore?: number; /** Filter by creation time */ createdAfter?: number; createdBefore?: number; /** Pagination */ limit?: number; offset?: number; } /** * Agent Authorization Signature Verification * * Ed25519 signature creation and verification for GhostSpeak's * trustless agent pre-authorization system. * * Enables verifiable delegation of reputation update authority. */ /** * Keypair interface for Ed25519 signing operations * Compatible with both legacy and modern Solana key formats */ interface SigningKeypair { publicKey: { toBase58(): string; toBytes(): Uint8Array; }; secretKey: Uint8Array; } /** * Authorization Module - Agent Pre-Authorization System * * GhostSpeak's trustless system for agents to pre-authorize facilitators * (e.g., PayAI) to update their reputation with built-in security limits. * * @module AuthorizationModule */ /** * Authorization Module * * Manages agent pre-authorizations for reputation updates. */ declare class AuthorizationModule extends BaseModule { constructor(config: GhostSpeakConfig); /** * Create a signed authorization for a facilitator * * @param params - Authorization parameters * @param agentKeypair - Agent's keypair for signing * @returns Signed authorization * * @example * ```typescript * const authorization = await client.authorization.createAuthorization({ * authorizedSource: payAIFacilitatorAddress, * indexLimit: 1000, // Allow 1000 reputation updates * expiresIn: 30 * 24 * 60 * 60, // 30 days * network: 'devnet', * }, agentKeypair) * ``` */ createAuthorization(params: CreateAuthorizationParams, agentKeypair: SigningKeypair): Promise; /** * Store authorization on-chain (optional, ~0.002 SOL fee) * * Creates a PDA account storing the authorization for on-chain verification. * This provides an immutable audit trail but costs rent (~0.002 SOL). * * **Cost vs Benefit:** * - Off-chain (default): Free, but requires sharing signed authorization * - On-chain: ~0.002 SOL, provides transparent audit trail * * **When to use on-chain storage:** * - High-value authorizations where transparency is critical * - Compliance/audit requirements * - Public agent reputation systems * * @param authorization - Authorization to store * @param agentSigner - Agent's signer (or facilitator if they pay fee) * @param config - Optional storage configuration * @returns Transaction signature * * @example * ```typescript * // Default: Agent pays ~0.002 SOL * const sig = await client.authorization.storeAuthorizationOnChain(auth, agentSigner) * * // Custom fee structure * const sig = await client.authorization.storeAuthorizationOnChain(auth, agentSigner, { * storageFee: 1500000n, // 0.0015 SOL * feePayedByAgent: false // Facilitator pays * }) * ``` */ storeAuthorizationOnChain(authorization: ReputationAuthorization, agentSigner: TransactionSigner, config?: Partial): Promise; /** * Verify authorization signature * * @param authorization - Authorization to verify * @returns True if signature is valid * * @example * ```typescript * const isValid = await client.authorization.verifySignature(authorization) * if (!isValid) { * throw new Error('Invalid authorization signature') * } * ``` */ verifySignature(authorization: ReputationAuthorization): Promise; /** * Check authorization status (without on-chain call) * * @param authorization - Authorization to check * @param currentIndex - Current usage count (optional, defaults to authorization.currentIndex) * @returns Authorization status */ getAuthorizationStatus(authorization: ReputationAuthorization, currentIndex?: number): { status: AuthorizationStatus; isValid: boolean; remainingUses: number; reason?: string; }; /** * Fetch authorization from on-chain PDA * * @param agentAddress - Agent's address * @param authorizedSource - Authorized source address * @param nonce - Optional nonce (must match creation) * @returns Authorization with current on-chain status */ fetchAuthorization(agentAddress: Address$1, authorizedSource: Address$1, nonce?: string): Promise; /** * Update reputation using authorization * * Called by facilitators (e.g., PayAI) to update agent reputation * using a pre-signed authorization. * * @param authorization - Authorization to use * @param reputationChange - Reputation change to apply * @param transactionSignature - Transaction signature for audit trail * @param usageRecord - PDA for usage record (audit trail) * @param metadata - Optional metadata * @param facilitatorSigner - Facilitator's signer * @returns Transaction signature */ updateReputationWithAuth(authorization: ReputationAuthorization, reputationChange: number, transactionSignature: string, usageRecord: Address$1, metadata: Record | undefined, facilitatorSigner: TransactionSigner): Promise; /** * Revoke authorization * * Agent can revoke an authorization before it expires or is exhausted. * * @param agentAddress - Agent's address * @param authorization - Authorization account PDA * @param nonce - Optional nonce (must match creation) * @param agentSigner - Agent's signer * @returns Transaction signature */ revokeAuthorization(agentAddress: Address$1, authorization: Address$1, nonce: string | undefined, agentSigner: TransactionSigner): Promise; /** * List authorizations for an agent (filtering) * * @param filter - Filter criteria * @returns List of authorizations */ listAuthorizations(filter: AuthorizationFilter): Promise; /** * Serialize authorization for storage/transmission * * @param authorization - Authorization to serialize * @returns JSON-safe object */ serializeAuthorization(authorization: ReputationAuthorization): Record; /** * Deserialize authorization from storage/transmission * * @param data - Serialized authorization data * @returns Authorization object */ deserializeAuthorization(data: Record): ReputationAuthorization; /** * Get authorization ID (deterministic hash) * * @param authorization - Authorization to hash * @returns Base58-encoded hash */ getAuthorizationId(authorization: ReputationAuthorization): Promise; /** * Helper: Create authorization for PayAI facilitator * * Convenience method with sensible defaults for PayAI integration. * * @param payAIFacilitatorAddress - PayAI facilitator address * @param agentKeypair - Agent's keypair * @param options - Optional overrides * @returns Signed authorization * * @example * ```typescript * const auth = await client.authorization.createPayAIAuthorization( * 'PayAI...FacilitatorAddress', * agentKeypair, * { indexLimit: 5000 } // Optional overrides * ) * ``` */ createPayAIAuthorization(payAIFacilitatorAddress: Address$1, agentKeypair: SigningKeypair, options?: Partial): Promise; /** * Calculate storage fee based on authorization duration and custom fees * * @param authorization - Authorization to calculate fee for * @param config - Storage configuration * @returns Fee in lamports * * @example * ```typescript * // Default fee: 0.002 SOL * const fee = module.calculateStorageFee(auth) * * // Custom fee for 30-day authorizations: 0.001 SOL * const fee = module.calculateStorageFee(auth, { * customFees: { 2592000: 1000000n } // 30 days = 0.001 SOL * }) * ``` */ private calculateStorageFee; /** * Estimate on-chain storage cost for an authorization * * @param params - Authorization parameters * @param config - Optional storage configuration * @returns Estimated cost in SOL * * @example * ```typescript * const costInSOL = await client.authorization.estimateStorageCost({ * authorizedSource: facilitatorAddress, * expiresIn: 30 * 24 * 60 * 60 // 30 days * }) * console.log(`On-chain storage will cost ${costInSOL} SOL`) * ``` */ estimateStorageCost(params: CreateAuthorizationParams, config?: Partial): Promise; } interface StakeParams { /** Agent address to stake for */ agent: Address$1; /** Agent's token account holding GHOST tokens */ agentTokenAccount: Address$1; /** Staking vault to receive tokens */ stakingVault: Address$1; /** Global staking config account */ stakingConfig: Address$1; /** GHOST token mint address */ ghostMint: Address$1; /** Amount of GHOST tokens to stake (in lamports) */ amount: bigint; /** Lock duration in seconds */ lockDuration: bigint; /** The agent owner's transaction signer */ agentOwner: TransactionSigner; } interface UnstakeParams { /** Staking account to unstake from */ stakingAccount: Address$1; /** Agent address */ agent: Address$1; /** Staking vault holding the tokens */ stakingVault: Address$1; /** Agent's token account to receive tokens */ agentTokenAccount: Address$1; /** The agent owner's transaction signer */ agentOwner: TransactionSigner; } interface InitializeStakingConfigParams { /** Admin who can modify staking config */ authority: TransactionSigner; /** Minimum stake amount */ minStake: bigint; /** Treasury address to receive fees */ treasury: Address$1; } declare class StakingModule extends BaseModule { /** * Initialize the global staking configuration (admin only) */ initializeStakingConfig(params: InitializeStakingConfigParams): Promise; /** * Stake GHOST tokens for an agent * * @param params - Staking parameters * @returns Transaction signature */ stake(params: StakeParams): Promise; /** * Unstake GHOST tokens from an agent * * @param params - Unstaking parameters * @returns Transaction signature */ unstake(params: UnstakeParams): Promise; /** * Get staking account for an agent * * @param stakingAccountAddress - The staking account address * @returns Staking account data or null if not found */ getStakingAccount(stakingAccountAddress: Address$1): Promise; /** * Get the global staking configuration * * @param stakingConfigAddress - The staking config account address * @returns Staking config data or null if not initialized */ getStakingConfig(stakingConfigAddress: Address$1): Promise; } /** * Main GhostSpeak client with fluent API design * * Example usage: * ```typescript * const ghostspeak = new GhostSpeak() * * // Create an agent * const agent = await ghostspeak * .agent() * .create({ name: "My Agent", capabilities: ["coding"] }) * .compressed() * .execute() * * ``` */ declare class GhostSpeakClient { private config; constructor(config?: Partial); /** * Direct access to Agent Module for read operations */ get agents(): AgentModule; /** * Direct access to Ghost Module for claiming external agents * * Ghosts are external AI agents (type 10) that exist on x402 facilitators. * They can be claimed using Solana Attestation Service (SAS) * for trustless ownership verification. */ get ghosts(): GhostModule; /** * Direct access to Governance Module for read operations */ get governanceModule(): GovernanceModule; /** * Direct access to Multisig Module for read operations */ get multisigModule(): MultisigModule; /** * Agent operations */ agent(): AgentBuilder; /** * Reputation operations */ reputation(): ReputationModule; /** * Reputation Tag Engine (Pillar 2: Granular Tags) * * Automatic tag assignment and management based on agent metrics. * Features confidence scoring, evidence tracking, and tag decay. */ tagEngine(): any; /** * Multi-Source Reputation Aggregator (Pillar 3: External Sources) * * Aggregate reputation data from multiple sources (x402, GitHub, custom webhooks) * with weighted scoring and conflict detection. */ reputationAggregator(): any; /** * Privacy operations */ privacy(): PrivacyModule; /** * Governance operations */ governance(): GovernanceBuilder; /** * Multisig operations */ multisig(): MultisigBuilder; /** * Unified Credential operations (Solana + Crossmint) */ credentials(): UnifiedCredentialService; /** * DID operations (Decentralized Identifiers) */ did(): DidModule; /** * Direct access to Authorization Module for read operations */ get authorization(): AuthorizationModule; /** * Direct access to Staking Module for read operations */ get staking(): StakingModule; /** * Enable development mode features */ enableDevMode(): this; /** * Configure network */ useNetwork(cluster: 'mainnet-beta' | 'devnet' | 'testnet' | 'localnet'): this; /** * Configure custom RPC */ useRpc(endpoint: string, wsEndpoint?: string): this; /** * Get default RPC endpoint for cluster */ private getDefaultRpcEndpoint; } /** * Agent builder for fluent API */ declare class AgentBuilder { private module; private params; constructor(config: GhostSpeakConfig); create(params: { name: string; description?: string; capabilities: string[]; }): this; withDescription(description: string): this; withType(agentType: number): this; withIPFS(): this; compressed(): this; debug(): this; withSigner(signer: TransactionSigner): this; private validateParams; getCost(): Promise; simulate(): Promise; explain(): Promise; execute(): Promise<{ address: Address$1; signature: string; }>; private deriveAgentAddress; } /** * Channel builder parameters interface */ /** * Marketplace builder for fluent API */ /** * Governance builder for fluent API */ declare class GovernanceBuilder { private module; private params; constructor(config: GhostSpeakConfig); /** * Create a governance proposal */ proposal(): ProposalBuilder; /** * Get governance queries */ query(): GovernanceQuery; debug(): this; withSigner(signer: TransactionSigner): this; } /** * Governance builder parameters interface */ interface GovernanceBuilderParams { signer?: TransactionSigner; } /** * Proposal builder for fluent API */ declare class ProposalBuilder { private module; private builderParams; private params; constructor(module: GovernanceModule, builderParams: GovernanceBuilderParams); create(params: { title: string; description: string; }): this; type(proposalType: 'parameter_change' | 'upgrade' | 'treasury'): this; votingDuration(hours: number): this; executionDelay(hours: number): this; private validateParams; execute(): Promise<{ address: Address$1; signature: string; }>; withSigner(signer: TransactionSigner): this; } /** * Governance query helper */ declare class GovernanceQuery { private module; constructor(module: GovernanceModule); activeProposals(): Promise<{ address: Address$1; data: GovernanceProposal; }[]>; proposalsByProposer(proposer: Address$1): Promise<{ address: Address$1; data: GovernanceProposal; }[]>; proposalsByStatus(status: 'draft' | 'voting' | 'succeeded' | 'defeated' | 'executed'): Promise<{ address: Address$1; data: GovernanceProposal; }[]>; } /** * Multisig builder for fluent API */ declare class MultisigBuilder { private module; private params; constructor(config: GhostSpeakConfig); create(): CreateMultisigBuilder; proposal(): MultisigProposalBuilder; approve(): MultisigApproveBuilder; executeProposal(): MultisigExecuteBuilder; withSigner(signer: TransactionSigner): this; debug(): this; } interface MultisigBuilderParams { signer?: TransactionSigner; } declare class CreateMultisigBuilder { private module; private builderParams; private params; constructor(module: MultisigModule, builderParams: MultisigBuilderParams); withId(id: bigint): this; threshold(t: number): this; signers(s: Address$1[]): this; execute(): Promise<{ signature: string; }>; withSigner(signer: TransactionSigner): this; } declare class MultisigProposalBuilder { private module; private builderParams; private params; constructor(module: MultisigModule, builderParams: MultisigBuilderParams); forMultisig(address: Address$1): this; title(t: string): this; description(d: string): this; execute(): Promise<{ signature: string; }>; withSigner(signer: TransactionSigner): this; } declare class MultisigApproveBuilder { private module; private builderParams; private params; constructor(module: MultisigModule, builderParams: MultisigBuilderParams); proposal(address: Address$1): this; vote(choice: VoteChoice): this; reason(text: string): this; tokenAccount(account: Address$1): this; execute(): Promise<{ signature: string; }>; withSigner(signer: TransactionSigner): this; } declare class MultisigExecuteBuilder { private module; private builderParams; private params; constructor(module: MultisigModule, builderParams: MultisigBuilderParams); proposal(address: Address$1): this; target(programId: Address$1): this; execute(): Promise<{ signature: string; }>; withSigner(signer: TransactionSigner): this; } /** * Common utility functions for GhostSpeak SDK */ /** * Convert SOL to lamports */ declare function sol(amount: number): bigint; /** * Smart Error System with Actionable Solutions * * Every error includes context and suggested solutions to help developers * quickly resolve issues. */ /** * Base GhostSpeak error class */ declare class GhostSpeakError extends Error { readonly code: ErrorCode; readonly context: Record; readonly solution?: string; readonly instruction?: string; constructor(code: ErrorCode, message: string, context?: Record, solution?: string, instruction?: string); /** * Format error for display */ toString(): string; /** * Convert to SDK error type */ toSDKError(): SDKError; } /** * Network-related errors */ declare class NetworkError extends GhostSpeakError { constructor(endpoint: string, originalError?: Error); } /** * Insufficient balance error */ declare class InsufficientBalanceError extends GhostSpeakError { constructor(required: bigint, available: bigint, address: Address$1); } /** * Validation error for invalid inputs */ declare class ValidationError extends GhostSpeakError { constructor(message: string, context?: Record); } export { type Agent, AgentType, type Channel, ChannelType, type Escrow, EscrowStatus, type GhostSpeakConfig, GhostSpeakError, InsufficientBalanceError, NetworkError, type SDKError, ValidationError, GhostSpeakClient as default, sol };