@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,398 @@
1
+ "use strict";
2
+ /**
3
+ * React Hooks for Varity Client
4
+ *
5
+ * Provides easy-to-use React hooks for blockchain interactions
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.useVarityClient = useVarityClient;
9
+ exports.useVarityWallet = useVarityWallet;
10
+ exports.useVarityBalance = useVarityBalance;
11
+ exports.useVarityContract = useVarityContract;
12
+ exports.useVarityAuth = useVarityAuth;
13
+ exports.useVarityStorage = useVarityStorage;
14
+ exports.useVarityChain = useVarityChain;
15
+ const react_1 = require("react");
16
+ const VarityClient_1 = require("../VarityClient");
17
+ /**
18
+ * useVarityClient - Create and manage Varity client instance
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * function App() {
23
+ * const client = useVarityClient({ chain: 'varity-l3' });
24
+ *
25
+ * return <div>Chain: {client.getChainName()}</div>;
26
+ * }
27
+ * ```
28
+ */
29
+ function useVarityClient(config) {
30
+ const clientRef = (0, react_1.useRef)(null);
31
+ if (!clientRef.current) {
32
+ clientRef.current = new VarityClient_1.VarityClient(config);
33
+ }
34
+ (0, react_1.useEffect)(() => {
35
+ return () => {
36
+ clientRef.current?.dispose();
37
+ };
38
+ }, []);
39
+ return clientRef.current;
40
+ }
41
+ /**
42
+ * useVarityWallet - Manage wallet connection and state
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * function WalletButton() {
47
+ * const { connect, disconnect, isConnected, account, balance } = useVarityWallet(client);
48
+ *
49
+ * if (isConnected) {
50
+ * return <button onClick={disconnect}>Disconnect ({balance})</button>;
51
+ * }
52
+ *
53
+ * return <button onClick={() => connect({ walletType: 'metamask' })}>Connect</button>;
54
+ * }
55
+ * ```
56
+ */
57
+ function useVarityWallet(client) {
58
+ const [isConnected, setIsConnected] = (0, react_1.useState)(false);
59
+ const [account, setAccount] = (0, react_1.useState)(null);
60
+ const [walletInfo, setWalletInfo] = (0, react_1.useState)(null);
61
+ const [isConnecting, setIsConnecting] = (0, react_1.useState)(false);
62
+ const [error, setError] = (0, react_1.useState)(null);
63
+ const connect = (0, react_1.useCallback)(async (options) => {
64
+ setIsConnecting(true);
65
+ setError(null);
66
+ try {
67
+ const connectedAccount = await client.wallet.connect(options);
68
+ setAccount(connectedAccount);
69
+ setIsConnected(true);
70
+ // Get wallet info
71
+ const info = await client.wallet.getWalletInfo();
72
+ setWalletInfo(info);
73
+ }
74
+ catch (err) {
75
+ setError(err);
76
+ throw err;
77
+ }
78
+ finally {
79
+ setIsConnecting(false);
80
+ }
81
+ }, [client]);
82
+ const disconnect = (0, react_1.useCallback)(() => {
83
+ client.wallet.disconnect();
84
+ setAccount(null);
85
+ setIsConnected(false);
86
+ setWalletInfo(null);
87
+ }, [client]);
88
+ const refreshBalance = (0, react_1.useCallback)(async () => {
89
+ if (isConnected) {
90
+ const info = await client.wallet.getWalletInfo();
91
+ setWalletInfo(info);
92
+ }
93
+ }, [client, isConnected]);
94
+ return {
95
+ connect,
96
+ disconnect,
97
+ isConnected,
98
+ isConnecting,
99
+ account,
100
+ walletInfo,
101
+ address: walletInfo?.address || null,
102
+ balance: walletInfo?.balanceFormatted || '0',
103
+ chainId: walletInfo?.chainId || null,
104
+ refreshBalance,
105
+ error,
106
+ };
107
+ }
108
+ /**
109
+ * useVarityBalance - Track wallet balance with auto-refresh
110
+ *
111
+ * @example
112
+ * ```typescript
113
+ * function BalanceDisplay() {
114
+ * const { balance, isLoading, refresh } = useVarityBalance(client);
115
+ *
116
+ * return (
117
+ * <div>
118
+ * Balance: {balance}
119
+ * <button onClick={refresh}>Refresh</button>
120
+ * </div>
121
+ * );
122
+ * }
123
+ * ```
124
+ */
125
+ function useVarityBalance(client, autoRefresh = true, refreshInterval = 10000) {
126
+ const [balance, setBalance] = (0, react_1.useState)('0');
127
+ const [isLoading, setIsLoading] = (0, react_1.useState)(false);
128
+ const [error, setError] = (0, react_1.useState)(null);
129
+ const fetchBalance = (0, react_1.useCallback)(async () => {
130
+ if (!client.wallet.isConnected()) {
131
+ setBalance('0');
132
+ return;
133
+ }
134
+ setIsLoading(true);
135
+ setError(null);
136
+ try {
137
+ const info = await client.wallet.getWalletInfo();
138
+ setBalance(info.balanceFormatted);
139
+ }
140
+ catch (err) {
141
+ setError(err);
142
+ }
143
+ finally {
144
+ setIsLoading(false);
145
+ }
146
+ }, [client]);
147
+ (0, react_1.useEffect)(() => {
148
+ fetchBalance();
149
+ if (autoRefresh) {
150
+ const interval = setInterval(fetchBalance, refreshInterval);
151
+ return () => clearInterval(interval);
152
+ }
153
+ }, [fetchBalance, autoRefresh, refreshInterval]);
154
+ return {
155
+ balance,
156
+ isLoading,
157
+ error,
158
+ refresh: fetchBalance,
159
+ };
160
+ }
161
+ /**
162
+ * useVarityContract - Interact with smart contracts
163
+ *
164
+ * @example
165
+ * ```typescript
166
+ * function TokenBalance() {
167
+ * const { read, write, isLoading } = useVarityContract(client, account);
168
+ *
169
+ * const balance = read({
170
+ * address: '0x...',
171
+ * abi: ERC20_ABI,
172
+ * functionName: 'balanceOf',
173
+ * args: ['0x...']
174
+ * });
175
+ *
176
+ * return <div>Balance: {balance}</div>;
177
+ * }
178
+ * ```
179
+ */
180
+ function useVarityContract(client, account) {
181
+ const [isLoading, setIsLoading] = (0, react_1.useState)(false);
182
+ const [error, setError] = (0, react_1.useState)(null);
183
+ const read = (0, react_1.useCallback)(async (options) => {
184
+ setIsLoading(true);
185
+ setError(null);
186
+ try {
187
+ const result = await client.contracts.read(options);
188
+ return result;
189
+ }
190
+ catch (err) {
191
+ setError(err);
192
+ throw err;
193
+ }
194
+ finally {
195
+ setIsLoading(false);
196
+ }
197
+ }, [client]);
198
+ const write = (0, react_1.useCallback)(async (options) => {
199
+ if (!account) {
200
+ throw new Error('No wallet connected');
201
+ }
202
+ setIsLoading(true);
203
+ setError(null);
204
+ try {
205
+ const result = await client.contracts.write(options, account);
206
+ return result;
207
+ }
208
+ catch (err) {
209
+ setError(err);
210
+ throw err;
211
+ }
212
+ finally {
213
+ setIsLoading(false);
214
+ }
215
+ }, [client, account]);
216
+ return {
217
+ read,
218
+ write,
219
+ isLoading,
220
+ error,
221
+ };
222
+ }
223
+ /**
224
+ * useVarityAuth - Manage SIWE authentication
225
+ *
226
+ * @example
227
+ * ```typescript
228
+ * function AuthButton() {
229
+ * const { signIn, signOut, isAuthenticated, session } = useVarityAuth(client, account);
230
+ *
231
+ * if (isAuthenticated) {
232
+ * return <button onClick={signOut}>Sign Out</button>;
233
+ * }
234
+ *
235
+ * return <button onClick={signIn}>Sign In with Ethereum</button>;
236
+ * }
237
+ * ```
238
+ */
239
+ function useVarityAuth(client, account) {
240
+ const [isAuthenticated, setIsAuthenticated] = (0, react_1.useState)(false);
241
+ const [session, setSession] = (0, react_1.useState)(null);
242
+ const [isLoading, setIsLoading] = (0, react_1.useState)(false);
243
+ const [error, setError] = (0, react_1.useState)(null);
244
+ const signIn = (0, react_1.useCallback)(async (statement) => {
245
+ if (!account) {
246
+ throw new Error('No wallet connected');
247
+ }
248
+ setIsLoading(true);
249
+ setError(null);
250
+ try {
251
+ // Generate SIWE message
252
+ const message = await client.auth.generateMessage({
253
+ address: account.address,
254
+ statement: statement || 'Sign in to Varity',
255
+ });
256
+ // Sign message
257
+ const result = await client.auth.signMessage(message, account);
258
+ // Create session
259
+ const newSession = await client.auth.createSession(result);
260
+ setSession(newSession);
261
+ setIsAuthenticated(true);
262
+ return newSession;
263
+ }
264
+ catch (err) {
265
+ setError(err);
266
+ throw err;
267
+ }
268
+ finally {
269
+ setIsLoading(false);
270
+ }
271
+ }, [client, account]);
272
+ const signOut = (0, react_1.useCallback)(() => {
273
+ if (account) {
274
+ client.auth.deleteSession(account.address);
275
+ }
276
+ setSession(null);
277
+ setIsAuthenticated(false);
278
+ }, [client, account]);
279
+ // Check for existing session on mount
280
+ (0, react_1.useEffect)(() => {
281
+ if (account) {
282
+ const existingSession = client.auth.getSession(account.address);
283
+ if (existingSession) {
284
+ setSession(existingSession);
285
+ setIsAuthenticated(true);
286
+ }
287
+ }
288
+ }, [client, account]);
289
+ return {
290
+ signIn,
291
+ signOut,
292
+ isAuthenticated,
293
+ session,
294
+ isLoading,
295
+ error,
296
+ };
297
+ }
298
+ /**
299
+ * useVarityStorage - Upload and download from IPFS
300
+ *
301
+ * @example
302
+ * ```typescript
303
+ * function FileUpload() {
304
+ * const { upload, isUploading, uploadProgress } = useVarityStorage(client);
305
+ *
306
+ * const handleUpload = async (file: File) => {
307
+ * const result = await upload(file);
308
+ * console.log('Uploaded to:', result.gateway);
309
+ * };
310
+ *
311
+ * return <input type="file" onChange={(e) => handleUpload(e.target.files[0])} />;
312
+ * }
313
+ * ```
314
+ */
315
+ function useVarityStorage(client) {
316
+ const [isUploading, setIsUploading] = (0, react_1.useState)(false);
317
+ const [uploadProgress, setUploadProgress] = (0, react_1.useState)(0);
318
+ const [error, setError] = (0, react_1.useState)(null);
319
+ const upload = (0, react_1.useCallback)(async (file, options) => {
320
+ setIsUploading(true);
321
+ setUploadProgress(0);
322
+ setError(null);
323
+ try {
324
+ const result = await client.storage.upload(file, {
325
+ ...options,
326
+ onProgress: (progress) => {
327
+ setUploadProgress(progress);
328
+ options?.onProgress?.(progress);
329
+ },
330
+ });
331
+ setUploadProgress(100);
332
+ return result;
333
+ }
334
+ catch (err) {
335
+ setError(err);
336
+ throw err;
337
+ }
338
+ finally {
339
+ setIsUploading(false);
340
+ }
341
+ }, [client]);
342
+ const download = (0, react_1.useCallback)(async (cid) => {
343
+ setError(null);
344
+ try {
345
+ const data = await client.storage.download(cid);
346
+ return data;
347
+ }
348
+ catch (err) {
349
+ setError(err);
350
+ throw err;
351
+ }
352
+ }, [client]);
353
+ const uploadJSON = (0, react_1.useCallback)(async (data, options) => {
354
+ setIsUploading(true);
355
+ setError(null);
356
+ try {
357
+ const result = await client.storage.uploadJSON(data, options);
358
+ return result;
359
+ }
360
+ catch (err) {
361
+ setError(err);
362
+ throw err;
363
+ }
364
+ finally {
365
+ setIsUploading(false);
366
+ }
367
+ }, [client]);
368
+ return {
369
+ upload,
370
+ download,
371
+ uploadJSON,
372
+ isUploading,
373
+ uploadProgress,
374
+ error,
375
+ };
376
+ }
377
+ /**
378
+ * useVarityChain - Monitor chain information
379
+ *
380
+ * @example
381
+ * ```typescript
382
+ * function ChainInfo() {
383
+ * const { chainId, chainName, isVarityL3 } = useVarityChain(client);
384
+ *
385
+ * return <div>Connected to: {chainName} (ID: {chainId})</div>;
386
+ * }
387
+ * ```
388
+ */
389
+ function useVarityChain(client) {
390
+ const config = (0, react_1.useMemo)(() => client.getConfig(), [client]);
391
+ return {
392
+ chainId: config.chainId,
393
+ chainName: config.chainName,
394
+ rpcUrl: config.rpcUrl,
395
+ nativeCurrency: config.nativeCurrency,
396
+ isVarityL3: config.isVarityL3,
397
+ };
398
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Storage Manager - Handle IPFS storage operations via Thirdweb
3
+ */
4
+ import type { ThirdwebClient } from 'thirdweb';
5
+ import type { StorageUploadOptions, StorageUploadResult, StorageDownloadOptions } from '../types';
6
+ /**
7
+ * StorageManager - Manage IPFS storage operations
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * // Upload file
12
+ * const result = await storageManager.upload(file);
13
+ * console.log('IPFS CID:', result.cid);
14
+ *
15
+ * // Download file
16
+ * const data = await storageManager.download(result.cid);
17
+ * ```
18
+ */
19
+ export declare class StorageManager {
20
+ private readonly client;
21
+ private readonly defaultGateway;
22
+ constructor(client: ThirdwebClient);
23
+ /**
24
+ * Upload file to IPFS
25
+ * @param file File to upload (File, Blob, or Buffer)
26
+ * @param options Upload options
27
+ * @returns Upload result with CID and URL
28
+ */
29
+ upload(file: File | Blob | Buffer | string, options?: StorageUploadOptions): Promise<StorageUploadResult>;
30
+ /**
31
+ * Upload multiple files to IPFS
32
+ * @param files Array of files to upload
33
+ * @param options Upload options
34
+ * @returns Array of upload results
35
+ */
36
+ uploadBatch(files: (File | Blob | Buffer | string)[], options?: StorageUploadOptions): Promise<StorageUploadResult[]>;
37
+ /**
38
+ * Upload JSON data to IPFS
39
+ * @param data JSON data to upload
40
+ * @param options Upload options
41
+ * @returns Upload result
42
+ */
43
+ uploadJSON(data: any, options?: StorageUploadOptions): Promise<StorageUploadResult>;
44
+ /**
45
+ * Download file from IPFS
46
+ * @param cid IPFS CID or full URI
47
+ * @param options Download options
48
+ * @returns Downloaded data
49
+ */
50
+ download(cid: string, options?: StorageDownloadOptions): Promise<any>;
51
+ /**
52
+ * Download JSON from IPFS
53
+ * @param cid IPFS CID or full URI
54
+ * @param options Download options
55
+ * @returns Parsed JSON data
56
+ */
57
+ downloadJSON(cid: string, options?: StorageDownloadOptions): Promise<any>;
58
+ /**
59
+ * Get IPFS gateway URL for CID
60
+ * @param cid IPFS CID
61
+ * @param gateway Custom gateway URL (optional)
62
+ * @returns Gateway URL
63
+ */
64
+ getGatewayUrl(cid: string, gateway?: string): string;
65
+ /**
66
+ * Get IPFS URI from CID
67
+ * @param cid IPFS CID
68
+ * @returns IPFS URI
69
+ */
70
+ getIPFSUri(cid: string): string;
71
+ /**
72
+ * Upload metadata for NFT
73
+ * @param metadata NFT metadata object
74
+ * @returns Upload result with metadata URI
75
+ */
76
+ uploadNFTMetadata(metadata: {
77
+ name: string;
78
+ description: string;
79
+ image: string;
80
+ attributes?: Array<{
81
+ trait_type: string;
82
+ value: any;
83
+ }>;
84
+ [key: string]: any;
85
+ }): Promise<StorageUploadResult>;
86
+ /**
87
+ * Upload directory to IPFS
88
+ * @param files Array of files with names
89
+ * @returns Upload result with directory CID
90
+ */
91
+ uploadDirectory(files: Array<{
92
+ name: string;
93
+ content: File | Blob | Buffer | string;
94
+ }>): Promise<StorageUploadResult>;
95
+ /**
96
+ * Check if CID is valid
97
+ * @param cid CID to validate
98
+ * @returns True if valid
99
+ */
100
+ isValidCID(cid: string): boolean;
101
+ /**
102
+ * Pin CID to ensure persistence
103
+ * Note: This requires a pinning service integration
104
+ * @param cid CID to pin
105
+ */
106
+ pin(cid: string): Promise<void>;
107
+ /**
108
+ * Unpin CID
109
+ * Note: This requires a pinning service integration
110
+ * @param cid CID to unpin
111
+ */
112
+ unpin(cid: string): Promise<void>;
113
+ /**
114
+ * Get storage statistics
115
+ * @returns Storage statistics
116
+ */
117
+ getStats(): Promise<{
118
+ totalUploads: number;
119
+ totalSize: number;
120
+ }>;
121
+ }
122
+ export default StorageManager;