@account-kit/privy-integration 4.73.1-alpha.1 → 4.73.1-alpha.11
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/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.js +49 -37
- package/dist/esm/adapters/react-native.js.map +1 -1
- 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/hooks/useAlchemyClient.js +11 -10
- 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/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/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/version.js.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.map +1 -1
- package/dist/types/adapters/web.native.d.ts +6 -0
- package/dist/types/adapters/web.native.d.ts.map +1 -0
- package/dist/types/hooks/useAlchemyClient.d.ts.map +1 -1
- package/dist/types/providers/WebProvider.native.d.ts +6 -0
- package/dist/types/providers/WebProvider.native.d.ts.map +1 -0
- package/dist/types/version.d.ts +1 -1
- package/dist/types/version.d.ts.map +1 -1
- package/package.json +14 -4
- package/src/Provider.native.tsx +18 -0
- package/src/Provider.tsx +6 -0
- package/src/adapters/react-native.ts +102 -78
- package/src/adapters/web.native.ts +6 -0
- package/src/context/AlchemyContext.tsx +162 -0
- package/src/hooks/useAlchemyClient.ts +17 -11
- package/src/hooks/useAlchemySendTransaction.ts +1 -1
- package/src/hooks/useAlchemySolanaTransaction.ts +1 -1
- package/src/providers/ReactNativeProvider.tsx +45 -0
- package/src/providers/WebProvider.native.tsx +11 -0
- package/src/providers/WebProvider.tsx +45 -0
- package/src/version.ts +1 -1
|
@@ -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("Web Provider 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("useAlchemyConfig from web Provider 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,iDAAiD;QAC/C,oEAAoE,CACvE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,gBAAgB;IAC9B,MAAM,IAAI,KAAK,CACb,uEAAuE;QACrE,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 \"Web Provider 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 \"useAlchemyConfig from web Provider is not available in React Native. \" +\n 'Import from \"@account-kit/privy-integration/react-native\" instead.',\n );\n}\n"]}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { useCallback } from "react";
|
|
2
2
|
import { usePrivy, useEmbeddedEthereumWallet, } from "@privy-io/expo";
|
|
3
|
+
import { hashAuthorization } from "viem/utils";
|
|
4
|
+
import { parseSignature } from "viem";
|
|
3
5
|
/**
|
|
4
6
|
* React Native (Expo) adapter for @privy-io/expo
|
|
5
7
|
* Implements platform-specific hooks for React Native applications
|
|
@@ -22,11 +24,15 @@ export const reactNativeAdapter = {
|
|
|
22
24
|
},
|
|
23
25
|
useAuthorizationSigner() {
|
|
24
26
|
const { wallets } = useEmbeddedEthereumWallet();
|
|
25
|
-
|
|
27
|
+
// Don't memoize the callback - create it fresh each time to ensure we have the latest wallets
|
|
28
|
+
const signAuthorization = async (unsignedAuth) => {
|
|
29
|
+
console.log("[RN Adapter] signAuthorization called with:", unsignedAuth);
|
|
30
|
+
console.log("[RN Adapter] Current wallets:", wallets);
|
|
26
31
|
const wallet = wallets?.[0];
|
|
27
32
|
if (!wallet) {
|
|
28
33
|
throw new Error("Privy embedded wallet not found. Please ensure the user is authenticated and has created a wallet.");
|
|
29
34
|
}
|
|
35
|
+
console.log("[RN Adapter] Using wallet:", wallet.address);
|
|
30
36
|
const provider = await wallet.getProvider?.();
|
|
31
37
|
if (!provider) {
|
|
32
38
|
throw new Error("Provider not available on this wallet. Ensure you're using the embedded Ethereum wallet.");
|
|
@@ -36,48 +42,34 @@ export const reactNativeAdapter = {
|
|
|
36
42
|
if (!implementationAddress) {
|
|
37
43
|
throw new Error("Implementation address is required for EIP-7702 authorization");
|
|
38
44
|
}
|
|
39
|
-
|
|
45
|
+
console.log("[RN Adapter] Signing 7702 auth for address:", implementationAddress);
|
|
46
|
+
// Create the authorization structure (matches Privy's implementation)
|
|
40
47
|
const authorization = {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
chainId: unsignedAuth.chainId,
|
|
45
|
-
},
|
|
46
|
-
types: {
|
|
47
|
-
Authorization: [
|
|
48
|
-
{ name: "chainId", type: "uint256" },
|
|
49
|
-
{ name: "address", type: "address" },
|
|
50
|
-
{ name: "nonce", type: "uint256" },
|
|
51
|
-
],
|
|
52
|
-
},
|
|
53
|
-
primaryType: "Authorization",
|
|
54
|
-
message: {
|
|
55
|
-
chainId: unsignedAuth.chainId,
|
|
56
|
-
address: implementationAddress,
|
|
57
|
-
nonce: unsignedAuth.nonce,
|
|
58
|
-
},
|
|
48
|
+
chainId: unsignedAuth.chainId,
|
|
49
|
+
address: implementationAddress,
|
|
50
|
+
nonce: unsignedAuth.nonce,
|
|
59
51
|
};
|
|
52
|
+
// Hash the authorization using viem (same as Privy does)
|
|
53
|
+
const authorizationHash = hashAuthorization(authorization);
|
|
54
|
+
console.log("[RN Adapter] Authorization hash:", authorizationHash);
|
|
55
|
+
// Sign the hash directly with secp256k1_sign (same as Privy)
|
|
60
56
|
const signature = (await provider.request({
|
|
61
|
-
method: "
|
|
62
|
-
params: [
|
|
57
|
+
method: "secp256k1_sign",
|
|
58
|
+
params: [authorizationHash],
|
|
63
59
|
}));
|
|
64
|
-
|
|
65
|
-
//
|
|
66
|
-
const
|
|
67
|
-
const
|
|
68
|
-
const v = parseInt(signature.slice(130, 132), 16);
|
|
69
|
-
// Convert v to yParity (0 or 1)
|
|
70
|
-
// v can be 27/28 (legacy) or 0/1 (EIP-155)
|
|
71
|
-
const yParity = v >= 27 ? v - 27 : v;
|
|
72
|
-
return {
|
|
60
|
+
console.log("[RN Adapter] Received signature:", signature);
|
|
61
|
+
// Parse the signature using viem (same as Privy)
|
|
62
|
+
const parsedSignature = parseSignature(signature);
|
|
63
|
+
const result = {
|
|
73
64
|
chainId: unsignedAuth.chainId,
|
|
74
65
|
address: implementationAddress,
|
|
75
66
|
nonce: unsignedAuth.nonce,
|
|
76
|
-
|
|
77
|
-
s,
|
|
78
|
-
yParity,
|
|
67
|
+
...parsedSignature,
|
|
79
68
|
};
|
|
80
|
-
|
|
69
|
+
console.log("[RN Adapter] Returning authorization:", result);
|
|
70
|
+
return result;
|
|
71
|
+
};
|
|
72
|
+
return signAuthorization;
|
|
81
73
|
},
|
|
82
74
|
};
|
|
83
75
|
/**
|
|
@@ -87,14 +79,34 @@ export const reactNativeAdapter = {
|
|
|
87
79
|
* @returns {EmbeddedWallet} The adapted wallet following the common interface
|
|
88
80
|
*/
|
|
89
81
|
function adaptExpoWallet(wallet) {
|
|
82
|
+
// Use closure to maintain up-to-date chain ID across chain switches
|
|
83
|
+
let cachedChainId = wallet.chainId || "1";
|
|
90
84
|
return {
|
|
91
85
|
address: wallet.address,
|
|
92
|
-
|
|
86
|
+
get chainId() {
|
|
87
|
+
return cachedChainId;
|
|
88
|
+
},
|
|
93
89
|
getEthereumProvider: async () => {
|
|
94
90
|
if (!wallet.getProvider) {
|
|
95
91
|
throw new Error("getProvider is not available on this wallet. Ensure you're using the embedded Ethereum wallet.");
|
|
96
92
|
}
|
|
97
|
-
|
|
93
|
+
const provider = await wallet.getProvider();
|
|
94
|
+
// Always fetch current chain ID when provider is accessed
|
|
95
|
+
// This ensures we have the latest chain after wallet_switchEthereumChain calls
|
|
96
|
+
try {
|
|
97
|
+
const currentChainId = (await provider.request({
|
|
98
|
+
method: "eth_chainId",
|
|
99
|
+
params: [],
|
|
100
|
+
}));
|
|
101
|
+
// Convert hex to decimal string format (e.g., "0x1" -> "1")
|
|
102
|
+
cachedChainId = parseInt(currentChainId, 16).toString();
|
|
103
|
+
console.log("[RN Adapter] Updated chain ID to:", cachedChainId);
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
console.warn("[Privy Integration] Failed to fetch current chain ID:", err);
|
|
107
|
+
// Fall back to cached value if fetch fails
|
|
108
|
+
}
|
|
109
|
+
return provider;
|
|
98
110
|
},
|
|
99
111
|
};
|
|
100
112
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-native.js","sourceRoot":"","sources":["../../../src/adapters/react-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EA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,uDAAuD,EACvD,GAAG,CACJ,CAAC;gBACF,2CAA2C;YAC7C,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 type { Authorization } from \"viem\";\nimport { hashAuthorization } from \"viem/utils\";\nimport { parseSignature } from \"viem\";\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() {\n const { wallets } = useEmbeddedEthereumWallet();\n\n const getEmbeddedWallet = useCallback((): EmbeddedWallet => {\n const wallet = wallets?.[0];\n if (!wallet) {\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 return adaptExpoWallet(wallet);\n }, [wallets]);\n\n return getEmbeddedWallet;\n },\n\n usePrivyAuth(): PrivyAuthState {\n const { user } = usePrivy();\n return { authenticated: !!user, user };\n },\n\n useAuthorizationSigner() {\n const { wallets } = useEmbeddedEthereumWallet();\n\n // Don't memoize the callback - create it fresh each time to ensure we have the latest wallets\n const signAuthorization = async (\n unsignedAuth: AuthorizationRequest<number>,\n ): Promise<Authorization<number, true>> => {\n console.log(\"[RN Adapter] signAuthorization called with:\", unsignedAuth);\n console.log(\"[RN Adapter] Current wallets:\", wallets);\n\n const wallet = wallets?.[0];\n if (!wallet) {\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 console.log(\"[RN Adapter] Using wallet:\", wallet.address);\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 console.log(\n \"[RN Adapter] Signing 7702 auth for address:\",\n implementationAddress,\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 console.log(\"[RN Adapter] Authorization hash:\", authorizationHash);\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 console.log(\"[RN Adapter] Received signature:\", signature);\n\n // Parse the signature using viem (same as Privy)\n const parsedSignature = parseSignature(signature);\n\n const result = {\n chainId: unsignedAuth.chainId,\n address: implementationAddress,\n nonce: unsignedAuth.nonce,\n ...parsedSignature,\n };\n\n console.log(\"[RN Adapter] Returning authorization:\", result);\n return result;\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 console.log(\"[RN Adapter] Updated chain ID to:\", cachedChainId);\n } catch (err) {\n console.warn(\n \"[Privy Integration] Failed to fetch current chain ID:\",\n err,\n );\n // Fall back to cached value if fetch fails\n }\n\n return provider;\n },\n };\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"web.native.js","sourceRoot":"","sources":["../../../src/adapters/web.native.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,CAAC","sourcesContent":["/**\n * React Native stub for web adapter\n * This file prevents Metro from importing @privy-io/react-auth\n */\n\nexport const webAdapter = null;\n"]}
|
|
@@ -25,10 +25,14 @@ export function useAlchemyClient() {
|
|
|
25
25
|
const config = useAlchemyConfig();
|
|
26
26
|
const cache = useClientCache();
|
|
27
27
|
const getEmbeddedWallet = useEmbeddedWallet();
|
|
28
|
-
const
|
|
29
|
-
const
|
|
28
|
+
const getClient = useCallback(async () => {
|
|
29
|
+
const embeddedWallet = getEmbeddedWallet();
|
|
30
|
+
// IMPORTANT: Get provider FIRST to ensure chain ID is updated
|
|
31
|
+
// The provider fetch triggers chain ID update in the adapter
|
|
32
|
+
const provider = await embeddedWallet.getEthereumProvider();
|
|
33
|
+
// NOW get the chain from the SAME wallet instance with updated chain ID
|
|
30
34
|
// Handle CAIP-2 format like "eip155:1"
|
|
31
|
-
const chainIdStr =
|
|
35
|
+
const chainIdStr = embeddedWallet.chainId?.toString();
|
|
32
36
|
if (!chainIdStr) {
|
|
33
37
|
throw new Error("Embedded wallet chainId is not set. Please ensure the wallet is connected to a network.");
|
|
34
38
|
}
|
|
@@ -39,12 +43,9 @@ export function useAlchemyClient() {
|
|
|
39
43
|
if (isNaN(parsedChainId)) {
|
|
40
44
|
throw new Error(`Failed to parse chainId from embedded wallet. Received: ${chainIdStr}`);
|
|
41
45
|
}
|
|
42
|
-
|
|
43
|
-
}, [getEmbeddedWallet]);
|
|
44
|
-
const getClient = useCallback(async () => {
|
|
45
|
-
const embeddedWallet = getEmbeddedWallet();
|
|
46
|
-
const chain = getEmbeddedWalletChain();
|
|
46
|
+
const chain = getChain(parsedChainId);
|
|
47
47
|
// Generate a cache key based on configuration and wallet address
|
|
48
|
+
// IMPORTANT: Include whether authorization signer is available in cache key
|
|
48
49
|
const currentCacheKey = JSON.stringify({
|
|
49
50
|
address: embeddedWallet.address,
|
|
50
51
|
chainId: chain.id,
|
|
@@ -52,13 +53,13 @@ export function useAlchemyClient() {
|
|
|
52
53
|
jwt: config.jwt,
|
|
53
54
|
rpcUrl: config.rpcUrl,
|
|
54
55
|
policyId: config.policyId,
|
|
56
|
+
hasAuthSigner: !!signAuthorizationFn,
|
|
55
57
|
});
|
|
56
58
|
// Return cached client if configuration hasn't changed
|
|
57
59
|
if (cache.client && cache.cacheKey === currentCacheKey) {
|
|
58
60
|
return cache.client;
|
|
59
61
|
}
|
|
60
62
|
// Configuration changed or no cache exists, create new client
|
|
61
|
-
const provider = await embeddedWallet.getEthereumProvider();
|
|
62
63
|
// Create base signer from Privy wallet
|
|
63
64
|
const baseSigner = new WalletClientSigner(createWalletClient({
|
|
64
65
|
account: embeddedWallet.address,
|
|
@@ -72,6 +73,7 @@ export function useAlchemyClient() {
|
|
|
72
73
|
signAuthorization: signAuthorizationFn,
|
|
73
74
|
}
|
|
74
75
|
: baseSigner;
|
|
76
|
+
console.log("[useAlchemyClient] Created signer with authorization support:", !!signAuthorizationFn);
|
|
75
77
|
// Determine transport configuration using schema validation
|
|
76
78
|
// This properly handles combinations like rpcUrl + jwt together
|
|
77
79
|
const transportConfig = ConnectionConfigSchema.parse({
|
|
@@ -99,7 +101,6 @@ export function useAlchemyClient() {
|
|
|
99
101
|
return cache.client;
|
|
100
102
|
}, [
|
|
101
103
|
getEmbeddedWallet,
|
|
102
|
-
getEmbeddedWalletChain,
|
|
103
104
|
signAuthorizationFn,
|
|
104
105
|
config.apiKey,
|
|
105
106
|
config.jwt,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAlchemyClient.js","sourceRoot":"","sources":["../../../src/hooks/useAlchemyClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACpC,OAAO,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAgB,MAAM,MAAM,CAAC;AAChE,OAAO,EACL,uBAAuB,GAExB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EACL,gBAAgB,EAChB,cAAc,EACd,UAAU,GACX,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AAEpE;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,gBAAgB;IAC9B,MAAM,OAAO,GAAG,UAAU,EAAE,CAAC;IAC7B,MAAM,mBAAmB,GAAG,OAAO,CAAC,sBAAsB,EAAE,EAAE,IAAI,IAAI,CAAC;IACvE,MAAM,MAAM,GAAG,gBAAgB,EAAE,CAAC;IAClC,MAAM,KAAK,GAAG,cAAc,EAAE,CAAC;IAC/B,MAAM,iBAAiB,GAAG,iBAAiB,EAAE,CAAC;IAE9C,MAAM,
|
|
1
|
+
{"version":3,"file":"useAlchemyClient.js","sourceRoot":"","sources":["../../../src/hooks/useAlchemyClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO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A4D;QAC5D,gEAAgE;QAChE,MAAM,eAAe,GAAG,sBAAsB,CAAC,KAAK,CAAC;YACnD,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,GAAG,EAAE,MAAM,CAAC,GAAG;SAChB,CAAC,CAAC;QAEH,MAAM,SAAS,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;QAE3C,SAAS,CAAC,aAAa,CAAC;YACtB,6BAA6B,EAAE,qBAAqB;SACrD,CAAC,CAAC;QAEH,+DAA+D;QAC/D,KAAK,CAAC,MAAM,GAAG,uBAAuB,CAAC;YACrC,KAAK;YACL,SAAS;YACT,MAAM;YACN,SAAS,EAAE,MAAM,CAAC,QAAQ;gBACxB,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC;oBAC9B,CAAC,CAAC,MAAM,CAAC,QAAQ;oBACjB,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC;gBACrB,CAAC,CAAC,SAAS;SACd,CAAC,CAAC;QAEH,sBAAsB;QACtB,KAAK,CAAC,QAAQ,GAAG,eAAe,CAAC;QAEjC,OAAO,KAAK,CAAC,MAAM,CAAC;IACtB,CAAC,EAAE;QACD,iBAAiB;QACjB,mBAAmB;QACnB,MAAM,CAAC,MAAM;QACb,MAAM,CAAC,GAAG;QACV,MAAM,CAAC,MAAM;QACb,MAAM,CAAC,QAAQ;QACf,KAAK;KACN,CAAC,CAAC;IAEH,OAAO,EAAE,SAAS,EAAE,CAAC;AACvB,CAAC","sourcesContent":["import { useCallback } from \"react\";\nimport { WalletClientSigner, ConnectionConfigSchema } from \"@aa-sdk/core\";\nimport { createWalletClient, custom, type Address } from \"viem\";\nimport {\n createSmartWalletClient,\n type SmartWalletClient,\n} from \"@account-kit/wallet-client\";\nimport { alchemy } from \"@account-kit/infra\";\nimport {\n useAlchemyConfig,\n useClientCache,\n useAdapter,\n} from \"../context/AlchemyContext.js\";\nimport { getChain } from \"../util/getChain.js\";\nimport { useEmbeddedWallet } from \"./internal/useEmbeddedWallet.js\";\n\n/**\n * Hook to get and memoize a SmartWalletClient instance\n * The client is cached in the AlchemyProvider context (React tree scoped)\n * Automatically clears cache on logout via the provider\n *\n * @returns {{ getClient: () => Promise<SmartWalletClient> }} Object containing the smart wallet client getter\n *\n * @example\n * ```tsx\n * const { getClient } = useAlchemyClient();\n * const smartWalletClient = await getClient();\n * ```\n */\nexport function useAlchemyClient() {\n const adapter = useAdapter();\n const signAuthorizationFn = adapter.useAuthorizationSigner?.() || null;\n const config = useAlchemyConfig();\n const cache = useClientCache();\n const getEmbeddedWallet = useEmbeddedWallet();\n\n const getClient = useCallback(async (): Promise<SmartWalletClient> => {\n const embeddedWallet = getEmbeddedWallet();\n\n // IMPORTANT: Get provider FIRST to ensure chain ID is updated\n // The provider fetch triggers chain ID update in the adapter\n const provider = await embeddedWallet.getEthereumProvider();\n\n // NOW get the chain from the SAME wallet instance with updated chain ID\n // Handle CAIP-2 format like \"eip155:1\"\n const chainIdStr = embeddedWallet.chainId?.toString();\n\n if (!chainIdStr) {\n throw new Error(\n \"Embedded wallet chainId is not set. Please ensure the wallet is connected to a network.\",\n );\n }\n\n const numericChainId = chainIdStr.includes(\":\")\n ? chainIdStr.split(\":\")[1]\n : chainIdStr;\n\n const parsedChainId = Number(numericChainId);\n\n if (isNaN(parsedChainId)) {\n throw new Error(\n `Failed to parse chainId from embedded wallet. Received: ${chainIdStr}`,\n );\n }\n\n const chain = getChain(parsedChainId);\n\n // Generate a cache key based on configuration and wallet address\n // IMPORTANT: Include whether authorization signer is available in cache key\n const currentCacheKey = JSON.stringify({\n address: embeddedWallet.address,\n chainId: chain.id,\n apiKey: config.apiKey,\n jwt: config.jwt,\n rpcUrl: config.rpcUrl,\n policyId: config.policyId,\n hasAuthSigner: !!signAuthorizationFn,\n });\n\n // Return cached client if configuration hasn't changed\n if (cache.client && cache.cacheKey === currentCacheKey) {\n return cache.client;\n }\n\n // Configuration changed or no cache exists, create new client\n\n // Create base signer from Privy wallet\n const baseSigner = new WalletClientSigner(\n createWalletClient({\n account: embeddedWallet.address as Address,\n chain,\n transport: custom(provider),\n }),\n \"privy\",\n );\n\n // Extend signer with EIP-7702 authorization support (if available)\n const signer = signAuthorizationFn\n ? {\n ...baseSigner,\n signAuthorization: signAuthorizationFn,\n }\n : baseSigner;\n\n console.log(\n \"[useAlchemyClient] Created signer with authorization support:\",\n !!signAuthorizationFn,\n );\n\n // Determine transport configuration using schema validation\n // This properly handles combinations like rpcUrl + jwt together\n const transportConfig = ConnectionConfigSchema.parse({\n rpcUrl: config.rpcUrl,\n apiKey: config.apiKey,\n jwt: config.jwt,\n });\n\n const transport = alchemy(transportConfig);\n\n transport.updateHeaders({\n \"X-Alchemy-Client-Breadcrumb\": \"privyIntegrationSdk\",\n });\n\n // Create and cache the smart wallet client in provider context\n cache.client = createSmartWalletClient({\n chain,\n transport,\n signer,\n policyIds: config.policyId\n ? Array.isArray(config.policyId)\n ? config.policyId\n : [config.policyId]\n : undefined,\n });\n\n // Store the cache key\n cache.cacheKey = currentCacheKey;\n\n return cache.client;\n }, [\n getEmbeddedWallet,\n signAuthorizationFn,\n config.apiKey,\n config.jwt,\n config.rpcUrl,\n config.policyId,\n cache,\n ]);\n\n return { getClient };\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useCallback, useState } from "react";
|
|
2
2
|
import { isHex } from "viem";
|
|
3
3
|
import { useAlchemyClient } from "./useAlchemyClient.js";
|
|
4
|
-
import { useAlchemyConfig } from "../
|
|
4
|
+
import { useAlchemyConfig } from "../context/AlchemyContext.js";
|
|
5
5
|
import { useEmbeddedWallet } from "./internal/useEmbeddedWallet.js";
|
|
6
6
|
/**
|
|
7
7
|
* Normalize value to hex format
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAlchemySendTransaction.js","sourceRoot":"","sources":["../../../src/hooks/useAlchemySendTransaction.ts"],"names":[],"mappings":"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,OAAO,QAAQ,CAAC;QAClB,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,QAAQ,GACZ,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;YAC/D,QAAQ,CAAC,QAAQ,CAAC,CAAC;YACnB,MAAM,QAAQ,CAAC;QACjB,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;IACH,CAAC,EACD,CAAC,SAAS,EAAE,iBAAiB,EAAE,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,kBAAkB,CAAC,CAC3E,CAAC;IAEF,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,QAAQ,CAAC,IAAI,CAAC,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,CAAC;QACd,YAAY,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO;QACL,eAAe;QACf,SAAS;QACT,KAAK;QACL,IAAI;QACJ,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import { useCallback, useState } from \"react\";\nimport { type Address, type Hex, isHex } from \"viem\";\nimport { useAlchemyClient } from \"./useAlchemyClient.js\";\nimport { useAlchemyConfig } from \"../context/AlchemyContext.js\";\nimport { useEmbeddedWallet } from \"./internal/useEmbeddedWallet.js\";\nimport type {\n UnsignedTransactionRequest,\n SendTransactionOptions,\n SendTransactionResult,\n UseSendTransactionResult,\n} from \"../types\";\n\n/**\n * Normalize value to hex format\n * Accepts bigint, number, decimal string, or hex string\n *\n * @param {string | number | bigint} value - Value to normalize\n * @returns {Hex} Hex string representation of the value\n */\nfunction normalizeValue(value: string | number | bigint): Hex {\n if (typeof value === \"bigint\") {\n return `0x${value.toString(16)}`;\n }\n if (typeof value === \"number\") {\n return `0x${BigInt(value).toString(16)}`;\n }\n if (isHex(value)) {\n return value;\n }\n // Assume decimal string\n return `0x${BigInt(value).toString(16)}`;\n}\n\n/**\n * Hook to send transactions with optional gas sponsorship via Alchemy\n * Supports both single transactions and batch transactions\n * Drop-in alternative to Privy's useSendTransaction hook\n *\n * @returns {UseSendTransactionResult} Hook result with sendTransaction function and state\n *\n * @example Single transaction\n * ```tsx\n * const { sendTransaction, isLoading, error, data } = useAlchemySendTransaction();\n *\n * const handleSend = async () => {\n * try {\n * const result = await sendTransaction({\n * to: '0x...',\n * data: '0x...',\n * value: '1000000000000000000', // 1 ETH\n * });\n * console.log('Transaction hash:', result.txnHash);\n * } catch (err) {\n * console.error('Transaction failed:', err);\n * }\n * };\n * ```\n *\n * @example Batch transactions\n * ```tsx\n * const { sendTransaction } = useAlchemySendTransaction();\n *\n * const result = await sendTransaction([\n * { to: '0x...', data: '0x...', value: '1000000000000000000' },\n * { to: '0x...', data: '0x...' },\n * ]);\n * ```\n */\nexport function useAlchemySendTransaction(): UseSendTransactionResult {\n const { getClient } = useAlchemyClient();\n const config = useAlchemyConfig();\n const getEmbeddedWallet = useEmbeddedWallet();\n\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [data, setData] = useState<SendTransactionResult | null>(null);\n\n const sendTransaction = useCallback(\n async (\n input: UnsignedTransactionRequest | UnsignedTransactionRequest[],\n options?: SendTransactionOptions,\n ): Promise<SendTransactionResult> => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = await getClient();\n const embeddedWallet = getEmbeddedWallet();\n\n // Determine if transaction should be sponsored\n const hasPolicyId = !!config.policyId;\n const enableSponsorship = !config.disableSponsorship;\n const shouldSponsor =\n options?.disableSponsorship !== undefined\n ? !options.disableSponsorship\n : hasPolicyId && enableSponsorship;\n\n // Format the transaction call(s)\n const inputs = Array.isArray(input) ? input : [input];\n const formattedCalls = inputs.map((txn) => ({\n to: txn.to,\n data: txn.data,\n value: txn.value ? normalizeValue(txn.value) : undefined,\n }));\n\n // Build capabilities based on sponsorship\n const policyId = Array.isArray(config.policyId)\n ? config.policyId[0]\n : config.policyId;\n\n const capabilities: {\n eip7702Auth: true;\n paymasterService?: { policyId: string };\n } = { eip7702Auth: true };\n\n if (shouldSponsor && policyId) {\n capabilities.paymasterService = { policyId };\n }\n\n // Send the transaction(s)\n const result = await client.sendCalls({\n from: embeddedWallet.address as Address,\n calls: formattedCalls,\n capabilities,\n });\n\n if (!result.preparedCallIds || result.preparedCallIds.length === 0) {\n throw new Error(\n \"No prepared call IDs returned from transaction submission\",\n );\n }\n\n // Wait for the transaction to be confirmed\n const txStatus = await client.waitForCallsStatus({\n id: result.preparedCallIds[0],\n timeout: 60_000,\n });\n\n const txnHash = txStatus.receipts?.[0]?.transactionHash;\n if (!txnHash) {\n throw new Error(\"Transaction hash not found in receipt\");\n }\n\n const txResult: SendTransactionResult = { txnHash };\n setData(txResult);\n return txResult;\n } catch (err) {\n const errorObj =\n err instanceof Error ? err : new Error(\"Transaction failed\");\n setError(errorObj);\n throw errorObj;\n } finally {\n setIsLoading(false);\n }\n },\n [getClient, getEmbeddedWallet, config.policyId, config.disableSponsorship],\n );\n\n const reset = useCallback(() => {\n setError(null);\n setData(null);\n setIsLoading(false);\n }, []);\n\n return {\n sendTransaction,\n isLoading,\n error,\n data,\n reset,\n };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useCallback, useMemo, useState } from "react";
|
|
2
2
|
import { Connection, PublicKey, SystemProgram, Transaction, TransactionInstruction, VersionedTransaction, } from "@solana/web3.js";
|
|
3
|
-
import { useAlchemyConfig } from "../
|
|
3
|
+
import { useAlchemyConfig } from "../context/AlchemyContext.js";
|
|
4
4
|
import { createSolanaSponsoredTransaction } from "../util/createSolanaSponsoredTransaction.js";
|
|
5
5
|
import { useSignTransaction, useWallets } from "@privy-io/react-auth/solana";
|
|
6
6
|
import { createSolanaTransaction } from "../util/createSolanaTransaction.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAlchemySolanaTransaction.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YACT,YAAY,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;IACH,CAAC,EACD;QACE,cAAc;QACd,UAAU;QACV,iBAAiB;QACjB,wBAAwB;QACxB,IAAI,CAAC,mBAAmB;QACxB,eAAe;KAChB,CACF,CAAC;IAEF,MAAM,eAAe,GAAG,WAAW,CACjC,CAAC,MAA+B,EAAE,EAAE;QAClC,2FAA2F;QAC3F,oBAAoB,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IAC/C,CAAC,EACD,CAAC,oBAAoB,CAAC,CACvB,CAAC;IAEF,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,YAAY,CAAC,KAAK,CAAC,CAAC;QACpB,QAAQ,CAAC,IAAI,CAAC,CAAC;QACf,OAAO,CAAC,SAAS,CAAC,CAAC;IACrB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO;QACL,UAAU;QACV,IAAI;QACJ,SAAS;QACT,KAAK;QACL,KAAK;QACL,eAAe;QACf,oBAAoB;KACrB,CAAC;AACJ,CAAC;AAED,SAAS,OAAO,CAAC,OAAe;IAC9B,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;AAC3B,CAAC","sourcesContent":["import { useCallback, useMemo, useState } from \"react\";\nimport {\n Connection,\n PublicKey,\n SystemProgram,\n Transaction,\n TransactionInstruction,\n VersionedTransaction,\n} from \"@solana/web3.js\";\nimport { useAlchemyConfig } from \"../Provider.js\";\nimport { createSolanaSponsoredTransaction } from \"../util/createSolanaSponsoredTransaction.js\";\nimport { useSignTransaction, useWallets } from \"@privy-io/react-auth/solana\";\nimport { createSolanaTransaction } from \"../util/createSolanaTransaction.js\";\n\n/**\n * Type helper for values that can be synchronous or asynchronous\n *\n * @template T - The value type\n */\nexport type PromiseOrValue<T> = T | Promise<T>;\n\n/**\n * Callback to modify a transaction before it's signed\n * Useful for adding additional signatures or metadata\n *\n * @param transaction - The unsigned transaction to modify\n * @returns The modified transaction\n */\nexport type PreSend = (\n this: void,\n transaction: VersionedTransaction | Transaction,\n) => PromiseOrValue<VersionedTransaction | Transaction>;\n\n/**\n * Callback to transform instructions into a custom transaction\n * Useful for advanced transaction construction (e.g., multi-sig, custom versioning)\n *\n * @param instructions - Array of Solana transaction instructions\n * @returns Constructed transaction (legacy or versioned)\n */\nexport type TransformInstruction = (\n this: void,\n instructions: TransactionInstruction[],\n) => PromiseOrValue<Transaction | VersionedTransaction>;\n\n/**\n * Optional transaction lifecycle hooks for advanced use cases\n */\nexport type SolanaTransactionParamOptions = {\n /** Hook called before signing the transaction */\n preSend?: PreSend;\n /** Custom transaction builder from instructions */\n transformInstruction?: TransformInstruction;\n};\n\n/**\n * Parameters for sending a Solana transaction\n * Supports either a simple transfer or custom instructions\n */\nexport type SolanaTransactionParams =\n | {\n /** Simple SOL transfer parameters */\n transfer: {\n /** Amount in lamports (accepts number or bigint) */\n amount: number | bigint;\n /** Recipient's base58-encoded address */\n toAddress: string;\n };\n /** Optional transaction lifecycle hooks */\n transactionComponents?: SolanaTransactionParamOptions;\n /** Options for confirming the transaction on-chain */\n confirmationOptions?: Parameters<Connection[\"confirmTransaction\"]>[1];\n }\n | {\n /** Custom Solana transaction instructions */\n instructions: TransactionInstruction[];\n /** Optional transaction lifecycle hooks */\n transactionComponents?: SolanaTransactionParamOptions;\n /** Options for confirming the transaction on-chain */\n confirmationOptions?: Parameters<Connection[\"confirmTransaction\"]>[1];\n };\n\n/**\n * Result of a successful Solana transaction\n */\nexport interface SolanaTransactionResult {\n /** Base58-encoded transaction signature (hash) */\n hash: string;\n}\n\n/**\n * Configuration options for useAlchemySolanaTransaction hook\n */\nexport interface UseAlchemySolanaTransactionOptions {\n /** Solana RPC URL (overrides provider config) */\n rpcUrl?: string;\n /** Gas sponsorship policy ID (overrides provider config) */\n policyId?: string | void;\n /** Transaction confirmation options */\n confirmationOptions?: Parameters<Connection[\"confirmTransaction\"]>[1];\n /** Specific wallet address to use (defaults to first available wallet) */\n walletAddress?: string;\n}\n\n/**\n * Return type of useAlchemySolanaTransaction hook\n */\nexport interface UseAlchemySolanaTransactionResult {\n /** Active Solana connection instance */\n readonly connection: Connection | null;\n /** Transaction result if successful */\n readonly data: void | SolanaTransactionResult;\n /** Whether a transaction is currently being sent */\n readonly isPending: boolean;\n /** Error if transaction failed */\n readonly error: Error | null;\n /** Reset hook state (clears error, data, isPending) */\n reset(): void;\n /** Send transaction (fire-and-forget, errors caught internally) */\n sendTransaction(params: SolanaTransactionParams): void;\n /** Send transaction and await result (throws on error) */\n sendTransactionAsync(\n params: SolanaTransactionParams,\n ): Promise<SolanaTransactionResult>;\n}\n\n/**\n * Hook to send Solana transactions with optional gas sponsorship via Alchemy\n * Works with Privy's Solana wallet integration for signing transactions\n * Supports both simple transfers and custom instruction sets\n *\n * @param {UseAlchemySolanaTransactionOptions} [opts] - Configuration options\n * @param {string} [opts.rpcUrl] - Solana RPC URL (overrides provider config)\n * @param {string} [opts.policyId] - Gas sponsorship policy ID (overrides provider config)\n * @param {string} [opts.walletAddress] - Specific wallet address to use (defaults to first wallet)\n * @param {Parameters<Connection[\"confirmTransaction\"]>[1]} [opts.confirmationOptions] - Transaction confirmation options\n * @returns {UseAlchemySolanaTransactionResult} Hook result with transaction functions and state\n *\n * @example Simple SOL transfer\n * ```tsx\n * const { sendTransactionAsync, isPending, error, data } = useAlchemySolanaTransaction({\n * rpcUrl: 'https://solana-mainnet.g.alchemy.com/v2/your-api-key',\n * policyId: 'your-policy-id', // Optional: for gas sponsorship\n * });\n *\n * const handleTransfer = async () => {\n * try {\n * const result = await sendTransactionAsync({\n * transfer: {\n * amount: 1_000_000_000, // 1 SOL in lamports\n * toAddress: 'recipient-address',\n * },\n * });\n * console.log('Transaction hash:', result.hash);\n * } catch (err) {\n * console.error('Transaction failed:', err);\n * }\n * };\n * ```\n *\n * @example Custom instructions\n * ```tsx\n * import { SystemProgram, PublicKey } from '@solana/web3.js';\n *\n * const { sendTransactionAsync } = useAlchemySolanaTransaction();\n *\n * // Build your custom instructions\n * const transferIx = SystemProgram.transfer({\n * fromPubkey: new PublicKey(walletAddress),\n * toPubkey: new PublicKey(recipientAddress),\n * lamports: 1_000_000,\n * });\n *\n * // Pass instructions array to the hook\n * const result = await sendTransactionAsync({\n * instructions: [transferIx],\n * });\n * ```\n *\n * @example With provider configuration\n * ```tsx\n * // In your provider setup\n * <AlchemyProvider\n * solanaRpcUrl=\"https://solana-mainnet.g.alchemy.com/v2/...\"\n * solanaPolicyId=\"your-solana-policy-id\"\n * >\n * <YourApp />\n * </AlchemyProvider>\n *\n * // In your component - uses provider config automatically\n * const { sendTransactionAsync } = useAlchemySolanaTransaction();\n * ```\n */\nexport function useAlchemySolanaTransaction(\n opts: UseAlchemySolanaTransactionOptions = {},\n): UseAlchemySolanaTransactionResult {\n const config = useAlchemyConfig();\n const { wallets } = useWallets();\n const { signTransaction } = useSignTransaction();\n\n // Resolve the Privy Solana wallet to use\n const embeddedWallet = useMemo(() => {\n if (opts.walletAddress) {\n const w = wallets.find((w) => w.address === opts.walletAddress);\n if (!w) throw new Error(\"Specified Solana wallet not found\");\n return w;\n }\n return wallets[0];\n }, [wallets, opts.walletAddress]);\n\n // Build Solana connection from rpcUrl (hook override or provider default)\n const connection = useMemo(() => {\n const url = opts.rpcUrl || config.solanaRpcUrl;\n return url ? new Connection(url) : null;\n }, [opts.rpcUrl, config.solanaRpcUrl]);\n\n const [isPending, setIsPending] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [data, setData] = useState<void | SolanaTransactionResult>(undefined);\n\n const resolvedPolicyId = useMemo(() => {\n if (opts.policyId != null) return opts.policyId || undefined;\n // Use solanaPolicyId from config, fallback to policyId for backwards compat\n const configPolicy = config.solanaPolicyId || config.policyId;\n return Array.isArray(configPolicy) ? configPolicy[0] : configPolicy;\n }, [opts.policyId, config.solanaPolicyId, config.policyId]);\n\n const mapTransformInstructions = useMemo(() => {\n const addSponsorship: TransformInstruction = async (instructions) => {\n const policyId = resolvedPolicyId;\n if (!policyId)\n throw new Error(\n \"Gas sponsorship requires a policyId (see provider or hook options).\",\n );\n const localConnection = connection || missing(\"connection\");\n const fromAddress = embeddedWallet?.address;\n if (!fromAddress) throw new Error(\"No embedded Solana wallet connected\");\n return createSolanaSponsoredTransaction(\n instructions,\n localConnection,\n policyId,\n fromAddress,\n );\n };\n const createTx: TransformInstruction = async (instructions) => {\n const localConnection = connection || missing(\"connection\");\n const fromAddress = embeddedWallet?.address;\n if (!fromAddress) throw new Error(\"No embedded Solana wallet connected\");\n return createSolanaTransaction(\n instructions,\n localConnection,\n fromAddress,\n );\n };\n const defaultTransform =\n !!resolvedPolicyId && !config.disableSponsorship\n ? addSponsorship\n : createTx;\n return {\n addSponsorship,\n createTransaction: createTx,\n default: defaultTransform,\n } as const;\n }, [\n resolvedPolicyId,\n config.disableSponsorship,\n connection,\n embeddedWallet?.address,\n ]);\n\n const buildInstructions = useCallback(\n (\n params: SolanaTransactionParams,\n fromAddress: string,\n ): TransactionInstruction[] => {\n if (\"instructions\" in params) return params.instructions;\n return [\n SystemProgram.transfer({\n fromPubkey: new PublicKey(fromAddress),\n toPubkey: new PublicKey(params.transfer.toAddress),\n lamports:\n typeof params.transfer.amount === \"bigint\"\n ? Number(params.transfer.amount) // web3.js currently expects number; callers can pass bigint safely\n : params.transfer.amount,\n }),\n ];\n },\n [],\n );\n\n function toUnsignedBytes(tx: VersionedTransaction | Transaction): Uint8Array {\n // Serialize the full transaction structure (with placeholder signatures)\n // Privy expects the complete transaction format, not just the message\n if (tx instanceof VersionedTransaction) {\n // VersionedTransaction.serialize() includes signature slots\n return tx.serialize();\n }\n // Legacy Transaction: serialize without requiring all signatures\n const buf = tx.serialize({\n requireAllSignatures: false,\n verifySignatures: false,\n });\n return buf instanceof Uint8Array ? buf : new Uint8Array(buf);\n }\n\n const sendTransactionAsync = useCallback(\n async (\n params: SolanaTransactionParams,\n ): Promise<SolanaTransactionResult> => {\n setIsPending(true);\n setError(null);\n try {\n const localConnection = connection || missing(\"connection\");\n if (!embeddedWallet?.address) {\n throw new Error(\"No Solana wallet connected via Privy\");\n }\n\n const fromAddress = embeddedWallet.address;\n const {\n transactionComponents: { preSend, transformInstruction } = {},\n confirmationOptions,\n } = params;\n\n const instructions = buildInstructions(params, fromAddress);\n\n let transaction: VersionedTransaction | Transaction;\n if (transformInstruction) {\n transaction = await transformInstruction(instructions);\n } else {\n transaction = await mapTransformInstructions.default(instructions);\n }\n\n transaction = (await preSend?.(transaction)) || transaction;\n\n // Sign the transaction using Privy's useSignTransaction hook\n const unsignedBytes = toUnsignedBytes(transaction);\n const { signedTransaction } = await signTransaction({\n transaction: unsignedBytes,\n wallet: embeddedWallet,\n });\n\n // Broadcast the signed transaction\n const hash = await localConnection.sendRawTransaction(\n signedTransaction,\n { skipPreflight: false },\n );\n\n if (confirmationOptions || opts.confirmationOptions) {\n await localConnection.confirmTransaction(\n hash,\n confirmationOptions || opts.confirmationOptions,\n );\n }\n\n setData({ hash });\n return { hash };\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n setError(e);\n throw e;\n } finally {\n setIsPending(false);\n }\n },\n [\n embeddedWallet,\n connection,\n buildInstructions,\n mapTransformInstructions,\n opts.confirmationOptions,\n signTransaction,\n ],\n );\n\n const sendTransaction = useCallback(\n (params: SolanaTransactionParams) => {\n // Prevent unhandled rejection warnings; error state is already set in sendTransactionAsync\n sendTransactionAsync(params).catch(() => {});\n },\n [sendTransactionAsync],\n );\n\n const reset = useCallback(() => {\n setIsPending(false);\n setError(null);\n setData(undefined);\n }, []);\n\n return {\n connection,\n data,\n isPending,\n error,\n reset,\n sendTransaction,\n sendTransactionAsync,\n };\n}\n\nfunction missing(message: string): never {\n throw new Error(message);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"useAlchemySolanaTransaction.js","sourceRoot":"","sources":["../../../src/hooks/useAlchemySolanaTransaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,OAAO,EA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,wBAAwB;QACxB,IAAI,CAAC,mBAAmB;QACxB,eAAe;KAChB,CACF,CAAC;IAEF,MAAM,eAAe,GAAG,WAAW,CACjC,CAAC,MAA+B,EAAE,EAAE;QAClC,2FAA2F;QAC3F,oBAAoB,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IAC/C,CAAC,EACD,CAAC,oBAAoB,CAAC,CACvB,CAAC;IAEF,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,YAAY,CAAC,KAAK,CAAC,CAAC;QACpB,QAAQ,CAAC,IAAI,CAAC,CAAC;QACf,OAAO,CAAC,SAAS,CAAC,CAAC;IACrB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO;QACL,UAAU;QACV,IAAI;QACJ,SAAS;QACT,KAAK;QACL,KAAK;QACL,eAAe;QACf,oBAAoB;KACrB,CAAC;AACJ,CAAC;AAED,SAAS,OAAO,CAAC,OAAe;IAC9B,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;AAC3B,CAAC","sourcesContent":["import { useCallback, useMemo, useState } from \"react\";\nimport {\n Connection,\n PublicKey,\n SystemProgram,\n Transaction,\n TransactionInstruction,\n VersionedTransaction,\n} from \"@solana/web3.js\";\nimport { useAlchemyConfig } from \"../context/AlchemyContext.js\";\nimport { createSolanaSponsoredTransaction } from \"../util/createSolanaSponsoredTransaction.js\";\nimport { useSignTransaction, useWallets } from \"@privy-io/react-auth/solana\";\nimport { createSolanaTransaction } from \"../util/createSolanaTransaction.js\";\n\n/**\n * Type helper for values that can be synchronous or asynchronous\n *\n * @template T - The value type\n */\nexport type PromiseOrValue<T> = T | Promise<T>;\n\n/**\n * Callback to modify a transaction before it's signed\n * Useful for adding additional signatures or metadata\n *\n * @param transaction - The unsigned transaction to modify\n * @returns The modified transaction\n */\nexport type PreSend = (\n this: void,\n transaction: VersionedTransaction | Transaction,\n) => PromiseOrValue<VersionedTransaction | Transaction>;\n\n/**\n * Callback to transform instructions into a custom transaction\n * Useful for advanced transaction construction (e.g., multi-sig, custom versioning)\n *\n * @param instructions - Array of Solana transaction instructions\n * @returns Constructed transaction (legacy or versioned)\n */\nexport type TransformInstruction = (\n this: void,\n instructions: TransactionInstruction[],\n) => PromiseOrValue<Transaction | VersionedTransaction>;\n\n/**\n * Optional transaction lifecycle hooks for advanced use cases\n */\nexport type SolanaTransactionParamOptions = {\n /** Hook called before signing the transaction */\n preSend?: PreSend;\n /** Custom transaction builder from instructions */\n transformInstruction?: TransformInstruction;\n};\n\n/**\n * Parameters for sending a Solana transaction\n * Supports either a simple transfer or custom instructions\n */\nexport type SolanaTransactionParams =\n | {\n /** Simple SOL transfer parameters */\n transfer: {\n /** Amount in lamports (accepts number or bigint) */\n amount: number | bigint;\n /** Recipient's base58-encoded address */\n toAddress: string;\n };\n /** Optional transaction lifecycle hooks */\n transactionComponents?: SolanaTransactionParamOptions;\n /** Options for confirming the transaction on-chain */\n confirmationOptions?: Parameters<Connection[\"confirmTransaction\"]>[1];\n }\n | {\n /** Custom Solana transaction instructions */\n instructions: TransactionInstruction[];\n /** Optional transaction lifecycle hooks */\n transactionComponents?: SolanaTransactionParamOptions;\n /** Options for confirming the transaction on-chain */\n confirmationOptions?: Parameters<Connection[\"confirmTransaction\"]>[1];\n };\n\n/**\n * Result of a successful Solana transaction\n */\nexport interface SolanaTransactionResult {\n /** Base58-encoded transaction signature (hash) */\n hash: string;\n}\n\n/**\n * Configuration options for useAlchemySolanaTransaction hook\n */\nexport interface UseAlchemySolanaTransactionOptions {\n /** Solana RPC URL (overrides provider config) */\n rpcUrl?: string;\n /** Gas sponsorship policy ID (overrides provider config) */\n policyId?: string | void;\n /** Transaction confirmation options */\n confirmationOptions?: Parameters<Connection[\"confirmTransaction\"]>[1];\n /** Specific wallet address to use (defaults to first available wallet) */\n walletAddress?: string;\n}\n\n/**\n * Return type of useAlchemySolanaTransaction hook\n */\nexport interface UseAlchemySolanaTransactionResult {\n /** Active Solana connection instance */\n readonly connection: Connection | null;\n /** Transaction result if successful */\n readonly data: void | SolanaTransactionResult;\n /** Whether a transaction is currently being sent */\n readonly isPending: boolean;\n /** Error if transaction failed */\n readonly error: Error | null;\n /** Reset hook state (clears error, data, isPending) */\n reset(): void;\n /** Send transaction (fire-and-forget, errors caught internally) */\n sendTransaction(params: SolanaTransactionParams): void;\n /** Send transaction and await result (throws on error) */\n sendTransactionAsync(\n params: SolanaTransactionParams,\n ): Promise<SolanaTransactionResult>;\n}\n\n/**\n * Hook to send Solana transactions with optional gas sponsorship via Alchemy\n * Works with Privy's Solana wallet integration for signing transactions\n * Supports both simple transfers and custom instruction sets\n *\n * @param {UseAlchemySolanaTransactionOptions} [opts] - Configuration options\n * @param {string} [opts.rpcUrl] - Solana RPC URL (overrides provider config)\n * @param {string} [opts.policyId] - Gas sponsorship policy ID (overrides provider config)\n * @param {string} [opts.walletAddress] - Specific wallet address to use (defaults to first wallet)\n * @param {Parameters<Connection[\"confirmTransaction\"]>[1]} [opts.confirmationOptions] - Transaction confirmation options\n * @returns {UseAlchemySolanaTransactionResult} Hook result with transaction functions and state\n *\n * @example Simple SOL transfer\n * ```tsx\n * const { sendTransactionAsync, isPending, error, data } = useAlchemySolanaTransaction({\n * rpcUrl: 'https://solana-mainnet.g.alchemy.com/v2/your-api-key',\n * policyId: 'your-policy-id', // Optional: for gas sponsorship\n * });\n *\n * const handleTransfer = async () => {\n * try {\n * const result = await sendTransactionAsync({\n * transfer: {\n * amount: 1_000_000_000, // 1 SOL in lamports\n * toAddress: 'recipient-address',\n * },\n * });\n * console.log('Transaction hash:', result.hash);\n * } catch (err) {\n * console.error('Transaction failed:', err);\n * }\n * };\n * ```\n *\n * @example Custom instructions\n * ```tsx\n * import { SystemProgram, PublicKey } from '@solana/web3.js';\n *\n * const { sendTransactionAsync } = useAlchemySolanaTransaction();\n *\n * // Build your custom instructions\n * const transferIx = SystemProgram.transfer({\n * fromPubkey: new PublicKey(walletAddress),\n * toPubkey: new PublicKey(recipientAddress),\n * lamports: 1_000_000,\n * });\n *\n * // Pass instructions array to the hook\n * const result = await sendTransactionAsync({\n * instructions: [transferIx],\n * });\n * ```\n *\n * @example With provider configuration\n * ```tsx\n * // In your provider setup\n * <AlchemyProvider\n * solanaRpcUrl=\"https://solana-mainnet.g.alchemy.com/v2/...\"\n * solanaPolicyId=\"your-solana-policy-id\"\n * >\n * <YourApp />\n * </AlchemyProvider>\n *\n * // In your component - uses provider config automatically\n * const { sendTransactionAsync } = useAlchemySolanaTransaction();\n * ```\n */\nexport function useAlchemySolanaTransaction(\n opts: UseAlchemySolanaTransactionOptions = {},\n): UseAlchemySolanaTransactionResult {\n const config = useAlchemyConfig();\n const { wallets } = useWallets();\n const { signTransaction } = useSignTransaction();\n\n // Resolve the Privy Solana wallet to use\n const embeddedWallet = useMemo(() => {\n if (opts.walletAddress) {\n const w = wallets.find((w) => w.address === opts.walletAddress);\n if (!w) throw new Error(\"Specified Solana wallet not found\");\n return w;\n }\n return wallets[0];\n }, [wallets, opts.walletAddress]);\n\n // Build Solana connection from rpcUrl (hook override or provider default)\n const connection = useMemo(() => {\n const url = opts.rpcUrl || config.solanaRpcUrl;\n return url ? new Connection(url) : null;\n }, [opts.rpcUrl, config.solanaRpcUrl]);\n\n const [isPending, setIsPending] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [data, setData] = useState<void | SolanaTransactionResult>(undefined);\n\n const resolvedPolicyId = useMemo(() => {\n if (opts.policyId != null) return opts.policyId || undefined;\n // Use solanaPolicyId from config, fallback to policyId for backwards compat\n const configPolicy = config.solanaPolicyId || config.policyId;\n return Array.isArray(configPolicy) ? configPolicy[0] : configPolicy;\n }, [opts.policyId, config.solanaPolicyId, config.policyId]);\n\n const mapTransformInstructions = useMemo(() => {\n const addSponsorship: TransformInstruction = async (instructions) => {\n const policyId = resolvedPolicyId;\n if (!policyId)\n throw new Error(\n \"Gas sponsorship requires a policyId (see provider or hook options).\",\n );\n const localConnection = connection || missing(\"connection\");\n const fromAddress = embeddedWallet?.address;\n if (!fromAddress) throw new Error(\"No embedded Solana wallet connected\");\n return createSolanaSponsoredTransaction(\n instructions,\n localConnection,\n policyId,\n fromAddress,\n );\n };\n const createTx: TransformInstruction = async (instructions) => {\n const localConnection = connection || missing(\"connection\");\n const fromAddress = embeddedWallet?.address;\n if (!fromAddress) throw new Error(\"No embedded Solana wallet connected\");\n return createSolanaTransaction(\n instructions,\n localConnection,\n fromAddress,\n );\n };\n const defaultTransform =\n !!resolvedPolicyId && !config.disableSponsorship\n ? addSponsorship\n : createTx;\n return {\n addSponsorship,\n createTransaction: createTx,\n default: defaultTransform,\n } as const;\n }, [\n resolvedPolicyId,\n config.disableSponsorship,\n connection,\n embeddedWallet?.address,\n ]);\n\n const buildInstructions = useCallback(\n (\n params: SolanaTransactionParams,\n fromAddress: string,\n ): TransactionInstruction[] => {\n if (\"instructions\" in params) return params.instructions;\n return [\n SystemProgram.transfer({\n fromPubkey: new PublicKey(fromAddress),\n toPubkey: new PublicKey(params.transfer.toAddress),\n lamports:\n typeof params.transfer.amount === \"bigint\"\n ? Number(params.transfer.amount) // web3.js currently expects number; callers can pass bigint safely\n : params.transfer.amount,\n }),\n ];\n },\n [],\n );\n\n function toUnsignedBytes(tx: VersionedTransaction | Transaction): Uint8Array {\n // Serialize the full transaction structure (with placeholder signatures)\n // Privy expects the complete transaction format, not just the message\n if (tx instanceof VersionedTransaction) {\n // VersionedTransaction.serialize() includes signature slots\n return tx.serialize();\n }\n // Legacy Transaction: serialize without requiring all signatures\n const buf = tx.serialize({\n requireAllSignatures: false,\n verifySignatures: false,\n });\n return buf instanceof Uint8Array ? buf : new Uint8Array(buf);\n }\n\n const sendTransactionAsync = useCallback(\n async (\n params: SolanaTransactionParams,\n ): Promise<SolanaTransactionResult> => {\n setIsPending(true);\n setError(null);\n try {\n const localConnection = connection || missing(\"connection\");\n if (!embeddedWallet?.address) {\n throw new Error(\"No Solana wallet connected via Privy\");\n }\n\n const fromAddress = embeddedWallet.address;\n const {\n transactionComponents: { preSend, transformInstruction } = {},\n confirmationOptions,\n } = params;\n\n const instructions = buildInstructions(params, fromAddress);\n\n let transaction: VersionedTransaction | Transaction;\n if (transformInstruction) {\n transaction = await transformInstruction(instructions);\n } else {\n transaction = await mapTransformInstructions.default(instructions);\n }\n\n transaction = (await preSend?.(transaction)) || transaction;\n\n // Sign the transaction using Privy's useSignTransaction hook\n const unsignedBytes = toUnsignedBytes(transaction);\n const { signedTransaction } = await signTransaction({\n transaction: unsignedBytes,\n wallet: embeddedWallet,\n });\n\n // Broadcast the signed transaction\n const hash = await localConnection.sendRawTransaction(\n signedTransaction,\n { skipPreflight: false },\n );\n\n if (confirmationOptions || opts.confirmationOptions) {\n await localConnection.confirmTransaction(\n hash,\n confirmationOptions || opts.confirmationOptions,\n );\n }\n\n setData({ hash });\n return { hash };\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n setError(e);\n throw e;\n } finally {\n setIsPending(false);\n }\n },\n [\n embeddedWallet,\n connection,\n buildInstructions,\n mapTransformInstructions,\n opts.confirmationOptions,\n signTransaction,\n ],\n );\n\n const sendTransaction = useCallback(\n (params: SolanaTransactionParams) => {\n // Prevent unhandled rejection warnings; error state is already set in sendTransactionAsync\n sendTransactionAsync(params).catch(() => {});\n },\n [sendTransactionAsync],\n );\n\n const reset = useCallback(() => {\n setIsPending(false);\n setError(null);\n setData(undefined);\n }, []);\n\n return {\n connection,\n data,\n isPending,\n error,\n reset,\n sendTransaction,\n sendTransactionAsync,\n };\n}\n\nfunction missing(message: string): never {\n throw new Error(message);\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React Native stub for WebProvider
|
|
3
|
+
* This file prevents Metro from importing web-specific code
|
|
4
|
+
*/
|
|
5
|
+
export function AlchemyProvider() {
|
|
6
|
+
throw new Error("WebProvider is not available in React Native. " +
|
|
7
|
+
'Import from "@account-kit/privy-integration/react-native" instead.');
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=WebProvider.native.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"WebProvider.native.js","sourceRoot":"","sources":["../../../src/providers/WebProvider.native.tsx"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,UAAU,eAAe;IAC7B,MAAM,IAAI,KAAK,CACb,gDAAgD;QAC9C,oEAAoE,CACvE,CAAC;AACJ,CAAC","sourcesContent":["/**\n * React Native stub for WebProvider\n * This file prevents Metro from importing web-specific code\n */\n\nexport function AlchemyProvider() {\n throw new Error(\n \"WebProvider is not available in React Native. \" +\n 'Import from \"@account-kit/privy-integration/react-native\" instead.',\n );\n}\n"]}
|
package/dist/esm/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "4.73.1-alpha.
|
|
1
|
+
export declare const VERSION = "4.73.1-alpha.11";
|
package/dist/esm/version.js
CHANGED
package/dist/esm/version.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,yBAAyB;AACzB,MAAM,CAAC,MAAM,OAAO,GAAG,
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,yBAAyB;AACzB,MAAM,CAAC,MAAM,OAAO,GAAG,iBAAiB,CAAC","sourcesContent":["// This file is autogenerated by inject-version.ts. Any changes will be\n// overwritten on commit!\nexport const VERSION = \"4.73.1-alpha.11\";\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Provider.native.d.ts","sourceRoot":"","sources":["../../src/Provider.native.tsx"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,wBAAgB,eAAe,SAK9B;AAED,wBAAgB,gBAAgB,SAK/B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-native.d.ts","sourceRoot":"","sources":["../../../src/adapters/react-native.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"react-native.d.ts","sourceRoot":"","sources":["../../../src/adapters/react-native.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,YAAY,EAAkC,MAAM,YAAY,CAAC;AAY/E;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,YAmGhC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"web.native.d.ts","sourceRoot":"","sources":["../../../src/adapters/web.native.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,eAAO,MAAM,UAAU,MAAO,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAlchemyClient.d.ts","sourceRoot":"","sources":["../../../src/hooks/useAlchemyClient.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,iBAAiB,EACvB,MAAM,4BAA4B,CAAC;AAUpC;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB;
|
|
1
|
+
{"version":3,"file":"useAlchemyClient.d.ts","sourceRoot":"","sources":["../../../src/hooks/useAlchemyClient.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,iBAAiB,EACvB,MAAM,4BAA4B,CAAC;AAUpC;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB;qBAOU,OAAO,CAAC,iBAAiB,CAAC;EAkHnE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"WebProvider.native.d.ts","sourceRoot":"","sources":["../../../src/providers/WebProvider.native.tsx"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,wBAAgB,eAAe,SAK9B"}
|
package/dist/types/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const VERSION = "4.73.1-alpha.
|
|
1
|
+
export declare const VERSION = "4.73.1-alpha.11";
|
|
2
2
|
//# sourceMappingURL=version.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,OAAO,
|
|
1
|
+
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,OAAO,oBAAoB,CAAC"}
|