@explorins/pers-sdk-react-native 1.5.35 → 1.5.36

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.
package/README.md CHANGED
@@ -51,19 +51,12 @@ npm install react-native-url-polyfill
51
51
 
52
52
  ## Critical Setup Requirement: Passkeys
53
53
 
54
- To enable Passkey authentication (WebAuthn) on iOS and Android, you **must** register your app's bundle information with the PERS backend.
54
+ To enable Passkey authentication (WebAuthn) on iOS and Android, you **must** complete the setup in **[REACT_NATIVE_PASSKEY_SETUP.md](./REACT_NATIVE_PASSKEY_SETUP.md)**.
55
55
 
56
- **Please send the following information to the PERS Team (support@explorins.com):**
57
-
58
- 1. **iOS Bundle Identifier**: e.g., `com.yourcompany.app`
59
- 2. **Apple Team ID**: Your 10-character Apple Team ID (e.g., `R553XYJPW7`)
60
- 3. **Android Package Name**: e.g., `com.yourcompany.app`
61
- 4. **Android SHA-256 Certificate Fingerprint**:
62
- * **Development**: The fingerprint from your local keystore or Expo development build.
63
- * **Production**: The fingerprint from your Google Play Console signing key.
64
-
65
- **Why is this required?**
66
- The PERS Signer server must host an `apple-app-site-association` file (for iOS) and an `assetlinks.json` file (for Android) that explicitly trusts your application. Without this, the operating system will reject Passkey creation requests.
56
+ This includes:
57
+ - Registering your app with the PERS backend (required for OS trust)
58
+ - Native configuration (Info.plist, AndroidManifest.xml)
59
+ - Expo/development build setup
67
60
 
68
61
  ## Quick Start
69
62
 
@@ -312,7 +305,11 @@ const {
312
305
  resolveIPFSUrl,
313
306
  fetchAndProcessMetadata,
314
307
  getChainDataById,
315
- getExplorerUrl
308
+ getExplorerUrl,
309
+ // Helper methods for token collections
310
+ extractTokenIds, // Extract tokenIds from TokenDTO metadata
311
+ getAccountOwnedTokensFromContract, // Recommended: Get owned tokens automatically
312
+ buildCollectionRequest // Build request for getTokenCollection
316
313
  } = useWeb3();
317
314
 
318
315
  // User status & achievements
@@ -336,6 +333,69 @@ const {
336
333
  } = useDonations();
337
334
  ```
338
335
 
336
+ ## Token Collection Helper Methods
337
+
338
+ The `useWeb3` hook includes helper methods for querying token balances from any blockchain address. These work with **all token standards** (ERC-20, ERC-721, ERC-1155).
339
+
340
+ ### Recommended: getAccountOwnedTokensFromContract
341
+
342
+ A unified API to get all tokens owned by any blockchain address:
343
+
344
+ ```typescript
345
+ import { useWeb3, useTokens, usePersSDK } from '@explorins/pers-sdk-react-native';
346
+
347
+ function RewardTokensScreen() {
348
+ const { user } = usePersSDK();
349
+ const { getRewardTokens } = useTokens();
350
+ const { getAccountOwnedTokensFromContract } = useWeb3();
351
+
352
+ const loadUserRewards = async () => {
353
+ const walletAddress = user?.wallets?.[0]?.address;
354
+ if (!walletAddress) return;
355
+
356
+ const rewardTokens = await getRewardTokens();
357
+
358
+ for (const token of rewardTokens) {
359
+ // Works with ERC-20, ERC-721, and ERC-1155 automatically
360
+ const result = await getAccountOwnedTokensFromContract(walletAddress, token);
361
+
362
+ console.log(`Token: ${token.symbol}`);
363
+ console.log(`Owned: ${result.totalOwned}`);
364
+
365
+ result.ownedTokens.forEach(owned => {
366
+ console.log(` - ${owned.metadata?.name}: ${owned.balance}`);
367
+ });
368
+ }
369
+ };
370
+
371
+ return (
372
+ <TouchableOpacity onPress={loadUserRewards}>
373
+ <Text>Load My Rewards</Text>
374
+ </TouchableOpacity>
375
+ );
376
+ }
377
+ ```
378
+
379
+ ### How It Handles Each Token Standard
380
+
381
+ | Token Type | What It Does |
382
+ |------------|--------------|
383
+ | **ERC-20** | Returns balance for fungible tokens |
384
+ | **ERC-721** | Enumerates all owned NFTs |
385
+ | **ERC-1155** | Extracts tokenIds from metadata, queries balances |
386
+
387
+ The helper abstracts away the complexity - especially for ERC-1155 which requires specific `tokenIds` that the helper extracts from `token.metadata[].tokenMetadataIncrementalId`.
388
+
389
+ ### Return Type
390
+
391
+ ```typescript
392
+ interface AccountOwnedTokensResult {
393
+ token: TokenDTO; // The token definition
394
+ ownedTokens: TokenBalance[]; // Tokens with balance > 0
395
+ totalOwned: number; // Count of owned tokens
396
+ }
397
+ ```
398
+
339
399
  ## EVM Blockchain Transaction Signing
340
400
 
341
401
  The `useTransactionSigner` hook provides secure EVM blockchain transaction signing:
@@ -15,5 +15,5 @@ export { useAnalytics } from './useAnalytics';
15
15
  export { useDonations } from './useDonations';
16
16
  export type { RawUserData } from './useAuth';
17
17
  export type { TransactionSignerHook, SubmissionResult, AuthenticatedUser, TransactionSigningResult, StatusUpdateData, OnStatusUpdateFn, SigningStatus as SigningStatusType } from './useTransactionSigner';
18
- export type { UserOwnedTokensResult, Web3Hook } from './useWeb3';
18
+ export type { AccountOwnedTokensResult, Web3Hook } from './useWeb3';
19
19
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,gB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,qBAAqB,EACrB,gBAAgB,EAChB,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,gBAAgB,EAChB,aAAa,IAAI,iBAAiB,EACnC,MAAM,wBAAwB,CAAC;AAChC,YAAY,EAAE,wBAAwB,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC"}
@@ -1,17 +1,8 @@
1
1
  import type { TokenBalance, TokenBalanceRequest, TokenCollectionRequest, TokenCollection, TokenMetadata } from '@explorins/pers-sdk/web3';
2
2
  import type { ChainData } from '@explorins/pers-sdk/web3-chain';
3
3
  import type { TokenDTO } from '@explorins/pers-shared';
4
- /**
5
- * Result of getting user's owned tokens from a contract
6
- */
7
- export interface UserOwnedTokensResult {
8
- /** The token definition (contains contract info, ABI, metadata definitions) */
9
- token: TokenDTO;
10
- /** Array of token balances the user owns (filtered to hasBalance: true) */
11
- ownedTokens: readonly TokenBalance[];
12
- /** Total count of owned tokens */
13
- totalOwned: number;
14
- }
4
+ import type { AccountOwnedTokensResult } from '@explorins/pers-sdk';
5
+ export type { AccountOwnedTokensResult } from '@explorins/pers-sdk';
15
6
  /**
16
7
  * React hook for Web3 operations in the PERS SDK
17
8
  *
@@ -21,48 +12,9 @@ export interface UserOwnedTokensResult {
21
12
  *
22
13
  * Note: Wallet addresses should be obtained from `user.wallets` via `usePersSDK()`.
23
14
  *
24
- * ## ERC-1155 Token Handling
25
- *
26
- * **IMPORTANT**: ERC-1155 tokens require specific `tokenIds` to query balances.
27
- * Unlike ERC-721, you cannot enumerate owned tokens - you must know which tokenId to check.
28
- *
29
- * The tokenIds come from `TokenDTO.metadata[].tokenMetadataIncrementalId`.
30
- *
31
- * ### Option 1: Use the helper method (Recommended)
32
- * ```typescript
33
- * const { getUserOwnedTokensFromContract } = useWeb3();
34
- * const { getRewardTokens } = useTokens();
35
- *
36
- * const rewardTokens = await getRewardTokens();
37
- * const result = await getUserOwnedTokensFromContract(walletAddress, rewardTokens[0]);
38
- * console.log('Owned rewards:', result.ownedTokens);
39
- * ```
40
- *
41
- * ### Option 2: Manual tokenIds extraction
42
- * ```typescript
43
- * const { getTokenCollection, extractTokenIds } = useWeb3();
44
- * const { getRewardTokens } = useTokens();
45
- *
46
- * const rewardTokens = await getRewardTokens();
47
- * const rewardToken = rewardTokens[0];
48
- *
49
- * // Extract tokenIds for ERC-1155
50
- * const tokenIds = extractTokenIds(rewardToken);
51
- *
52
- * const collection = await getTokenCollection({
53
- * accountAddress: walletAddress,
54
- * contractAddress: rewardToken.contractAddress,
55
- * abi: rewardToken.abi,
56
- * chainId: rewardToken.chainId,
57
- * tokenIds: tokenIds // Required for ERC-1155!
58
- * });
59
- *
60
- * const ownedTokens = collection.tokens.filter(t => t.hasBalance);
61
- * ```
62
- *
63
15
  * @returns Web3 hook with methods for blockchain operations
64
16
  *
65
- * @example Basic Usage
17
+ * @example
66
18
  * ```typescript
67
19
  * function Web3Component() {
68
20
  * const { user } = usePersSDK();
@@ -110,8 +62,8 @@ export declare const useWeb3: () => {
110
62
  getChainDataById: (chainId: number) => Promise<ChainData | null>;
111
63
  getExplorerUrl: (chainId: number, address: string, type: 'address' | 'tx') => Promise<string>;
112
64
  extractTokenIds: (token: TokenDTO) => string[] | undefined;
113
- getUserOwnedTokensFromContract: (walletAddress: string, token: TokenDTO, maxTokens?: number) => Promise<UserOwnedTokensResult>;
114
- buildCollectionRequest: (walletAddress: string, token: TokenDTO, maxTokens?: number) => TokenCollectionRequest;
65
+ getAccountOwnedTokensFromContract: (accountAddress: string, token: TokenDTO, maxTokens?: number) => Promise<AccountOwnedTokensResult>;
66
+ buildCollectionRequest: (accountAddress: string, token: TokenDTO, maxTokens?: number) => TokenCollectionRequest;
115
67
  isAvailable: boolean;
116
68
  };
117
69
  export type Web3Hook = ReturnType<typeof useWeb3>;
@@ -1 +1 @@
1
- {"version":3,"file":"useWeb3.d.ts","sourceRoot":"","sources":["../../src/hooks/useWeb3.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,YAAY,EACZ,mBAAmB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"AAEA,OAAO,KAAK,EACV,YAAY,EACZ,mBAAmB,EACnB,sBAAsB,EACtB,eAAe,EACf,aAAa,EACd,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gCAAgC,CAAC;AAChE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAGpE,YAAY,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAEpE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,eAAO,MAAM,OAAO;+BA0BkC,mBAAmB,KAAG,QAAQ,YAAY,CAAC;gCAiC1C,mBAAmB,KAAG,QAAQ,aAAa,GAAG,IAAI,CAAC;kCAcjD,sBAAsB,KAAG,QAAQ,eAAe,CAAC;0BAczD,MAAM,WAAW,MAAM,KAAG,QAAQ,MAAM,CAAC;wCAc3B,MAAM,WAAW,MAAM,KAAG,QAAQ,aAAa,GAAG,IAAI,CAAC;gCAc/D,MAAM,KAAG,QAAQ,SAAS,GAAG,IAAI,CAAC;8BAcpC,MAAM,WAAW,MAAM,QAAQ,SAAS,GAAG,IAAI,KAAG,QAAQ,MAAM,CAAC;6BAiCxE,QAAQ,KAAG,MAAM,EAAE,GAAG,SAAS;wDAuCzD,MAAM,SACf,QAAQ,cACJ,MAAM,KAChB,QAAQ,wBAAwB,CAAC;6CAqBlB,MAAM,SACf,QAAQ,cACJ,MAAM,KAChB,sBAAsB;;CAqB1B,CAAC;AAEF,MAAM,MAAM,QAAQ,GAAG,UAAU,CAAC,OAAO,OAAO,CAAC,CAAC"}
@@ -1,6 +1,5 @@
1
1
  import { useCallback } from 'react';
2
2
  import { usePersSDK } from '../providers/PersSDKProvider';
3
- import { NativeTokenTypes } from '@explorins/pers-shared';
4
3
  /**
5
4
  * React hook for Web3 operations in the PERS SDK
6
5
  *
@@ -10,48 +9,9 @@ import { NativeTokenTypes } from '@explorins/pers-shared';
10
9
  *
11
10
  * Note: Wallet addresses should be obtained from `user.wallets` via `usePersSDK()`.
12
11
  *
13
- * ## ERC-1155 Token Handling
14
- *
15
- * **IMPORTANT**: ERC-1155 tokens require specific `tokenIds` to query balances.
16
- * Unlike ERC-721, you cannot enumerate owned tokens - you must know which tokenId to check.
17
- *
18
- * The tokenIds come from `TokenDTO.metadata[].tokenMetadataIncrementalId`.
19
- *
20
- * ### Option 1: Use the helper method (Recommended)
21
- * ```typescript
22
- * const { getUserOwnedTokensFromContract } = useWeb3();
23
- * const { getRewardTokens } = useTokens();
24
- *
25
- * const rewardTokens = await getRewardTokens();
26
- * const result = await getUserOwnedTokensFromContract(walletAddress, rewardTokens[0]);
27
- * console.log('Owned rewards:', result.ownedTokens);
28
- * ```
29
- *
30
- * ### Option 2: Manual tokenIds extraction
31
- * ```typescript
32
- * const { getTokenCollection, extractTokenIds } = useWeb3();
33
- * const { getRewardTokens } = useTokens();
34
- *
35
- * const rewardTokens = await getRewardTokens();
36
- * const rewardToken = rewardTokens[0];
37
- *
38
- * // Extract tokenIds for ERC-1155
39
- * const tokenIds = extractTokenIds(rewardToken);
40
- *
41
- * const collection = await getTokenCollection({
42
- * accountAddress: walletAddress,
43
- * contractAddress: rewardToken.contractAddress,
44
- * abi: rewardToken.abi,
45
- * chainId: rewardToken.chainId,
46
- * tokenIds: tokenIds // Required for ERC-1155!
47
- * });
48
- *
49
- * const ownedTokens = collection.tokens.filter(t => t.hasBalance);
50
- * ```
51
- *
52
12
  * @returns Web3 hook with methods for blockchain operations
53
13
  *
54
- * @example Basic Usage
14
+ * @example
55
15
  * ```typescript
56
16
  * function Web3Component() {
57
17
  * const { user } = usePersSDK();
@@ -172,138 +132,6 @@ export const useWeb3 = () => {
172
132
  throw error;
173
133
  }
174
134
  }, [sdk, isInitialized]);
175
- /**
176
- * Extract tokenIds from a TokenDTO for use with ERC-1155 contracts.
177
- *
178
- * ERC-1155 tokens require specific tokenIds to query balances. This helper
179
- * extracts the `tokenMetadataIncrementalId` from each metadata entry.
180
- *
181
- * @param token - Token definition containing metadata array
182
- * @returns Array of tokenId strings, or undefined if no metadata
183
- *
184
- * @example
185
- * ```typescript
186
- * const { extractTokenIds, getTokenCollection } = useWeb3();
187
- * const { getRewardTokens } = useTokens();
188
- *
189
- * const rewardToken = (await getRewardTokens())[0];
190
- * const tokenIds = extractTokenIds(rewardToken);
191
- *
192
- * if (tokenIds) {
193
- * const collection = await getTokenCollection({
194
- * accountAddress: walletAddress,
195
- * contractAddress: rewardToken.contractAddress,
196
- * abi: rewardToken.abi,
197
- * chainId: rewardToken.chainId,
198
- * tokenIds: tokenIds
199
- * });
200
- * }
201
- * ```
202
- */
203
- const extractTokenIds = useCallback((token) => {
204
- if (!token.metadata || token.metadata.length === 0) {
205
- return undefined;
206
- }
207
- return token.metadata.map(meta => meta.tokenMetadataIncrementalId.toString());
208
- }, []);
209
- /**
210
- * Get user's owned tokens from a specific token contract.
211
- *
212
- * This is a convenience method that automatically handles:
213
- * - ERC-1155 tokenId extraction from metadata
214
- * - Building the collection request
215
- * - Filtering to only tokens with balance > 0
216
- *
217
- * **This is the recommended way to get user's owned reward/status tokens.**
218
- *
219
- * @param walletAddress - User's wallet address
220
- * @param token - Token definition (from getRewardTokens, getStatusTokens, etc.)
221
- * @param maxTokens - Maximum tokens to retrieve (default: 50)
222
- * @returns Promise resolving to result with owned tokens
223
- * @throws Error if SDK is not initialized
224
- *
225
- * @example Get User's Owned Rewards
226
- * ```typescript
227
- * const { user } = usePersSDK();
228
- * const { getRewardTokens } = useTokens();
229
- * const { getUserOwnedTokensFromContract } = useWeb3();
230
- *
231
- * const walletAddress = user?.wallets?.[0]?.address;
232
- * const rewardTokens = await getRewardTokens();
233
- *
234
- * for (const token of rewardTokens) {
235
- * const result = await getUserOwnedTokensFromContract(walletAddress, token);
236
- *
237
- * console.log(`${token.name}: ${result.totalOwned} owned`);
238
- * result.ownedTokens.forEach(owned => {
239
- * console.log(` - TokenId ${owned.tokenId}: ${owned.balance}`);
240
- * console.log(` Name: ${owned.metadata?.name}`);
241
- * console.log(` Image: ${owned.metadata?.imageUrl}`);
242
- * });
243
- * }
244
- * ```
245
- */
246
- const getUserOwnedTokensFromContract = useCallback(async (walletAddress, token, maxTokens = 50) => {
247
- if (!isInitialized || !sdk) {
248
- throw new Error('SDK not initialized. Call initialize() first.');
249
- }
250
- try {
251
- // For ERC-1155, extract tokenIds from metadata
252
- const tokenIds = token.type === NativeTokenTypes.ERC1155 ? extractTokenIds(token) : undefined;
253
- const collection = await sdk.web3.getTokenCollection({
254
- accountAddress: walletAddress,
255
- contractAddress: token.contractAddress,
256
- abi: token.abi,
257
- chainId: token.chainId,
258
- tokenIds,
259
- maxTokens
260
- });
261
- // Filter to only owned tokens (hasBalance: true)
262
- // For ERC721, include all since they're enumerated
263
- const ownedTokens = token.type === NativeTokenTypes.ERC721
264
- ? collection.tokens
265
- : collection.tokens.filter(t => t.hasBalance);
266
- return {
267
- token,
268
- ownedTokens,
269
- totalOwned: ownedTokens.length
270
- };
271
- }
272
- catch (error) {
273
- console.error('Failed to get user owned tokens:', error);
274
- throw error;
275
- }
276
- }, [sdk, isInitialized, extractTokenIds]);
277
- /**
278
- * Build a TokenCollectionRequest from a TokenDTO.
279
- *
280
- * Automatically handles ERC-1155 tokenId extraction from metadata.
281
- * Use this when you need more control over the request than
282
- * `getUserOwnedTokensFromContract` provides.
283
- *
284
- * @param walletAddress - User's wallet address
285
- * @param token - Token definition
286
- * @param maxTokens - Maximum tokens to retrieve (default: 50)
287
- * @returns TokenCollectionRequest ready for getTokenCollection()
288
- *
289
- * @example
290
- * ```typescript
291
- * const { buildCollectionRequest, getTokenCollection } = useWeb3();
292
- *
293
- * const request = buildCollectionRequest(walletAddress, rewardToken);
294
- * const collection = await getTokenCollection(request);
295
- * ```
296
- */
297
- const buildCollectionRequest = useCallback((walletAddress, token, maxTokens = 50) => {
298
- return {
299
- accountAddress: walletAddress,
300
- contractAddress: token.contractAddress,
301
- abi: token.abi,
302
- chainId: token.chainId,
303
- tokenIds: token.type === NativeTokenTypes.ERC1155 ? extractTokenIds(token) : undefined,
304
- maxTokens
305
- };
306
- }, [extractTokenIds]);
307
135
  const resolveIPFSUrl = useCallback(async (url, chainId) => {
308
136
  if (!isInitialized || !sdk) {
309
137
  throw new Error('SDK not initialized. Call initialize() first.');
@@ -356,8 +184,86 @@ export const useWeb3 = () => {
356
184
  throw error;
357
185
  }
358
186
  }, [sdk, isInitialized]);
187
+ // ==========================================
188
+ // HELPER METHODS (delegating to core SDK)
189
+ // ==========================================
190
+ /**
191
+ * Extract tokenIds from a TokenDTO's metadata.
192
+ *
193
+ * Extracts `tokenMetadataIncrementalId` from each metadata entry. This is
194
+ * particularly useful for ERC-1155 tokens which require specific tokenIds
195
+ * to query balances, but works with any token that has metadata.
196
+ *
197
+ * **Note:** For most use cases, prefer `getAccountOwnedTokensFromContract()`
198
+ * which handles tokenId extraction automatically.
199
+ *
200
+ * @param token - Token definition containing metadata array
201
+ * @returns Array of tokenId strings, or undefined if no metadata
202
+ *
203
+ * @see {@link getAccountOwnedTokensFromContract} - Recommended helper that handles this automatically
204
+ */
205
+ const extractTokenIds = useCallback((token) => {
206
+ // Pure function - delegates to core SDK (no initialization required)
207
+ return sdk?.web3.extractTokenIds(token);
208
+ }, [sdk]);
209
+ /**
210
+ * Get owned tokens from a specific token contract for any blockchain address.
211
+ *
212
+ * **Recommended method** for querying token balances. Automatically handles:
213
+ * - Token type detection (ERC-20, ERC-721, ERC-1155)
214
+ * - TokenId extraction from metadata (uses `extractTokenIds()` internally for ERC-1155)
215
+ * - Building the collection request
216
+ * - Filtering to only tokens with balance > 0
217
+ *
218
+ * Works with any valid blockchain address - can query user wallets, external
219
+ * wallets, contract addresses, or any other address holding tokens.
220
+ *
221
+ * @param accountAddress - Any valid blockchain address (wallet, contract, etc.)
222
+ * @param token - Token definition (from getRewardTokens, getStatusTokens, etc.)
223
+ * @param maxTokens - Maximum tokens to retrieve (default: 50)
224
+ * @returns Promise resolving to result with owned tokens
225
+ * @throws Error if SDK is not initialized
226
+ *
227
+ * @example Query user's wallet
228
+ * ```typescript
229
+ * const { user } = usePersSDK();
230
+ * const { getAccountOwnedTokensFromContract } = useWeb3();
231
+ * const { getRewardTokens } = useTokens();
232
+ *
233
+ * const userWallet = user?.wallets?.[0]?.address;
234
+ * const rewardTokens = await getRewardTokens();
235
+ * const result = await getAccountOwnedTokensFromContract(userWallet, rewardTokens[0]);
236
+ * console.log(`User owns ${result.totalOwned} tokens`);
237
+ * ```
238
+ *
239
+ * @see {@link extractTokenIds} - Low-level helper used internally for ERC-1155
240
+ * @see {@link buildCollectionRequest} - For manual request building
241
+ */
242
+ const getAccountOwnedTokensFromContract = useCallback(async (accountAddress, token, maxTokens = 50) => {
243
+ if (!isInitialized || !sdk) {
244
+ throw new Error('SDK not initialized. Call initialize() first.');
245
+ }
246
+ return sdk.web3.getAccountOwnedTokensFromContract(accountAddress, token, maxTokens);
247
+ }, [sdk, isInitialized]);
248
+ /**
249
+ * Build a TokenCollectionRequest from a TokenDTO.
250
+ *
251
+ * Automatically handles ERC-1155 tokenId extraction from metadata.
252
+ * Use this when you need more control over the request than
253
+ * `getAccountOwnedTokensFromContract` provides.
254
+ *
255
+ * @param accountAddress - Any valid blockchain address (wallet, contract, etc.)
256
+ * @param token - Token definition
257
+ * @param maxTokens - Maximum tokens to retrieve (default: 50)
258
+ * @returns TokenCollectionRequest ready for getTokenCollection()
259
+ */
260
+ const buildCollectionRequest = useCallback((accountAddress, token, maxTokens = 50) => {
261
+ if (!sdk) {
262
+ throw new Error('SDK not initialized. Call initialize() first.');
263
+ }
264
+ return sdk.web3.buildCollectionRequest(accountAddress, token, maxTokens);
265
+ }, [sdk]);
359
266
  return {
360
- // Core methods
361
267
  getTokenBalance,
362
268
  getTokenMetadata,
363
269
  getTokenCollection,
@@ -365,11 +271,10 @@ export const useWeb3 = () => {
365
271
  fetchAndProcessMetadata,
366
272
  getChainDataById,
367
273
  getExplorerUrl,
368
- // Helper methods for ERC-1155 tokens
274
+ // Helper methods
369
275
  extractTokenIds,
370
- getUserOwnedTokensFromContract,
276
+ getAccountOwnedTokensFromContract,
371
277
  buildCollectionRequest,
372
- // State
373
278
  isAvailable: isInitialized && !!sdk?.web3,
374
279
  };
375
280
  };