@account-kit/privy-integration 4.75.4 → 4.76.0
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 +165 -6
- package/dist/esm/Provider.d.ts +4 -71
- package/dist/esm/Provider.js +4 -109
- package/dist/esm/Provider.js.map +1 -1
- package/dist/esm/Provider.native.d.ts +6 -0
- package/dist/esm/Provider.native.js +13 -0
- package/dist/esm/Provider.native.js.map +1 -0
- package/dist/esm/adapters/react-native.d.ts +6 -0
- package/dist/esm/adapters/react-native.js +132 -0
- package/dist/esm/adapters/react-native.js.map +1 -0
- package/dist/esm/adapters/types.d.ts +56 -0
- package/dist/esm/adapters/types.js +2 -0
- package/dist/esm/adapters/types.js.map +1 -0
- package/dist/esm/adapters/web.d.ts +6 -0
- package/dist/esm/adapters/web.js +71 -0
- package/dist/esm/adapters/web.js.map +1 -0
- package/dist/esm/adapters/web.native.d.ts +5 -0
- package/dist/esm/adapters/web.native.js +6 -0
- package/dist/esm/adapters/web.native.js.map +1 -0
- package/dist/esm/context/AlchemyContext.d.ts +71 -0
- package/dist/esm/context/AlchemyContext.js +115 -0
- package/dist/esm/context/AlchemyContext.js.map +1 -0
- package/dist/esm/hooks/internal/useEmbeddedWallet.d.ts +3 -4
- package/dist/esm/hooks/internal/useEmbeddedWallet.js +6 -13
- package/dist/esm/hooks/internal/useEmbeddedWallet.js.map +1 -1
- package/dist/esm/hooks/useAlchemyClient.js +17 -24
- package/dist/esm/hooks/useAlchemyClient.js.map +1 -1
- package/dist/esm/hooks/useAlchemySendTransaction.js +1 -1
- package/dist/esm/hooks/useAlchemySendTransaction.js.map +1 -1
- package/dist/esm/hooks/useAlchemySolanaTransaction.js +1 -1
- package/dist/esm/hooks/useAlchemySolanaTransaction.js.map +1 -1
- package/dist/esm/providers/ReactNativeProvider.d.ts +37 -0
- package/dist/esm/providers/ReactNativeProvider.js +41 -0
- package/dist/esm/providers/ReactNativeProvider.js.map +1 -0
- package/dist/esm/providers/WebProvider.d.ts +37 -0
- package/dist/esm/providers/WebProvider.js +41 -0
- package/dist/esm/providers/WebProvider.js.map +1 -0
- package/dist/esm/providers/WebProvider.native.d.ts +5 -0
- package/dist/esm/providers/WebProvider.native.js +9 -0
- package/dist/esm/providers/WebProvider.native.js.map +1 -0
- package/dist/esm/react-native.d.ts +11 -0
- package/dist/esm/react-native.js +13 -0
- package/dist/esm/react-native.js.map +1 -0
- package/dist/esm/types.d.ts +6 -0
- package/dist/esm/types.js.map +1 -1
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/version.js.map +1 -1
- package/dist/types/Provider.d.ts +4 -71
- package/dist/types/Provider.d.ts.map +1 -1
- package/dist/types/Provider.native.d.ts +7 -0
- package/dist/types/Provider.native.d.ts.map +1 -0
- package/dist/types/adapters/react-native.d.ts +7 -0
- package/dist/types/adapters/react-native.d.ts.map +1 -0
- package/dist/types/adapters/types.d.ts +57 -0
- package/dist/types/adapters/types.d.ts.map +1 -0
- package/dist/types/adapters/web.d.ts +7 -0
- package/dist/types/adapters/web.d.ts.map +1 -0
- package/dist/types/adapters/web.native.d.ts +6 -0
- package/dist/types/adapters/web.native.d.ts.map +1 -0
- package/dist/types/context/AlchemyContext.d.ts +72 -0
- package/dist/types/context/AlchemyContext.d.ts.map +1 -0
- package/dist/types/hooks/internal/useEmbeddedWallet.d.ts +3 -4
- package/dist/types/hooks/internal/useEmbeddedWallet.d.ts.map +1 -1
- package/dist/types/hooks/useAlchemyClient.d.ts.map +1 -1
- package/dist/types/providers/ReactNativeProvider.d.ts +38 -0
- package/dist/types/providers/ReactNativeProvider.d.ts.map +1 -0
- package/dist/types/providers/WebProvider.d.ts +38 -0
- package/dist/types/providers/WebProvider.d.ts.map +1 -0
- package/dist/types/providers/WebProvider.native.d.ts +6 -0
- package/dist/types/providers/WebProvider.native.d.ts.map +1 -0
- package/dist/types/react-native.d.ts +12 -0
- package/dist/types/react-native.d.ts.map +1 -0
- package/dist/types/types.d.ts +6 -0
- package/dist/types/types.d.ts.map +1 -1
- package/dist/types/version.d.ts +1 -1
- package/package.json +27 -4
- package/src/Provider.native.tsx +18 -0
- package/src/Provider.tsx +6 -0
- package/src/adapters/react-native.ts +210 -0
- package/src/adapters/types.ts +71 -0
- package/src/adapters/web.native.ts +6 -0
- package/src/adapters/web.ts +113 -0
- package/src/context/AlchemyContext.tsx +185 -0
- package/src/hooks/internal/useEmbeddedWallet.ts +6 -20
- package/src/hooks/useAlchemyClient.ts +24 -38
- package/src/hooks/useAlchemySendTransaction.ts +1 -1
- package/src/hooks/useAlchemySolanaTransaction.ts +1 -1
- package/src/providers/ReactNativeProvider.tsx +49 -0
- package/src/providers/WebProvider.native.tsx +11 -0
- package/src/providers/WebProvider.tsx +49 -0
- package/src/react-native.ts +29 -0
- package/src/types.ts +7 -0
- package/src/version.ts +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @account-kit/privy-integration
|
|
2
2
|
|
|
3
|
-
Add gas sponsorship and smart wallet features to your Privy app in under 5 minutes.
|
|
3
|
+
Add gas sponsorship and smart wallet features to your Privy app in under 5 minutes. Works with **React Web** and **React Native (Expo)**.
|
|
4
4
|
|
|
5
5
|
## What This Package Does
|
|
6
6
|
|
|
@@ -10,7 +10,8 @@ If you're already using [Privy](https://privy.io) for authentication, this packa
|
|
|
10
10
|
- **⛽ Gas Sponsorship** - Pay gas fees for your users via Alchemy Gas Manager (EVM & Solana)
|
|
11
11
|
- **💱 Token Swaps** - Execute swaps through Alchemy's swap infrastructure
|
|
12
12
|
- **🚀 Batched Transactions** - Send multiple operations in a single transaction using `sendTransaction([...])`
|
|
13
|
-
- **☀️ Solana Support** - Send sponsored Solana transactions with Privy's embedded Solana wallets
|
|
13
|
+
- **☀️ Solana Support** - Send sponsored Solana transactions with Privy's embedded Solana wallets (Web only)
|
|
14
|
+
- **📱 React Native Support** - Full EVM support for React Native apps using `@privy-io/expo`
|
|
14
15
|
|
|
15
16
|
All while keeping Privy as your authentication provider. No need to change your auth flow or migrate user accounts.
|
|
16
17
|
|
|
@@ -24,6 +25,8 @@ All while keeping Privy as your authentication provider. No need to change your
|
|
|
24
25
|
|
|
25
26
|
## Installation
|
|
26
27
|
|
|
28
|
+
### React Web
|
|
29
|
+
|
|
27
30
|
```bash
|
|
28
31
|
npm install @account-kit/privy-integration
|
|
29
32
|
# or
|
|
@@ -32,7 +35,17 @@ yarn add @account-kit/privy-integration
|
|
|
32
35
|
pnpm add @account-kit/privy-integration
|
|
33
36
|
```
|
|
34
37
|
|
|
35
|
-
###
|
|
38
|
+
### React Native (Expo)
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
npm install @account-kit/privy-integration @privy-io/expo
|
|
42
|
+
# or
|
|
43
|
+
yarn add @account-kit/privy-integration @privy-io/expo
|
|
44
|
+
# or
|
|
45
|
+
pnpm add @account-kit/privy-integration @privy-io/expo
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Optional: Solana Support (Web Only)
|
|
36
49
|
|
|
37
50
|
To use Solana features (like `useAlchemySolanaTransaction`), you'll need to install the Solana Web3.js library:
|
|
38
51
|
|
|
@@ -50,10 +63,15 @@ Then import from the `/solana` export:
|
|
|
50
63
|
import { useAlchemySolanaTransaction } from "@account-kit/privy-integration/solana";
|
|
51
64
|
```
|
|
52
65
|
|
|
53
|
-
> **Note:** The Solana functionality is completely optional. If you only need EVM features, you don't need to install `@solana/web3.js`.
|
|
66
|
+
> **Note:** The Solana functionality is completely optional and currently only available for React web. If you only need EVM features, you don't need to install `@solana/web3.js`.
|
|
54
67
|
|
|
55
68
|
## Quick Start
|
|
56
69
|
|
|
70
|
+
Choose your platform:
|
|
71
|
+
|
|
72
|
+
<details>
|
|
73
|
+
<summary><strong>React Web</strong></summary>
|
|
74
|
+
|
|
57
75
|
### 1. Wrap Your App with Both Providers
|
|
58
76
|
|
|
59
77
|
**Important:** `AlchemyProvider` must be nested **inside** `PrivyProvider` to access authentication state.
|
|
@@ -98,7 +116,7 @@ function SendButton() {
|
|
|
98
116
|
const result = await sendTransaction({
|
|
99
117
|
to: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
|
|
100
118
|
data: "0x...",
|
|
101
|
-
value: "
|
|
119
|
+
value: "0xde0b6b3a7640000", // 1 ETH in hex (also accepts decimal string or bigint)
|
|
102
120
|
});
|
|
103
121
|
|
|
104
122
|
console.log("Transaction hash:", result.txnHash);
|
|
@@ -111,7 +129,7 @@ function SendButton() {
|
|
|
111
129
|
try {
|
|
112
130
|
// Batch transactions
|
|
113
131
|
const result = await sendTransaction([
|
|
114
|
-
{ to: "0x...", data: "0x...", value: "
|
|
132
|
+
{ to: "0x...", data: "0x...", value: "0xde0b6b3a7640000" }, // 1 ETH
|
|
115
133
|
{ to: "0x...", data: "0x..." },
|
|
116
134
|
{ to: "0x...", data: "0x..." },
|
|
117
135
|
]);
|
|
@@ -249,6 +267,146 @@ function SolanaSendButton() {
|
|
|
249
267
|
}
|
|
250
268
|
```
|
|
251
269
|
|
|
270
|
+
</details>
|
|
271
|
+
|
|
272
|
+
<details>
|
|
273
|
+
<summary><strong>React Native (Expo)</strong></summary>
|
|
274
|
+
|
|
275
|
+
### 1. Wrap Your App with Both Providers
|
|
276
|
+
|
|
277
|
+
**Important:** Use `@privy-io/expo` and import from `/react-native` for React Native apps.
|
|
278
|
+
|
|
279
|
+
```tsx
|
|
280
|
+
import { PrivyProvider } from "@privy-io/expo";
|
|
281
|
+
import { AlchemyProvider } from "@account-kit/privy-integration/react-native";
|
|
282
|
+
|
|
283
|
+
function App() {
|
|
284
|
+
return (
|
|
285
|
+
<PrivyProvider appId="your-privy-app-id" clientId="your-privy-client-id">
|
|
286
|
+
<AlchemyProvider
|
|
287
|
+
apiKey="your-alchemy-api-key"
|
|
288
|
+
policyId="your-gas-policy-id" // optional, for gas sponsorship
|
|
289
|
+
>
|
|
290
|
+
<YourApp />
|
|
291
|
+
</AlchemyProvider>
|
|
292
|
+
</PrivyProvider>
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
### 2. Send Gasless Transactions
|
|
298
|
+
|
|
299
|
+
```tsx
|
|
300
|
+
import { useAlchemySendTransaction } from "@account-kit/privy-integration/react-native";
|
|
301
|
+
import { Button } from "react-native";
|
|
302
|
+
|
|
303
|
+
function SendButton() {
|
|
304
|
+
const { sendTransaction, isLoading, error, data } =
|
|
305
|
+
useAlchemySendTransaction();
|
|
306
|
+
|
|
307
|
+
const handleSend = async () => {
|
|
308
|
+
try {
|
|
309
|
+
// Single transaction
|
|
310
|
+
const result = await sendTransaction({
|
|
311
|
+
to: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
|
|
312
|
+
data: "0x...",
|
|
313
|
+
value: "0xde0b6b3a7640000", // 1 ETH in hex (also accepts decimal string or bigint)
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
console.log("Transaction hash:", result.txnHash);
|
|
317
|
+
} catch (err) {
|
|
318
|
+
console.error("Transaction failed:", err);
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const handleBatch = async () => {
|
|
323
|
+
try {
|
|
324
|
+
// Batch transactions
|
|
325
|
+
const result = await sendTransaction([
|
|
326
|
+
{ to: "0x...", data: "0x...", value: "0xde0b6b3a7640000" }, // 1 ETH
|
|
327
|
+
{ to: "0x...", data: "0x..." },
|
|
328
|
+
{ to: "0x...", data: "0x..." },
|
|
329
|
+
]);
|
|
330
|
+
|
|
331
|
+
console.log("Batch transaction hash:", result.txnHash);
|
|
332
|
+
} catch (err) {
|
|
333
|
+
console.error("Batch transaction failed:", err);
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
return (
|
|
338
|
+
<>
|
|
339
|
+
<Button
|
|
340
|
+
onPress={handleSend}
|
|
341
|
+
disabled={isLoading}
|
|
342
|
+
title={isLoading ? "Sending..." : "Send Transaction"}
|
|
343
|
+
/>
|
|
344
|
+
<Button
|
|
345
|
+
onPress={handleBatch}
|
|
346
|
+
disabled={isLoading}
|
|
347
|
+
title={isLoading ? "Sending..." : "Send Batch"}
|
|
348
|
+
/>
|
|
349
|
+
</>
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
### 3. Execute Token Swaps
|
|
355
|
+
|
|
356
|
+
```tsx
|
|
357
|
+
import {
|
|
358
|
+
useAlchemyPrepareSwap,
|
|
359
|
+
useAlchemySubmitSwap,
|
|
360
|
+
} from "@account-kit/privy-integration/react-native";
|
|
361
|
+
import { Button } from "react-native";
|
|
362
|
+
|
|
363
|
+
function SwapButton() {
|
|
364
|
+
const { prepareSwap } = useAlchemyPrepareSwap();
|
|
365
|
+
const { submitSwap, isLoading } = useAlchemySubmitSwap();
|
|
366
|
+
|
|
367
|
+
const handleSwap = async () => {
|
|
368
|
+
try {
|
|
369
|
+
// Prepare swap
|
|
370
|
+
const preparedSwap = await prepareSwap({
|
|
371
|
+
fromToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // ETH
|
|
372
|
+
toToken: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC
|
|
373
|
+
fromAmount: "0xde0b6b3a7640000", // Swap exactly 1 ETH
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
// Execute swap
|
|
377
|
+
const result = await submitSwap(preparedSwap);
|
|
378
|
+
console.log("Swap confirmed:", result.txnHash);
|
|
379
|
+
} catch (err) {
|
|
380
|
+
console.error("Swap failed:", err);
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
return (
|
|
385
|
+
<Button
|
|
386
|
+
onPress={handleSwap}
|
|
387
|
+
disabled={isLoading}
|
|
388
|
+
title={isLoading ? "Swapping..." : "Swap Tokens"}
|
|
389
|
+
/>
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
### Multiple Wallet Support
|
|
395
|
+
|
|
396
|
+
If your users have multiple Privy wallets, specify which one to use:
|
|
397
|
+
|
|
398
|
+
```tsx
|
|
399
|
+
<AlchemyProvider
|
|
400
|
+
apiKey="your-alchemy-api-key"
|
|
401
|
+
policyId="your-gas-policy-id"
|
|
402
|
+
walletAddress="0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
|
|
403
|
+
>
|
|
404
|
+
<YourApp />
|
|
405
|
+
</AlchemyProvider>
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
</details>
|
|
409
|
+
|
|
252
410
|
## Configuration
|
|
253
411
|
|
|
254
412
|
### AlchemyProvider Props
|
|
@@ -263,6 +421,7 @@ function SolanaSendButton() {
|
|
|
263
421
|
| `solanaPolicyId` | `string \| string[]` | No | Gas Manager policy ID(s) for Solana sponsorship |
|
|
264
422
|
| `disableSponsorship` | `boolean` | No | Set to `true` to disable gas sponsorship by default (default: `false`) |
|
|
265
423
|
| `accountAuthMode` | `'eip7702' \| 'owner'` | No | Authorization mode for EVM smart accounts (default: `'eip7702'`) |
|
|
424
|
+
| `walletAddress` | `string` | No | Specific wallet address to use if user has multiple wallets (defaults to first wallet) |
|
|
266
425
|
|
|
267
426
|
\* **Required configuration (pick one):**
|
|
268
427
|
|
package/dist/esm/Provider.d.ts
CHANGED
|
@@ -1,73 +1,6 @@
|
|
|
1
|
-
import { type PropsWithChildren } from "react";
|
|
2
|
-
import type { SmartWalletClient } from "@account-kit/wallet-client";
|
|
3
|
-
import type { SmartContractAccount } from "@aa-sdk/core";
|
|
4
|
-
import type { AlchemyProviderConfig } from "./types.js";
|
|
5
1
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* @internal
|
|
2
|
+
* Web-specific exports
|
|
3
|
+
* Re-exports the web provider and hooks for React applications
|
|
9
4
|
*/
|
|
10
|
-
export
|
|
11
|
-
|
|
12
|
-
* Client cache stored in React tree (similar to QueryClient in React Query)
|
|
13
|
-
*
|
|
14
|
-
* @internal
|
|
15
|
-
*/
|
|
16
|
-
interface ClientCache {
|
|
17
|
-
client: SmartWalletClient | null;
|
|
18
|
-
account: SmartContractAccount | null;
|
|
19
|
-
cacheKey: string | null;
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* Provider component that configures Alchemy infrastructure for transaction handling
|
|
23
|
-
* Must be nested INSIDE PrivyProvider to access authentication state
|
|
24
|
-
* Automatically manages client cache lifecycle and resets on logout
|
|
25
|
-
*
|
|
26
|
-
* @param {PropsWithChildren<AlchemyProviderConfig>} props - Component props
|
|
27
|
-
* @param {React.ReactNode} props.children - React children to wrap with Alchemy configuration
|
|
28
|
-
* @param {string} [props.apiKey] - Your Alchemy API key
|
|
29
|
-
* @param {string} [props.jwt] - JWT token for authentication
|
|
30
|
-
* @param {string} [props.rpcUrl] - Custom RPC URL for EVM chains
|
|
31
|
-
* @param {string} [props.solanaRpcUrl] - Custom RPC URL for Solana
|
|
32
|
-
* @param {string | string[]} [props.policyId] - Gas Manager policy ID(s) for EVM chains
|
|
33
|
-
* @param {string | string[]} [props.solanaPolicyId] - Gas Manager policy ID(s) for Solana
|
|
34
|
-
* @param {boolean} [props.disableSponsorship] - Set to true to disable sponsorship by default (default: false)
|
|
35
|
-
* @param {'eip7702' | 'owner'} [props.accountAuthMode] - Authorization mode for EVM smart accounts (default: 'eip7702')
|
|
36
|
-
* @returns {JSX.Element} Provider component
|
|
37
|
-
*
|
|
38
|
-
* @example
|
|
39
|
-
* ```tsx
|
|
40
|
-
* <PrivyProvider appId="...">
|
|
41
|
-
* <AlchemyProvider
|
|
42
|
-
* apiKey="your-alchemy-api-key"
|
|
43
|
-
* policyId="your-gas-policy-id"
|
|
44
|
-
* >
|
|
45
|
-
* <YourApp />
|
|
46
|
-
* </AlchemyProvider>
|
|
47
|
-
* </PrivyProvider>
|
|
48
|
-
* ```
|
|
49
|
-
*/
|
|
50
|
-
export declare function AlchemyProvider({ children, accountAuthMode, ...config }: PropsWithChildren<AlchemyProviderConfig>): import("react/jsx-runtime").JSX.Element;
|
|
51
|
-
/**
|
|
52
|
-
* Hook to access Alchemy provider configuration
|
|
53
|
-
* Must be used within an <AlchemyProvider> component
|
|
54
|
-
*
|
|
55
|
-
* @returns {NormalizedAlchemyConfig} The current Alchemy configuration with defaults applied
|
|
56
|
-
* @throws {Error} If used outside of AlchemyProvider
|
|
57
|
-
*
|
|
58
|
-
* @example
|
|
59
|
-
* ```tsx
|
|
60
|
-
* const config = useAlchemyConfig();
|
|
61
|
-
* console.log('Policy ID:', config.policyId);
|
|
62
|
-
* console.log('Auth Mode:', config.accountAuthMode); // Always defined
|
|
63
|
-
* ```
|
|
64
|
-
*/
|
|
65
|
-
export declare function useAlchemyConfig(): NormalizedAlchemyConfig;
|
|
66
|
-
/**
|
|
67
|
-
* Hook to access the client cache (internal use only)
|
|
68
|
-
*
|
|
69
|
-
* @internal
|
|
70
|
-
* @returns {ClientCache} The client cache object
|
|
71
|
-
*/
|
|
72
|
-
export declare function useClientCache(): ClientCache;
|
|
73
|
-
export {};
|
|
5
|
+
export { AlchemyProvider } from "./providers/WebProvider.js";
|
|
6
|
+
export { useAlchemyConfig } from "./context/AlchemyContext.js";
|
package/dist/esm/Provider.js
CHANGED
|
@@ -1,112 +1,7 @@
|
|
|
1
|
-
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
-
import { createContext, useContext, useRef, useEffect, } from "react";
|
|
3
|
-
import { usePrivy } from "@privy-io/react-auth";
|
|
4
|
-
const AlchemyContext = createContext(null);
|
|
5
|
-
const ClientCacheContext = createContext(null);
|
|
6
1
|
/**
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* Automatically manages client cache lifecycle and resets on logout
|
|
10
|
-
*
|
|
11
|
-
* @param {PropsWithChildren<AlchemyProviderConfig>} props - Component props
|
|
12
|
-
* @param {React.ReactNode} props.children - React children to wrap with Alchemy configuration
|
|
13
|
-
* @param {string} [props.apiKey] - Your Alchemy API key
|
|
14
|
-
* @param {string} [props.jwt] - JWT token for authentication
|
|
15
|
-
* @param {string} [props.rpcUrl] - Custom RPC URL for EVM chains
|
|
16
|
-
* @param {string} [props.solanaRpcUrl] - Custom RPC URL for Solana
|
|
17
|
-
* @param {string | string[]} [props.policyId] - Gas Manager policy ID(s) for EVM chains
|
|
18
|
-
* @param {string | string[]} [props.solanaPolicyId] - Gas Manager policy ID(s) for Solana
|
|
19
|
-
* @param {boolean} [props.disableSponsorship] - Set to true to disable sponsorship by default (default: false)
|
|
20
|
-
* @param {'eip7702' | 'owner'} [props.accountAuthMode] - Authorization mode for EVM smart accounts (default: 'eip7702')
|
|
21
|
-
* @returns {JSX.Element} Provider component
|
|
22
|
-
*
|
|
23
|
-
* @example
|
|
24
|
-
* ```tsx
|
|
25
|
-
* <PrivyProvider appId="...">
|
|
26
|
-
* <AlchemyProvider
|
|
27
|
-
* apiKey="your-alchemy-api-key"
|
|
28
|
-
* policyId="your-gas-policy-id"
|
|
29
|
-
* >
|
|
30
|
-
* <YourApp />
|
|
31
|
-
* </AlchemyProvider>
|
|
32
|
-
* </PrivyProvider>
|
|
33
|
-
* ```
|
|
2
|
+
* Web-specific exports
|
|
3
|
+
* Re-exports the web provider and hooks for React applications
|
|
34
4
|
*/
|
|
35
|
-
export
|
|
36
|
-
|
|
37
|
-
// Normalize config with default values
|
|
38
|
-
const normalizedConfig = {
|
|
39
|
-
...config,
|
|
40
|
-
accountAuthMode,
|
|
41
|
-
};
|
|
42
|
-
// Store cache in a ref - persists across renders but scoped to this component instance
|
|
43
|
-
// This makes it SSR-safe (each request gets its own cache) and React StrictMode-safe
|
|
44
|
-
const cache = useRef({
|
|
45
|
-
client: null,
|
|
46
|
-
account: null,
|
|
47
|
-
cacheKey: null,
|
|
48
|
-
});
|
|
49
|
-
// Track previous state to detect logout and wallet changes
|
|
50
|
-
const prevAuthenticatedRef = useRef(authenticated);
|
|
51
|
-
const prevWalletAddressRef = useRef(user?.wallet?.address);
|
|
52
|
-
// Automatically reset cache when user logs out or switches wallets
|
|
53
|
-
useEffect(() => {
|
|
54
|
-
const wasAuthenticated = prevAuthenticatedRef.current;
|
|
55
|
-
const prevWalletAddress = prevWalletAddressRef.current;
|
|
56
|
-
const currentWalletAddress = user?.wallet?.address;
|
|
57
|
-
// Reset cache on logout
|
|
58
|
-
if (wasAuthenticated && !authenticated) {
|
|
59
|
-
cache.current.client = null;
|
|
60
|
-
cache.current.account = null;
|
|
61
|
-
cache.current.cacheKey = null;
|
|
62
|
-
}
|
|
63
|
-
// Reset cache on wallet address change (account switching)
|
|
64
|
-
if (authenticated &&
|
|
65
|
-
prevWalletAddress &&
|
|
66
|
-
currentWalletAddress &&
|
|
67
|
-
prevWalletAddress !== currentWalletAddress) {
|
|
68
|
-
cache.current.client = null;
|
|
69
|
-
cache.current.account = null;
|
|
70
|
-
cache.current.cacheKey = null;
|
|
71
|
-
}
|
|
72
|
-
// Update refs for next render
|
|
73
|
-
prevAuthenticatedRef.current = authenticated;
|
|
74
|
-
prevWalletAddressRef.current = currentWalletAddress;
|
|
75
|
-
}, [authenticated, user?.wallet?.address]);
|
|
76
|
-
return (_jsx(AlchemyContext.Provider, { value: normalizedConfig, children: _jsx(ClientCacheContext.Provider, { value: cache.current, children: children }) }));
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* Hook to access Alchemy provider configuration
|
|
80
|
-
* Must be used within an <AlchemyProvider> component
|
|
81
|
-
*
|
|
82
|
-
* @returns {NormalizedAlchemyConfig} The current Alchemy configuration with defaults applied
|
|
83
|
-
* @throws {Error} If used outside of AlchemyProvider
|
|
84
|
-
*
|
|
85
|
-
* @example
|
|
86
|
-
* ```tsx
|
|
87
|
-
* const config = useAlchemyConfig();
|
|
88
|
-
* console.log('Policy ID:', config.policyId);
|
|
89
|
-
* console.log('Auth Mode:', config.accountAuthMode); // Always defined
|
|
90
|
-
* ```
|
|
91
|
-
*/
|
|
92
|
-
export function useAlchemyConfig() {
|
|
93
|
-
const context = useContext(AlchemyContext);
|
|
94
|
-
if (!context) {
|
|
95
|
-
throw new Error("useAlchemyConfig must be used within <AlchemyProvider />");
|
|
96
|
-
}
|
|
97
|
-
return context;
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* Hook to access the client cache (internal use only)
|
|
101
|
-
*
|
|
102
|
-
* @internal
|
|
103
|
-
* @returns {ClientCache} The client cache object
|
|
104
|
-
*/
|
|
105
|
-
export function useClientCache() {
|
|
106
|
-
const context = useContext(ClientCacheContext);
|
|
107
|
-
if (!context) {
|
|
108
|
-
throw new Error("useClientCache must be used within <AlchemyProvider />. Make sure AlchemyProvider is nested inside PrivyProvider.");
|
|
109
|
-
}
|
|
110
|
-
return context;
|
|
111
|
-
}
|
|
5
|
+
export { AlchemyProvider } from "./providers/WebProvider.js";
|
|
6
|
+
export { useAlchemyConfig } from "./context/AlchemyContext.js";
|
|
112
7
|
//# sourceMappingURL=Provider.js.map
|
package/dist/esm/Provider.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Provider.js","sourceRoot":"","sources":["../../src/Provider.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"Provider.js","sourceRoot":"","sources":["../../src/Provider.tsx"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC","sourcesContent":["/**\n * Web-specific exports\n * Re-exports the web provider and hooks for React applications\n */\nexport { AlchemyProvider } from \"./providers/WebProvider.js\";\nexport { useAlchemyConfig } from \"./context/AlchemyContext.js\";\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React Native stub for web Provider
|
|
3
|
+
* This file prevents Metro from importing web-specific code
|
|
4
|
+
*/
|
|
5
|
+
export function AlchemyProvider() {
|
|
6
|
+
throw new Error("This module requires @privy-io/react-auth which is not available in React Native. " +
|
|
7
|
+
'Import from "@account-kit/privy-integration/react-native" instead.');
|
|
8
|
+
}
|
|
9
|
+
export function useAlchemyConfig() {
|
|
10
|
+
throw new Error("This module requires @privy-io/react-auth which is not available in React Native. " +
|
|
11
|
+
'Import from "@account-kit/privy-integration/react-native" instead.');
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=Provider.native.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Provider.native.js","sourceRoot":"","sources":["../../src/Provider.native.tsx"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,UAAU,eAAe;IAC7B,MAAM,IAAI,KAAK,CACb,oFAAoF;QAClF,oEAAoE,CACvE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,gBAAgB;IAC9B,MAAM,IAAI,KAAK,CACb,oFAAoF;QAClF,oEAAoE,CACvE,CAAC;AACJ,CAAC","sourcesContent":["/**\n * React Native stub for web Provider\n * This file prevents Metro from importing web-specific code\n */\n\nexport function AlchemyProvider() {\n throw new Error(\n \"This module requires @privy-io/react-auth which is not available in React Native. \" +\n 'Import from \"@account-kit/privy-integration/react-native\" instead.',\n );\n}\n\nexport function useAlchemyConfig() {\n throw new Error(\n \"This module requires @privy-io/react-auth which is not available in React Native. \" +\n 'Import from \"@account-kit/privy-integration/react-native\" instead.',\n );\n}\n"]}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { useCallback } from "react";
|
|
2
|
+
import { usePrivy, useEmbeddedEthereumWallet, } from "@privy-io/expo";
|
|
3
|
+
import { isAddressEqual, parseSignature } from "viem";
|
|
4
|
+
import { hashAuthorization } from "viem/utils";
|
|
5
|
+
/**
|
|
6
|
+
* React Native (Expo) adapter for @privy-io/expo
|
|
7
|
+
* Implements platform-specific hooks for React Native applications
|
|
8
|
+
*/
|
|
9
|
+
export const reactNativeAdapter = {
|
|
10
|
+
useEmbeddedWallet(preferredAddress) {
|
|
11
|
+
const { wallets } = useEmbeddedEthereumWallet();
|
|
12
|
+
const getEmbeddedWallet = useCallback(() => {
|
|
13
|
+
if (!wallets || wallets.length === 0) {
|
|
14
|
+
throw new Error("Privy embedded wallet not found. Please ensure the user is authenticated and has created a wallet.");
|
|
15
|
+
}
|
|
16
|
+
// If a preferred address is specified, find that wallet
|
|
17
|
+
const wallet = preferredAddress
|
|
18
|
+
? wallets.find((w) => isAddressEqual(w.address, preferredAddress))
|
|
19
|
+
: wallets[0];
|
|
20
|
+
if (!wallet) {
|
|
21
|
+
throw new Error(preferredAddress
|
|
22
|
+
? `Privy embedded wallet with address ${preferredAddress} not found.`
|
|
23
|
+
: "Privy embedded wallet not found. Please ensure the user is authenticated and has created a wallet.");
|
|
24
|
+
}
|
|
25
|
+
return adaptExpoWallet(wallet);
|
|
26
|
+
}, [wallets, preferredAddress]);
|
|
27
|
+
return getEmbeddedWallet;
|
|
28
|
+
},
|
|
29
|
+
usePrivyAuth() {
|
|
30
|
+
const { user } = usePrivy();
|
|
31
|
+
return { authenticated: !!user, user };
|
|
32
|
+
},
|
|
33
|
+
useWalletAddress(preferredAddress) {
|
|
34
|
+
const { wallets } = useEmbeddedEthereumWallet();
|
|
35
|
+
if (!wallets || wallets.length === 0) {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
// If a preferred address is specified, find that wallet
|
|
39
|
+
if (preferredAddress) {
|
|
40
|
+
const wallet = wallets.find((w) => isAddressEqual(w.address, preferredAddress));
|
|
41
|
+
return wallet?.address;
|
|
42
|
+
}
|
|
43
|
+
// Otherwise return the first wallet
|
|
44
|
+
return wallets[0]?.address;
|
|
45
|
+
},
|
|
46
|
+
useAuthorizationSigner(preferredAddress) {
|
|
47
|
+
const { wallets } = useEmbeddedEthereumWallet();
|
|
48
|
+
const signAuthorization = useCallback(async (unsignedAuth) => {
|
|
49
|
+
if (!wallets || wallets.length === 0) {
|
|
50
|
+
throw new Error("Privy embedded wallet not found. Please ensure the user is authenticated and has created a wallet.");
|
|
51
|
+
}
|
|
52
|
+
// If a preferred address is specified, find that wallet
|
|
53
|
+
const wallet = preferredAddress
|
|
54
|
+
? wallets.find((w) => isAddressEqual(w.address, preferredAddress))
|
|
55
|
+
: wallets[0];
|
|
56
|
+
if (!wallet) {
|
|
57
|
+
throw new Error(preferredAddress
|
|
58
|
+
? `Privy embedded wallet with address ${preferredAddress} not found.`
|
|
59
|
+
: "Privy embedded wallet not found. Please ensure the user is authenticated and has created a wallet.");
|
|
60
|
+
}
|
|
61
|
+
const provider = await wallet.getProvider?.();
|
|
62
|
+
if (!provider) {
|
|
63
|
+
throw new Error("Provider not available on this wallet. Ensure you're using the embedded Ethereum wallet.");
|
|
64
|
+
}
|
|
65
|
+
// Extract the implementation address (handle both 'address' and 'contractAddress' fields)
|
|
66
|
+
const implementationAddress = unsignedAuth.address ?? unsignedAuth.contractAddress;
|
|
67
|
+
if (!implementationAddress) {
|
|
68
|
+
throw new Error("Implementation address is required for EIP-7702 authorization");
|
|
69
|
+
}
|
|
70
|
+
// Create the authorization structure (matches Privy's implementation)
|
|
71
|
+
const authorization = {
|
|
72
|
+
chainId: unsignedAuth.chainId,
|
|
73
|
+
address: implementationAddress,
|
|
74
|
+
nonce: unsignedAuth.nonce,
|
|
75
|
+
};
|
|
76
|
+
// Hash the authorization using viem (same as Privy does)
|
|
77
|
+
const authorizationHash = hashAuthorization(authorization);
|
|
78
|
+
// Sign the hash directly with secp256k1_sign (same as Privy)
|
|
79
|
+
const signature = (await provider.request({
|
|
80
|
+
method: "secp256k1_sign",
|
|
81
|
+
params: [authorizationHash],
|
|
82
|
+
}));
|
|
83
|
+
// Parse the signature using viem (same as Privy)
|
|
84
|
+
const parsedSignature = parseSignature(signature);
|
|
85
|
+
return {
|
|
86
|
+
chainId: unsignedAuth.chainId,
|
|
87
|
+
address: implementationAddress,
|
|
88
|
+
nonce: unsignedAuth.nonce,
|
|
89
|
+
...parsedSignature,
|
|
90
|
+
};
|
|
91
|
+
}, [wallets, preferredAddress]);
|
|
92
|
+
return signAuthorization;
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
/**
|
|
96
|
+
* Adapts an Expo wallet to the common EmbeddedWallet interface
|
|
97
|
+
*
|
|
98
|
+
* @param {ExpoEmbeddedWallet} wallet - The Expo embedded wallet to adapt
|
|
99
|
+
* @returns {EmbeddedWallet} The adapted wallet following the common interface
|
|
100
|
+
*/
|
|
101
|
+
function adaptExpoWallet(wallet) {
|
|
102
|
+
// Use closure to maintain up-to-date chain ID across chain switches
|
|
103
|
+
let cachedChainId = wallet.chainId || "1";
|
|
104
|
+
return {
|
|
105
|
+
address: wallet.address,
|
|
106
|
+
get chainId() {
|
|
107
|
+
return cachedChainId;
|
|
108
|
+
},
|
|
109
|
+
getEthereumProvider: async () => {
|
|
110
|
+
if (!wallet.getProvider) {
|
|
111
|
+
throw new Error("getProvider is not available on this wallet. Ensure you're using the embedded Ethereum wallet.");
|
|
112
|
+
}
|
|
113
|
+
const provider = await wallet.getProvider();
|
|
114
|
+
// Always fetch current chain ID when provider is accessed
|
|
115
|
+
// This ensures we have the latest chain after wallet_switchEthereumChain calls
|
|
116
|
+
try {
|
|
117
|
+
const currentChainId = (await provider.request({
|
|
118
|
+
method: "eth_chainId",
|
|
119
|
+
params: [],
|
|
120
|
+
}));
|
|
121
|
+
// Convert hex to decimal string format (e.g., "0x1" -> "1")
|
|
122
|
+
cachedChainId = parseInt(currentChainId, 16).toString();
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
// Fall back to cached value if fetch fails
|
|
126
|
+
// Chain ID fetch errors are non-critical and can happen during initialization
|
|
127
|
+
}
|
|
128
|
+
return provider;
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
//# sourceMappingURL=react-native.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"react-native.js","sourceRoot":"","sources":["../../../src/adapters/react-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACpC,OAAO,EACL,QAAQ,EACR,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IAAI,EAAE;YAC9B,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC;gBACxB,MAAM,IAAI,KAAK,CACb,gGAAgG,CACjG,CAAC;YACJ,CAAC;YACD,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,WAAW,EAAE,CAAC;YAE5C,0DAA0D;YAC1D,+EAA+E;YAC/E,IAAI,CAAC;gBACH,MAAM,cAAc,GAAG,CAAC,MAAM,QAAQ,CAAC,OAAO,CAAC;oBAC7C,MAAM,EAAE,aAAa;oBACrB,MAAM,EAAE,EAAE;iBACX,CAAC,CAAW,CAAC;gBAEd,4DAA4D;gBAC5D,aAAa,GAAG,QAAQ,CAAC,cAAc,EAAE,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC;YAC1D,CAAC;YAAC,MAAM,CAAC;gBACP,2CAA2C;gBAC3C,8EAA8E;YAChF,CAAC;YAED,OAAO,QAAQ,CAAC;QAClB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { useCallback } from \"react\";\nimport {\n usePrivy,\n useEmbeddedEthereumWallet,\n type PrivyEmbeddedWalletProvider,\n} from \"@privy-io/expo\";\nimport { isAddressEqual, parseSignature, type Authorization } from \"viem\";\nimport { hashAuthorization } from \"viem/utils\";\nimport type { AuthorizationRequest } from \"@aa-sdk/core\";\nimport type { PrivyAdapter, EmbeddedWallet, PrivyAuthState } from \"./types.js\";\n\n/**\n * Wallet type from @privy-io/expo\n * Based on the example app structure\n */\ninterface ExpoEmbeddedWallet {\n address: string;\n chainId?: string;\n getProvider?: () => Promise<PrivyEmbeddedWalletProvider>;\n}\n\n/**\n * React Native (Expo) adapter for @privy-io/expo\n * Implements platform-specific hooks for React Native applications\n */\nexport const reactNativeAdapter: PrivyAdapter = {\n useEmbeddedWallet(preferredAddress?: string) {\n const { wallets } = useEmbeddedEthereumWallet();\n\n const getEmbeddedWallet = useCallback((): EmbeddedWallet => {\n if (!wallets || wallets.length === 0) {\n throw new Error(\n \"Privy embedded wallet not found. Please ensure the user is authenticated and has created a wallet.\",\n );\n }\n\n // If a preferred address is specified, find that wallet\n const wallet = preferredAddress\n ? wallets.find((w) =>\n isAddressEqual(\n w.address as `0x${string}`,\n preferredAddress as `0x${string}`,\n ),\n )\n : wallets[0];\n\n if (!wallet) {\n throw new Error(\n preferredAddress\n ? `Privy embedded wallet with address ${preferredAddress} not found.`\n : \"Privy embedded wallet not found. Please ensure the user is authenticated and has created a wallet.\",\n );\n }\n\n return adaptExpoWallet(wallet);\n }, [wallets, preferredAddress]);\n\n return getEmbeddedWallet;\n },\n\n usePrivyAuth(): PrivyAuthState {\n const { user } = usePrivy();\n return { authenticated: !!user, user };\n },\n\n useWalletAddress(preferredAddress?: string): string | undefined {\n const { wallets } = useEmbeddedEthereumWallet();\n\n if (!wallets || wallets.length === 0) {\n return undefined;\n }\n\n // If a preferred address is specified, find that wallet\n if (preferredAddress) {\n const wallet = wallets.find((w) =>\n isAddressEqual(\n w.address as `0x${string}`,\n preferredAddress as `0x${string}`,\n ),\n );\n return wallet?.address;\n }\n\n // Otherwise return the first wallet\n return wallets[0]?.address;\n },\n\n useAuthorizationSigner(preferredAddress?: string) {\n const { wallets } = useEmbeddedEthereumWallet();\n\n const signAuthorization = useCallback(\n async (\n unsignedAuth: AuthorizationRequest<number>,\n ): Promise<Authorization<number, true>> => {\n if (!wallets || wallets.length === 0) {\n throw new Error(\n \"Privy embedded wallet not found. Please ensure the user is authenticated and has created a wallet.\",\n );\n }\n\n // If a preferred address is specified, find that wallet\n const wallet = preferredAddress\n ? wallets.find((w) =>\n isAddressEqual(\n w.address as `0x${string}`,\n preferredAddress as `0x${string}`,\n ),\n )\n : wallets[0];\n\n if (!wallet) {\n throw new Error(\n preferredAddress\n ? `Privy embedded wallet with address ${preferredAddress} not found.`\n : \"Privy embedded wallet not found. Please ensure the user is authenticated and has created a wallet.\",\n );\n }\n\n const provider = await wallet.getProvider?.();\n if (!provider) {\n throw new Error(\n \"Provider not available on this wallet. Ensure you're using the embedded Ethereum wallet.\",\n );\n }\n\n // Extract the implementation address (handle both 'address' and 'contractAddress' fields)\n const implementationAddress =\n unsignedAuth.address ?? unsignedAuth.contractAddress;\n\n if (!implementationAddress) {\n throw new Error(\n \"Implementation address is required for EIP-7702 authorization\",\n );\n }\n\n // Create the authorization structure (matches Privy's implementation)\n const authorization = {\n chainId: unsignedAuth.chainId,\n address: implementationAddress,\n nonce: unsignedAuth.nonce,\n };\n\n // Hash the authorization using viem (same as Privy does)\n const authorizationHash = hashAuthorization(authorization);\n\n // Sign the hash directly with secp256k1_sign (same as Privy)\n const signature = (await provider.request({\n method: \"secp256k1_sign\",\n params: [authorizationHash],\n })) as `0x${string}`;\n\n // Parse the signature using viem (same as Privy)\n const parsedSignature = parseSignature(signature);\n\n return {\n chainId: unsignedAuth.chainId,\n address: implementationAddress,\n nonce: unsignedAuth.nonce,\n ...parsedSignature,\n };\n },\n [wallets, preferredAddress],\n );\n\n return signAuthorization;\n },\n};\n\n/**\n * Adapts an Expo wallet to the common EmbeddedWallet interface\n *\n * @param {ExpoEmbeddedWallet} wallet - The Expo embedded wallet to adapt\n * @returns {EmbeddedWallet} The adapted wallet following the common interface\n */\nfunction adaptExpoWallet(wallet: ExpoEmbeddedWallet): EmbeddedWallet {\n // Use closure to maintain up-to-date chain ID across chain switches\n let cachedChainId = wallet.chainId || \"1\";\n\n return {\n address: wallet.address as `0x${string}`,\n get chainId() {\n return cachedChainId;\n },\n getEthereumProvider: async () => {\n if (!wallet.getProvider) {\n throw new Error(\n \"getProvider is not available on this wallet. Ensure you're using the embedded Ethereum wallet.\",\n );\n }\n const provider = await wallet.getProvider();\n\n // Always fetch current chain ID when provider is accessed\n // This ensures we have the latest chain after wallet_switchEthereumChain calls\n try {\n const currentChainId = (await provider.request({\n method: \"eth_chainId\",\n params: [],\n })) as string;\n\n // Convert hex to decimal string format (e.g., \"0x1\" -> \"1\")\n cachedChainId = parseInt(currentChainId, 16).toString();\n } catch {\n // Fall back to cached value if fetch fails\n // Chain ID fetch errors are non-critical and can happen during initialization\n }\n\n return provider;\n },\n };\n}\n"]}
|