@varity-labs/client-js 2.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,296 @@
1
+ "use strict";
2
+ /**
3
+ * Storage Manager - Handle IPFS storage operations via Thirdweb
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.StorageManager = void 0;
7
+ const storage_1 = require("thirdweb/storage");
8
+ const types_1 = require("../types");
9
+ /**
10
+ * StorageManager - Manage IPFS storage operations
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * // Upload file
15
+ * const result = await storageManager.upload(file);
16
+ * console.log('IPFS CID:', result.cid);
17
+ *
18
+ * // Download file
19
+ * const data = await storageManager.download(result.cid);
20
+ * ```
21
+ */
22
+ class StorageManager {
23
+ constructor(client) {
24
+ this.client = client;
25
+ this.defaultGateway = 'https://ipfs.io/ipfs/';
26
+ }
27
+ /**
28
+ * Upload file to IPFS
29
+ * @param file File to upload (File, Blob, or Buffer)
30
+ * @param options Upload options
31
+ * @returns Upload result with CID and URL
32
+ */
33
+ async upload(file, options = {}) {
34
+ try {
35
+ let uploadData;
36
+ // Handle different file types
37
+ if (typeof file === 'string') {
38
+ // String data
39
+ uploadData = new Blob([file], { type: 'text/plain' });
40
+ }
41
+ else if (Buffer.isBuffer(file)) {
42
+ // Node.js Buffer - convert to Uint8Array for Blob compatibility
43
+ uploadData = new Blob([new Uint8Array(file)]);
44
+ }
45
+ else {
46
+ // File or Blob
47
+ uploadData = file;
48
+ }
49
+ // Upload to IPFS via Thirdweb
50
+ const uri = await (0, storage_1.upload)({
51
+ client: this.client,
52
+ files: [uploadData],
53
+ });
54
+ // Extract CID from URI (format: ipfs://CID)
55
+ const cid = uri.replace('ipfs://', '');
56
+ return {
57
+ cid,
58
+ url: uri,
59
+ gateway: `${this.defaultGateway}${cid}`,
60
+ };
61
+ }
62
+ catch (error) {
63
+ throw new types_1.StorageError(`Failed to upload to IPFS: ${error.message}`, { error });
64
+ }
65
+ }
66
+ /**
67
+ * Upload multiple files to IPFS
68
+ * @param files Array of files to upload
69
+ * @param options Upload options
70
+ * @returns Array of upload results
71
+ */
72
+ async uploadBatch(files, options = {}) {
73
+ try {
74
+ const uploadData = files.map((file) => {
75
+ if (typeof file === 'string') {
76
+ // Convert string to File object
77
+ return new File([file], 'file.txt', { type: 'text/plain' });
78
+ }
79
+ else if (Buffer.isBuffer(file)) {
80
+ // Convert Buffer to File object
81
+ return new File([new Uint8Array(file)], 'file.bin', { type: 'application/octet-stream' });
82
+ }
83
+ else {
84
+ return file;
85
+ }
86
+ });
87
+ // Upload all files
88
+ const uris = await (0, storage_1.upload)({
89
+ client: this.client,
90
+ files: uploadData,
91
+ });
92
+ // Convert URI to CID format
93
+ const results = [];
94
+ const uriArray = Array.isArray(uris) ? uris : [uris];
95
+ for (const uri of uriArray) {
96
+ const cid = uri.replace('ipfs://', '');
97
+ results.push({
98
+ cid,
99
+ url: uri,
100
+ gateway: `${this.defaultGateway}${cid}`,
101
+ });
102
+ }
103
+ return results;
104
+ }
105
+ catch (error) {
106
+ throw new types_1.StorageError(`Failed to batch upload to IPFS: ${error.message}`, { error });
107
+ }
108
+ }
109
+ /**
110
+ * Upload JSON data to IPFS
111
+ * @param data JSON data to upload
112
+ * @param options Upload options
113
+ * @returns Upload result
114
+ */
115
+ async uploadJSON(data, options = {}) {
116
+ try {
117
+ const jsonString = JSON.stringify(data, null, 2);
118
+ const blob = new Blob([jsonString], { type: 'application/json' });
119
+ return await this.upload(blob, options);
120
+ }
121
+ catch (error) {
122
+ throw new types_1.StorageError(`Failed to upload JSON to IPFS: ${error.message}`, { error });
123
+ }
124
+ }
125
+ /**
126
+ * Download file from IPFS
127
+ * @param cid IPFS CID or full URI
128
+ * @param options Download options
129
+ * @returns Downloaded data
130
+ */
131
+ async download(cid, options = {}) {
132
+ try {
133
+ // Normalize CID (remove ipfs:// prefix if present)
134
+ const normalizedCid = cid.replace('ipfs://', '');
135
+ const uri = `ipfs://${normalizedCid}`;
136
+ // Download from IPFS via Thirdweb
137
+ const data = await (0, storage_1.download)({
138
+ client: this.client,
139
+ uri,
140
+ });
141
+ return data;
142
+ }
143
+ catch (error) {
144
+ throw new types_1.StorageError(`Failed to download from IPFS: ${error.message}`, { cid, error });
145
+ }
146
+ }
147
+ /**
148
+ * Download JSON from IPFS
149
+ * @param cid IPFS CID or full URI
150
+ * @param options Download options
151
+ * @returns Parsed JSON data
152
+ */
153
+ async downloadJSON(cid, options = {}) {
154
+ try {
155
+ const data = await this.download(cid, options);
156
+ // If data is already parsed JSON, return it
157
+ if (typeof data === 'object') {
158
+ return data;
159
+ }
160
+ // If data is a Response object
161
+ if (data instanceof Response) {
162
+ return await data.json();
163
+ }
164
+ // If data is a string, parse it
165
+ if (typeof data === 'string') {
166
+ return JSON.parse(data);
167
+ }
168
+ // If data is a Blob, read and parse it
169
+ if (data instanceof Blob) {
170
+ const text = await data.text();
171
+ return JSON.parse(text);
172
+ }
173
+ return data;
174
+ }
175
+ catch (error) {
176
+ throw new types_1.StorageError(`Failed to download JSON from IPFS: ${error.message}`, { cid, error });
177
+ }
178
+ }
179
+ /**
180
+ * Get IPFS gateway URL for CID
181
+ * @param cid IPFS CID
182
+ * @param gateway Custom gateway URL (optional)
183
+ * @returns Gateway URL
184
+ */
185
+ getGatewayUrl(cid, gateway) {
186
+ const normalizedCid = cid.replace('ipfs://', '');
187
+ const baseGateway = gateway || this.defaultGateway;
188
+ return `${baseGateway}${normalizedCid}`;
189
+ }
190
+ /**
191
+ * Get IPFS URI from CID
192
+ * @param cid IPFS CID
193
+ * @returns IPFS URI
194
+ */
195
+ getIPFSUri(cid) {
196
+ const normalizedCid = cid.replace('ipfs://', '');
197
+ return `ipfs://${normalizedCid}`;
198
+ }
199
+ /**
200
+ * Upload metadata for NFT
201
+ * @param metadata NFT metadata object
202
+ * @returns Upload result with metadata URI
203
+ */
204
+ async uploadNFTMetadata(metadata) {
205
+ try {
206
+ return await this.uploadJSON(metadata);
207
+ }
208
+ catch (error) {
209
+ throw new types_1.StorageError(`Failed to upload NFT metadata: ${error.message}`, { error });
210
+ }
211
+ }
212
+ /**
213
+ * Upload directory to IPFS
214
+ * @param files Array of files with names
215
+ * @returns Upload result with directory CID
216
+ */
217
+ async uploadDirectory(files) {
218
+ try {
219
+ const uploadFiles = files.map((file) => {
220
+ let content;
221
+ if (typeof file.content === 'string') {
222
+ content = new Blob([file.content], { type: 'text/plain' });
223
+ }
224
+ else if (Buffer.isBuffer(file.content)) {
225
+ content = new Blob([new Uint8Array(file.content)]);
226
+ }
227
+ else {
228
+ content = file.content;
229
+ }
230
+ // Add name property to the blob
231
+ return new File([content], file.name);
232
+ });
233
+ const uris = await (0, storage_1.upload)({
234
+ client: this.client,
235
+ files: uploadFiles,
236
+ });
237
+ // upload returns string or string[], handle both cases
238
+ const uri = Array.isArray(uris) ? uris[0] : uris;
239
+ const cid = uri.replace('ipfs://', '');
240
+ return {
241
+ cid,
242
+ url: uri,
243
+ gateway: `${this.defaultGateway}${cid}`,
244
+ };
245
+ }
246
+ catch (error) {
247
+ throw new types_1.StorageError(`Failed to upload directory to IPFS: ${error.message}`, { error });
248
+ }
249
+ }
250
+ /**
251
+ * Check if CID is valid
252
+ * @param cid CID to validate
253
+ * @returns True if valid
254
+ */
255
+ isValidCID(cid) {
256
+ const normalizedCid = cid.replace('ipfs://', '');
257
+ // Basic CID validation (checks for valid characters and length)
258
+ // CIDv0: Qm followed by 44 base58 characters
259
+ // CIDv1: starts with 'b' or 'z' followed by base32/base58 characters
260
+ const cidv0Regex = /^Qm[1-9A-HJ-NP-Za-km-z]{44}$/;
261
+ const cidv1Regex = /^[bz][a-z2-7]{58,}$/;
262
+ return cidv0Regex.test(normalizedCid) || cidv1Regex.test(normalizedCid);
263
+ }
264
+ /**
265
+ * Pin CID to ensure persistence
266
+ * Note: This requires a pinning service integration
267
+ * @param cid CID to pin
268
+ */
269
+ async pin(cid) {
270
+ // Thirdweb storage handles pinning automatically
271
+ // This is a placeholder for custom pinning service integration
272
+ console.log(`CID ${cid} is automatically pinned by Thirdweb`);
273
+ }
274
+ /**
275
+ * Unpin CID
276
+ * Note: This requires a pinning service integration
277
+ * @param cid CID to unpin
278
+ */
279
+ async unpin(cid) {
280
+ // Placeholder for custom pinning service integration
281
+ console.log(`Unpinning CID ${cid}`);
282
+ }
283
+ /**
284
+ * Get storage statistics
285
+ * @returns Storage statistics
286
+ */
287
+ async getStats() {
288
+ // Placeholder - implement actual statistics tracking
289
+ return {
290
+ totalUploads: 0,
291
+ totalSize: 0,
292
+ };
293
+ }
294
+ }
295
+ exports.StorageManager = StorageManager;
296
+ exports.default = StorageManager;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Type definitions for Varity Client
3
+ */
4
+ import type { Chain } from 'thirdweb';
5
+ export interface ChainConfig {
6
+ chainId: number;
7
+ name: string;
8
+ rpcUrl: string;
9
+ nativeCurrency: {
10
+ name: string;
11
+ symbol: string;
12
+ decimals: number;
13
+ };
14
+ blockExplorer?: string;
15
+ }
16
+ export interface VarityClientConfig {
17
+ clientId?: string;
18
+ secretKey?: string;
19
+ chain?: 'varity-l3' | 'arbitrum-sepolia' | 'arbitrum-one' | Chain;
20
+ customChain?: ChainConfig;
21
+ }
22
+ export interface WalletConnectionOptions {
23
+ walletType: 'metamask' | 'walletconnect' | 'coinbase' | 'injected' | 'embedded';
24
+ walletConnectProjectId?: string;
25
+ }
26
+ export interface WalletInfo {
27
+ address: string;
28
+ balance: string;
29
+ balanceFormatted: string;
30
+ chainId: number;
31
+ }
32
+ export interface ContractDeployOptions {
33
+ abi: any[];
34
+ bytecode: string;
35
+ constructorArgs?: any[];
36
+ }
37
+ export interface ContractReadOptions {
38
+ address: string;
39
+ abi: any[];
40
+ functionName: string;
41
+ args?: any[];
42
+ }
43
+ export interface ContractWriteOptions {
44
+ address: string;
45
+ abi: any[];
46
+ functionName: string;
47
+ args?: any[];
48
+ value?: bigint;
49
+ }
50
+ export interface ContractEventFilter {
51
+ address: string;
52
+ abi: any[];
53
+ eventName: string;
54
+ fromBlock?: number;
55
+ toBlock?: number;
56
+ }
57
+ export interface ContractEvent {
58
+ eventName: string;
59
+ args: any;
60
+ blockNumber: number;
61
+ transactionHash: string;
62
+ logIndex: number;
63
+ }
64
+ export interface SIWEMessage {
65
+ domain: string;
66
+ address: string;
67
+ statement: string;
68
+ uri: string;
69
+ version: string;
70
+ chainId: number;
71
+ nonce: string;
72
+ issuedAt: string;
73
+ expirationTime?: string;
74
+ notBefore?: string;
75
+ requestId?: string;
76
+ resources?: string[];
77
+ }
78
+ export interface SIWESignatureResult {
79
+ message: string;
80
+ signature: string;
81
+ }
82
+ export interface SIWEVerifyResult {
83
+ success: boolean;
84
+ address?: string;
85
+ error?: string;
86
+ }
87
+ export interface SIWESession {
88
+ address: string;
89
+ chainId: number;
90
+ issuedAt: Date;
91
+ expiresAt: Date;
92
+ signature: string;
93
+ }
94
+ export interface StorageUploadOptions {
95
+ metadata?: Record<string, any>;
96
+ onProgress?: (progress: number) => void;
97
+ }
98
+ export interface StorageUploadResult {
99
+ cid: string;
100
+ url: string;
101
+ gateway: string;
102
+ }
103
+ export interface StorageDownloadOptions {
104
+ gateway?: string;
105
+ }
106
+ export interface TransactionOptions {
107
+ value?: bigint;
108
+ gasLimit?: bigint;
109
+ gasPrice?: bigint;
110
+ maxFeePerGas?: bigint;
111
+ maxPriorityFeePerGas?: bigint;
112
+ }
113
+ export interface TransactionResult {
114
+ transactionHash: string;
115
+ blockNumber: number;
116
+ from: string;
117
+ to?: string;
118
+ gasUsed: bigint;
119
+ status: 'success' | 'failed';
120
+ }
121
+ export interface TransactionReceipt {
122
+ transactionHash: string;
123
+ blockNumber: number;
124
+ blockHash: string;
125
+ from: string;
126
+ to?: string;
127
+ gasUsed: bigint;
128
+ cumulativeGasUsed: bigint;
129
+ contractAddress?: string;
130
+ logs: any[];
131
+ status: 'success' | 'failed';
132
+ }
133
+ export interface USDCAmount {
134
+ raw: bigint;
135
+ formatted: string;
136
+ decimals: number;
137
+ }
138
+ export declare class VarityError extends Error {
139
+ code: string;
140
+ details?: any | undefined;
141
+ constructor(message: string, code: string, details?: any | undefined);
142
+ }
143
+ export declare class WalletError extends VarityError {
144
+ constructor(message: string, details?: any);
145
+ }
146
+ export declare class ContractError extends VarityError {
147
+ constructor(message: string, details?: any);
148
+ }
149
+ export declare class TransactionError extends VarityError {
150
+ constructor(message: string, details?: any);
151
+ }
152
+ export declare class StorageError extends VarityError {
153
+ constructor(message: string, details?: any);
154
+ }
155
+ export declare class AuthenticationError extends VarityError {
156
+ constructor(message: string, details?: any);
157
+ }
package/dist/types.js ADDED
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ /**
3
+ * Type definitions for Varity Client
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AuthenticationError = exports.StorageError = exports.TransactionError = exports.ContractError = exports.WalletError = exports.VarityError = void 0;
7
+ // Error types
8
+ class VarityError extends Error {
9
+ constructor(message, code, details) {
10
+ super(message);
11
+ this.code = code;
12
+ this.details = details;
13
+ this.name = 'VarityError';
14
+ }
15
+ }
16
+ exports.VarityError = VarityError;
17
+ class WalletError extends VarityError {
18
+ constructor(message, details) {
19
+ super(message, 'WALLET_ERROR', details);
20
+ this.name = 'WalletError';
21
+ }
22
+ }
23
+ exports.WalletError = WalletError;
24
+ class ContractError extends VarityError {
25
+ constructor(message, details) {
26
+ super(message, 'CONTRACT_ERROR', details);
27
+ this.name = 'ContractError';
28
+ }
29
+ }
30
+ exports.ContractError = ContractError;
31
+ class TransactionError extends VarityError {
32
+ constructor(message, details) {
33
+ super(message, 'TRANSACTION_ERROR', details);
34
+ this.name = 'TransactionError';
35
+ }
36
+ }
37
+ exports.TransactionError = TransactionError;
38
+ class StorageError extends VarityError {
39
+ constructor(message, details) {
40
+ super(message, 'STORAGE_ERROR', details);
41
+ this.name = 'StorageError';
42
+ }
43
+ }
44
+ exports.StorageError = StorageError;
45
+ class AuthenticationError extends VarityError {
46
+ constructor(message, details) {
47
+ super(message, 'AUTHENTICATION_ERROR', details);
48
+ this.name = 'AuthenticationError';
49
+ }
50
+ }
51
+ exports.AuthenticationError = AuthenticationError;
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Utility functions for formatting addresses, amounts, and other data
3
+ */
4
+ import type { USDCAmount } from '../types';
5
+ export declare const USDC_DECIMALS = 6;
6
+ export declare const USDC_MULTIPLIER: bigint;
7
+ /**
8
+ * Format USDC amount from raw value (6 decimals)
9
+ * @param amount Raw USDC amount in smallest unit
10
+ * @returns Formatted USDC string
11
+ * @example
12
+ * formatUSDC(1000000n) // "1.000000"
13
+ * formatUSDC(1500000n) // "1.500000"
14
+ */
15
+ export declare function formatUSDC(amount: bigint): string;
16
+ /**
17
+ * Parse USDC amount from string to raw value
18
+ * @param amount USDC amount as string (e.g., "1.5", "10", "0.000001")
19
+ * @returns Raw USDC amount in smallest unit
20
+ * @example
21
+ * parseUSDC("1.5") // 1500000n
22
+ * parseUSDC("10") // 10000000n
23
+ */
24
+ export declare function parseUSDC(amount: string): bigint;
25
+ /**
26
+ * Get USDC amount with both raw and formatted values
27
+ * @param amount Raw USDC amount or string
28
+ * @returns USDCAmount object
29
+ */
30
+ export declare function getUSDCAmount(amount: bigint | string): USDCAmount;
31
+ /**
32
+ * Validate Ethereum address
33
+ * @param address Address to validate
34
+ * @returns True if valid
35
+ */
36
+ export declare function isValidAddress(address: string): boolean;
37
+ /**
38
+ * Format Ethereum address (checksum)
39
+ * @param address Address to format
40
+ * @returns Checksummed address
41
+ */
42
+ export declare function formatAddress(address: string): string;
43
+ /**
44
+ * Shorten address for display
45
+ * @param address Full address
46
+ * @param chars Number of characters to show on each side
47
+ * @returns Shortened address
48
+ * @example
49
+ * shortenAddress("0x1234567890123456789012345678901234567890") // "0x1234...7890"
50
+ */
51
+ export declare function shortenAddress(address: string, chars?: number): string;
52
+ /**
53
+ * Format transaction hash for display
54
+ * @param hash Transaction hash
55
+ * @param chars Number of characters to show on each side
56
+ * @returns Shortened hash
57
+ */
58
+ export declare function shortenTxHash(hash: string, chars?: number): string;
59
+ /**
60
+ * Convert Wei to Ether
61
+ * @param wei Amount in Wei
62
+ * @returns Amount in Ether as string
63
+ */
64
+ export declare function formatEther(wei: bigint): string;
65
+ /**
66
+ * Parse Ether to Wei
67
+ * @param ether Amount in Ether as string
68
+ * @returns Amount in Wei
69
+ */
70
+ export declare function parseEther(ether: string): bigint;
71
+ /**
72
+ * Get chain name from chain ID
73
+ * @param chainId Chain ID
74
+ * @returns Chain name
75
+ */
76
+ export declare function getChainName(chainId: number): string;
77
+ /**
78
+ * Get block explorer URL
79
+ * @param chainId Chain ID
80
+ * @returns Block explorer URL
81
+ */
82
+ export declare function getBlockExplorerUrl(chainId: number): string;
83
+ /**
84
+ * Get transaction URL in block explorer
85
+ * @param chainId Chain ID
86
+ * @param txHash Transaction hash
87
+ * @returns Transaction URL
88
+ */
89
+ export declare function getTxUrl(chainId: number, txHash: string): string;
90
+ /**
91
+ * Get address URL in block explorer
92
+ * @param chainId Chain ID
93
+ * @param address Address
94
+ * @returns Address URL
95
+ */
96
+ export declare function getAddressUrl(chainId: number, address: string): string;
97
+ /**
98
+ * Format timestamp to date string
99
+ * @param timestamp Unix timestamp in seconds
100
+ * @returns Formatted date string
101
+ */
102
+ export declare function formatTimestamp(timestamp: number): string;
103
+ /**
104
+ * Format gas amount for display
105
+ * @param gas Gas amount in wei
106
+ * @returns Formatted gas string
107
+ */
108
+ export declare function formatGas(gas: bigint): string;
109
+ /**
110
+ * Calculate percentage
111
+ * @param value Current value
112
+ * @param total Total value
113
+ * @param decimals Number of decimal places
114
+ * @returns Percentage string
115
+ */
116
+ export declare function formatPercentage(value: number, total: number, decimals?: number): string;
117
+ /**
118
+ * Format large numbers with K, M, B suffixes
119
+ * @param num Number to format
120
+ * @param decimals Number of decimal places
121
+ * @returns Formatted number string
122
+ */
123
+ export declare function formatNumber(num: number, decimals?: number): string;