@legacychain/sdk
Version:
Official SDK for interacting with LegacyChain smart contracts and APIs
489 lines (475 loc) • 14.3 kB
TypeScript
import { EventEmitter } from 'eventemitter3';
import { ethers } from 'ethers';
declare enum PlanType {
FREE = "FREE",
STARTER = "STARTER",
PRO = "PRO",
ENTERPRISE = "ENTERPRISE"
}
interface RateLimits {
requests: {
perMinute: number;
perHour: number;
perDay: number;
};
capsules: {
maxPerMonth: number;
maxStorage: number;
};
features: {
encryption: boolean;
multiSignature: boolean;
advancedAnalytics: boolean;
customBranding: boolean;
prioritySupport: boolean;
webhooks: boolean;
};
}
declare const PLAN_LIMITS: Record<PlanType, RateLimits>;
interface SDKConfig {
apiKey: string;
network?: 'mainnet' | 'testnet' | 'devnet';
rpcUrl?: string;
ipfsGateway?: string;
pinataJwt?: string;
debug?: boolean;
cache?: {
enabled: boolean;
ttl?: number;
};
retry?: {
attempts: number;
delay: number;
};
}
interface TimeCapsule {
id: string;
ipfsHash: string;
unlockTime: Date;
authorizedAddresses: string[];
isUnlocked: boolean;
metadata?: CapsuleMetadata;
createdAt: Date;
updatedAt: Date;
}
interface CapsuleMetadata {
title: string;
description: string;
type: 'text' | 'file' | 'mixed';
encrypted: boolean;
fileCount?: number;
totalSize?: number;
tags?: string[];
}
interface CreateCapsuleInput {
title: string;
description: string;
content: string | File | File[];
unlockTime: Date;
authorizedAddresses?: string[];
encrypt?: boolean;
password?: string;
metadata?: Record<string, any>;
}
interface PaymentCapsule {
id: string;
sender: string;
recipient: string;
amount: string;
token: 'ETH' | 'USDC' | 'USDT' | 'DAI';
unlockTime: Date;
status: 'pending' | 'claimable' | 'claimed' | 'refunded';
message?: string;
encrypted?: boolean;
createdAt: Date;
claimedAt?: Date;
}
interface CreatePaymentInput {
recipient: string;
amount: string;
token: 'ETH' | 'USDC' | 'USDT' | 'DAI';
unlockTime: Date;
message?: string;
encrypt?: boolean;
password?: string;
}
interface LegalDocument {
id: string;
documentHash: string;
documentType: 'NDA' | 'CONTRACT' | 'WILL' | 'AGREEMENT' | 'CERTIFICATE';
creator: string;
signers: SignerInfo[];
requiredSignatures: number;
status: 'draft' | 'pending' | 'active' | 'expired' | 'destroyed';
effectiveDate: Date;
expiryDate?: Date;
selfDestruct?: SelfDestructConfig;
metadata?: LegalMetadata;
createdAt: Date;
updatedAt: Date;
}
interface SignerInfo {
address: string;
signed: boolean;
signature?: string;
signedAt?: Date;
name?: string;
email?: string;
}
interface SelfDestructConfig {
type: 'time' | 'views' | 'manual';
value?: number | Date;
currentViews?: number;
}
interface LegalMetadata {
title: string;
parties: string[];
jurisdiction?: string;
encrypted: boolean;
fileType: string;
fileSize: number;
checksum: string;
}
interface CreateLegalDocumentInput {
file: File;
documentType: LegalDocument['documentType'];
signers: string[];
requiredSignatures?: number;
effectiveDate?: Date;
expiryDate?: Date;
selfDestruct?: SelfDestructConfig;
encrypt?: boolean;
password?: string;
metadata?: Record<string, any>;
}
interface ApiResponse<T> {
success: boolean;
data?: T;
error?: ApiError;
metadata?: {
timestamp: number;
requestId: string;
rateLimit?: {
limit: number;
remaining: number;
reset: number;
};
};
}
interface ApiError {
code: string;
message: string;
details?: any;
}
interface SDKEvents {
'capsule:created': (capsule: TimeCapsule) => void;
'capsule:unlocked': (capsuleId: string) => void;
'payment:created': (payment: PaymentCapsule) => void;
'payment:claimed': (paymentId: string) => void;
'document:created': (document: LegalDocument) => void;
'document:signed': (documentId: string, signer: string) => void;
'rateLimit:exceeded': (limit: RateLimits) => void;
'error': (error: ApiError) => void;
}
interface PaginationParams {
page?: number;
limit?: number;
sortBy?: string;
sortOrder?: 'asc' | 'desc';
}
interface PaginatedResponse<T> {
items: T[];
total: number;
page: number;
limit: number;
hasNext: boolean;
hasPrev: boolean;
}
interface CapsuleFilters {
status?: 'locked' | 'unlocked';
type?: 'time' | 'payment' | 'legal';
createdAfter?: Date;
createdBefore?: Date;
creator?: string;
search?: string;
}
interface AnalyticsData {
totalCapsules: number;
totalPayments: number;
totalDocuments: number;
storageUsed: number;
activeUsers: number;
monthlyGrowth: number;
topCategories: Array<{
type: string;
count: number;
percentage: number;
}>;
}
interface WebhookConfig {
url: string;
events: string[];
secret?: string;
active: boolean;
}
interface WebhookPayload {
event: string;
data: any;
timestamp: number;
signature?: string;
}
declare class TimeCapsuleService {
private client;
private contractAddress;
constructor(client: LegacyChainClient);
create(input: CreateCapsuleInput): Promise<TimeCapsule>;
get(capsuleId: string): Promise<TimeCapsule>;
list(params?: PaginationParams & {
filters?: CapsuleFilters;
}): Promise<PaginatedResponse<TimeCapsule>>;
unlock(capsuleId: string, password?: string): Promise<any>;
addAuthorizedAddress(capsuleId: string, address: string): Promise<void>;
removeAuthorizedAddress(capsuleId: string, address: string): Promise<void>;
isAuthorized(capsuleId: string, address: string): Promise<boolean>;
private fileToBase64;
}
declare class PaymentService {
private client;
private contractAddress;
constructor(client: LegacyChainClient);
create(input: CreatePaymentInput): Promise<PaymentCapsule>;
claim(paymentId: string): Promise<void>;
refund(paymentId: string): Promise<void>;
get(paymentId: string): Promise<PaymentCapsule>;
list(params?: PaginationParams): Promise<PaginatedResponse<PaymentCapsule>>;
getBalance(token: 'ETH' | 'USDC' | 'USDT' | 'DAI'): Promise<string>;
private getTokenAddress;
private approveToken;
decryptMessage(payment: PaymentCapsule, password: string): Promise<string>;
}
declare class LegalDocumentService {
private client;
private contractAddress;
constructor(client: LegacyChainClient);
create(input: CreateLegalDocumentInput): Promise<LegalDocument>;
sign(documentId: string, signature: string): Promise<void>;
generateSignature(documentId: string): Promise<string>;
get(documentId: string): Promise<LegalDocument>;
list(params?: PaginationParams): Promise<PaginatedResponse<LegalDocument>>;
recordView(documentId: string): Promise<void>;
destroy(documentId: string): Promise<void>;
downloadDocument(document: LegalDocument, password?: string): Promise<Blob>;
verifyDocument(documentId: string): Promise<boolean>;
private configureSelfDestruct;
private fileToBase64;
private calculateChecksum;
}
declare class AnalyticsService {
private client;
constructor(client: LegacyChainClient);
getOverview(): Promise<AnalyticsData>;
getCapsuleStats(timeRange?: {
start: Date;
end: Date;
}): Promise<any>;
getPaymentStats(timeRange?: {
start: Date;
end: Date;
}): Promise<any>;
getDocumentStats(timeRange?: {
start: Date;
end: Date;
}): Promise<any>;
getUsageMetrics(): Promise<any>;
trackEvent(eventName: string, properties?: Record<string, any>): Promise<void>;
getStorageUsage(): Promise<{
used: number;
limit: number;
percentage: number;
}>;
getRateLimitStatus(): Promise<any>;
exportData(format: 'csv' | 'json', type: 'capsules' | 'payments' | 'documents' | 'all'): Promise<Blob>;
}
declare class IPFSService {
private gateway;
private pinataJwt?;
private pinataUrl;
constructor(gateway?: string, pinataJwt?: string);
uploadFile(file: File, metadata?: Record<string, any>): Promise<string>;
uploadJSON(data: any, name: string, metadata?: Record<string, any>): Promise<string>;
retrieveFile(ipfsHash: string): Promise<Blob>;
retrieveJSON<T = any>(ipfsHash: string): Promise<T>;
unpin(ipfsHash: string): Promise<boolean>;
getGatewayUrl(ipfsHash: string): string;
setGateway(gateway: string): void;
}
declare class CryptoService {
private encoder;
private decoder;
encrypt(text: string, password: string): Promise<{
encrypted: string;
salt: string;
iv: string;
}>;
decrypt(encryptedData: string, password: string, salt: string, iv: string): Promise<string>;
hashPassword(password: string): Promise<string>;
generatePassword(length?: number): string;
generateKeyPair(): Promise<{
publicKey: string;
privateKey: string;
}>;
private deriveKey;
private arrayBufferToBase64;
private base64ToArrayBuffer;
}
declare class LegacyChainClient extends EventEmitter<SDKEvents> {
private config;
private httpClient;
private rateLimiter;
private queue;
private logger;
timeCapsules: TimeCapsuleService;
payments: PaymentService;
legalDocuments: LegalDocumentService;
analytics: AnalyticsService;
ipfs: IPFSService;
crypto: CryptoService;
private publicClient;
private walletClient;
private provider?;
private signer?;
constructor(config: SDKConfig);
private initializeWeb3Clients;
connectWallet(ethereum: any): Promise<void>;
private getPlanTypeFromApiKey;
private getApiBaseUrl;
makeRequest<T>(method: 'GET' | 'POST' | 'PUT' | 'DELETE', endpoint: string, data?: any, options?: any): Promise<ApiResponse<T>>;
getPublicClient(): any;
getWalletClient(): any;
getProvider(): ethers.Provider | undefined;
getSigner(): ethers.Signer;
getRateLimits(): RateLimits;
getConfig(): {
apiKey: string;
network?: "mainnet" | "testnet" | "devnet";
rpcUrl?: string;
ipfsGateway?: string;
pinataJwt?: string;
debug?: boolean;
cache?: {
enabled: boolean;
ttl?: number;
};
retry?: {
attempts: number;
delay: number;
};
};
updateConfig(newConfig: Partial<SDKConfig>): void;
destroy(): void;
}
declare class Logger {
private debug;
constructor(debug?: boolean);
log(message: string, ...args: any[]): void;
error(message: string, error?: any): void;
warn(message: string, ...args: any[]): void;
info(message: string, ...args: any[]): void;
}
interface PaymentRecord {
txHash: string;
payer: string;
amount: string;
token: string;
plan: PlanType;
duration: number;
timestamp: number;
expiresAt: number;
verified: boolean;
}
interface PlanPricing {
monthly: string;
yearly: string;
token: 'ETH' | 'USDC';
}
declare class PaymentVerificationService {
private provider;
private paymentRecords;
private apiKeyToAddress;
private addressToPlan;
private static PLAN_PRICING;
private static PAYMENT_ADDRESS;
constructor(provider?: ethers.Provider);
/**
* Verify a payment transaction and activate the plan
*/
verifyPayment(txHash: string, expectedPlan: PlanType, duration?: number): Promise<boolean>;
/**
* Get the current plan for an API key
*/
getPlanForApiKey(apiKey: string): PlanType;
/**
* Link an API key to a wallet address
*/
linkApiKeyToAddress(apiKey: string, address: string): void;
/**
* Get payment history for an address
*/
getPaymentHistory(address: string): PaymentRecord[];
/**
* Get pricing information
*/
static getPricing(): Record<PlanType, PlanPricing>;
/**
* Generate a payment request
*/
generatePaymentRequest(plan: PlanType, duration?: number): {
to: string;
amount: string;
token: string;
data: string;
};
/**
* Check if a plan is active
*/
isPlanActive(address: string): boolean;
/**
* Get days until plan expires
*/
getDaysUntilExpiry(address: string): number;
private initializeMockData;
}
declare class RateLimiter {
private cache;
private planType;
private paymentService;
constructor(planType?: PlanType, paymentService?: PaymentVerificationService);
checkLimit(userId: string): Promise<{
allowed: boolean;
retryAfter?: number;
}>;
checkCapsuleLimit(userId: string): Promise<{
allowed: boolean;
remaining: number;
}>;
incrementCapsuleCount(userId: string): Promise<void>;
checkStorageLimit(userId: string, sizeInMB: number): Promise<{
allowed: boolean;
remaining: number;
}>;
incrementStorage(userId: string, sizeInMB: number): Promise<void>;
getRemainingLimits(userId: string): RateLimits;
changePlan(newPlan: PlanType): void;
reset(userId: string): void;
getPlanInfo(userId: string): {
plan: PlanType;
daysRemaining: number;
isActive: boolean;
};
private getAddressForApiKey;
private getOrCreateState;
middleware(): (req: any, res: any, next: any) => Promise<void>;
}
declare const VERSION = "1.0.0";
export { AnalyticsService, CryptoService, IPFSService, LegacyChainClient, LegalDocumentService, Logger, PLAN_LIMITS, PaymentService, PlanType, RateLimiter, TimeCapsuleService, VERSION };
export type { AnalyticsData, ApiError, ApiResponse, CapsuleFilters, CapsuleMetadata, CreateCapsuleInput, CreateLegalDocumentInput, CreatePaymentInput, LegalDocument, LegalMetadata, PaginatedResponse, PaginationParams, PaymentCapsule, RateLimits, SDKConfig, SDKEvents, SelfDestructConfig, SignerInfo, TimeCapsule, WebhookConfig, WebhookPayload };