@stableflow/utils-solana 3.0.0-beta-02a59f37a0-20260515

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 ADDED
@@ -0,0 +1,31 @@
1
+ # @stableflow/utils-solana
2
+
3
+ Solana utilities for the StableFlow SDK: RPC fallback connections and associated-token-account helpers.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @stableflow/utils-solana @stableflow/core
9
+ ```
10
+
11
+ **Peer dependencies** (install in your app):
12
+
13
+ - `@solana/spl-token` ^0.4.14
14
+ - `@solana/web3.js` ^1.98.4
15
+
16
+ This package is primarily used by `@stableflow/wallet-solana` and some cross-chain wallet paths. Application code rarely imports it directly.
17
+
18
+ ## Main exports
19
+
20
+ | Export | Description |
21
+ |--------|-------------|
22
+ | `createSolanaFallbackConnection` | `Connection` proxy with automatic RPC failover |
23
+ | `getAvailableSolanaRpcUrl` | Health-check and return a working RPC URL |
24
+ | `getDestinationAssociatedTokenAddress` | Resolve or detect need to create recipient ATA |
25
+
26
+ See `dist/index.d.ts` after `pnpm build`.
27
+
28
+ ## See also
29
+
30
+ - [Developer Guide](../../DEVELOPER_GUIDE.md)
31
+ - [@stableflow/wallet-solana](../wallet-solana/README.md)
@@ -0,0 +1,12 @@
1
+ import { Connection } from '@solana/web3.js';
2
+
3
+ declare const createSolanaFallbackConnection: (rpcUrls: string[]) => Connection;
4
+ declare const getAvailableSolanaRpcUrl: (options?: {
5
+ isQuerySignature?: boolean;
6
+ }) => Promise<string>;
7
+ declare const getDestinationAssociatedTokenAddress: (params: any) => Promise<{
8
+ needCreateTokenAccount: boolean;
9
+ associatedTokenAddress: string;
10
+ }>;
11
+
12
+ export { createSolanaFallbackConnection, getAvailableSolanaRpcUrl, getDestinationAssociatedTokenAddress };
@@ -0,0 +1,12 @@
1
+ import { Connection } from '@solana/web3.js';
2
+
3
+ declare const createSolanaFallbackConnection: (rpcUrls: string[]) => Connection;
4
+ declare const getAvailableSolanaRpcUrl: (options?: {
5
+ isQuerySignature?: boolean;
6
+ }) => Promise<string>;
7
+ declare const getDestinationAssociatedTokenAddress: (params: any) => Promise<{
8
+ needCreateTokenAccount: boolean;
9
+ associatedTokenAddress: string;
10
+ }>;
11
+
12
+ export { createSolanaFallbackConnection, getAvailableSolanaRpcUrl, getDestinationAssociatedTokenAddress };
package/dist/index.js ADDED
@@ -0,0 +1,164 @@
1
+ 'use strict';
2
+
3
+ var splToken = require('@solana/spl-token');
4
+ var web3_js = require('@solana/web3.js');
5
+ var core = require('@stableflow/core');
6
+
7
+ // src/index.ts
8
+ var SOLANA_RPC_TIMEOUT_MS = 5e3;
9
+ var withTimeout = async (promise, timeoutMs) => {
10
+ return await Promise.race([
11
+ promise,
12
+ new Promise((_, reject) => {
13
+ setTimeout(() => reject(new Error(`Solana RPC timeout after ${timeoutMs}ms`)), timeoutMs);
14
+ })
15
+ ]);
16
+ };
17
+ var isRpcUnavailableError = (error) => {
18
+ const message = error?.message?.toLowerCase?.() || "";
19
+ return message.includes("fetch") || message.includes("timeout") || message.includes("failed to fetch") || message.includes("503") || message.includes("429") || message.includes("403") || message.includes("401") || message.includes("network");
20
+ };
21
+ var createSolanaFallbackConnection = (rpcUrls) => {
22
+ if (!rpcUrls?.length) {
23
+ throw new Error("No Solana RPC URLs configured");
24
+ }
25
+ const cs = new core.Csl(core.OpenAPI.DEBUG);
26
+ const csl = cs.log;
27
+ const connections = rpcUrls.map((rpcUrl) => new web3_js.Connection(rpcUrl, {
28
+ commitment: "confirmed"
29
+ }));
30
+ let activeIndex = 0;
31
+ let active = connections[activeIndex];
32
+ return new Proxy(connections[0], {
33
+ get(_, prop, receiver) {
34
+ const activeValue = Reflect.get(active, prop, receiver);
35
+ if (typeof activeValue !== "function") {
36
+ return activeValue;
37
+ }
38
+ return (...args) => {
39
+ const callAtIndex = (index) => {
40
+ const targetConnection = connections[index];
41
+ const method = targetConnection[prop];
42
+ if (typeof method !== "function") {
43
+ return method;
44
+ }
45
+ return method.apply(targetConnection, args);
46
+ };
47
+ const tryWithFallback = async () => {
48
+ let index = activeIndex;
49
+ let attempts = 0;
50
+ let lastError = null;
51
+ while (attempts < connections.length) {
52
+ try {
53
+ const result = await callAtIndex(index);
54
+ activeIndex = index;
55
+ active = connections[activeIndex];
56
+ return result;
57
+ } catch (error) {
58
+ lastError = error;
59
+ if (!isRpcUnavailableError(error)) {
60
+ throw error;
61
+ }
62
+ const nextIndex = (index + 1) % connections.length;
63
+ csl(
64
+ "solana rpc fallback",
65
+ "yellow-400",
66
+ "rpc unavailable, switching endpoint (%d -> %d): %o",
67
+ index,
68
+ nextIndex,
69
+ error
70
+ );
71
+ index = nextIndex;
72
+ attempts += 1;
73
+ }
74
+ }
75
+ throw lastError;
76
+ };
77
+ return tryWithFallback();
78
+ };
79
+ }
80
+ });
81
+ };
82
+ var probeRpcHealth = async (rpcUrl) => {
83
+ const response = await withTimeout(fetch(rpcUrl, {
84
+ method: "POST",
85
+ headers: {
86
+ "Content-Type": "application/json"
87
+ },
88
+ body: JSON.stringify({
89
+ jsonrpc: "2.0",
90
+ id: 1,
91
+ method: "getLatestBlockhash",
92
+ params: [{ commitment: "confirmed" }]
93
+ })
94
+ }), SOLANA_RPC_TIMEOUT_MS);
95
+ if (!response.ok) {
96
+ throw new Error(`Solana RPC unavailable: ${rpcUrl}, status=${response.status}`);
97
+ }
98
+ const body = await response.json();
99
+ if (body?.error) {
100
+ throw new Error(
101
+ `Solana RPC error: ${rpcUrl}, code=${body.error.code}, message=${body.error.message || "unknown"}`
102
+ );
103
+ }
104
+ if (!body?.result) {
105
+ throw new Error(`Solana RPC invalid response: ${rpcUrl}`);
106
+ }
107
+ };
108
+ var getAvailableSolanaRpcUrl = async (options) => {
109
+ const cs = new core.Csl(core.OpenAPI.DEBUG);
110
+ const csl = cs.log;
111
+ const rpcUrls = core.getChainRpcUrl("Solana").rpcUrls;
112
+ if (!rpcUrls?.length) {
113
+ throw new Error("No Solana RPC URLs configured");
114
+ }
115
+ const formatRpcUrl = (rpcUrl) => {
116
+ return rpcUrl;
117
+ };
118
+ for (const rpcUrl of rpcUrls) {
119
+ try {
120
+ await probeRpcHealth(rpcUrl);
121
+ return formatRpcUrl(rpcUrl);
122
+ } catch (error) {
123
+ csl("solana rpc health", "yellow-400", "rpc health check failed: %o", error);
124
+ }
125
+ }
126
+ return formatRpcUrl(rpcUrls[0]);
127
+ };
128
+ var getDestinationAssociatedTokenAddress = async (params) => {
129
+ const {
130
+ recipient,
131
+ toToken
132
+ } = params;
133
+ const cs = new core.Csl(core.OpenAPI.DEBUG);
134
+ const csl = cs.log;
135
+ const result = {
136
+ needCreateTokenAccount: false,
137
+ associatedTokenAddress: ""
138
+ };
139
+ if (toToken.chainType !== "sol") {
140
+ return result;
141
+ }
142
+ try {
143
+ const connection = createSolanaFallbackConnection(core.getChainRpcUrl("Solana").rpcUrls);
144
+ const wallet = new web3_js.PublicKey(recipient);
145
+ const TOKEN_MINT = new web3_js.PublicKey(toToken.contractAddress);
146
+ const ata = splToken.getAssociatedTokenAddressSync(TOKEN_MINT, wallet);
147
+ const accountInfo = await connection.getAccountInfo(ata);
148
+ csl("getDestinationAssociatedTokenAddress", "purple-400", "accountInfo: %o", accountInfo);
149
+ if (!accountInfo) {
150
+ result.needCreateTokenAccount = true;
151
+ return result;
152
+ }
153
+ result.associatedTokenAddress = ata.toBase58();
154
+ } catch (error) {
155
+ csl("getDestinationAssociatedTokenAddress", "red-500", "getDestinationAssociatedTokenAddress failed: %o", error);
156
+ }
157
+ return result;
158
+ };
159
+
160
+ exports.createSolanaFallbackConnection = createSolanaFallbackConnection;
161
+ exports.getAvailableSolanaRpcUrl = getAvailableSolanaRpcUrl;
162
+ exports.getDestinationAssociatedTokenAddress = getDestinationAssociatedTokenAddress;
163
+ //# sourceMappingURL=index.js.map
164
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":["Csl","OpenAPI","Connection","getChainRpc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MAAM,EAAA,GAAK,IAAIH,QAAA,CAAIC,YAAA,CAAQ,KAAK,CAAA;AAChC,EAAA,MAAM,MAAM,EAAA,CAAG,GAAA;AAEf,EAAA,MAAM,MAAA,GAAS;AAAA,IACb,sBAAA,EAAwB,KAAA;AAAA,IACxB,sBAAA,EAAwB;AAAA,GAC1B;AAEA,EAAA,IAAI,OAAA,CAAQ,cAAc,KAAA,EAAO;AAC/B,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,IAAI;AACF,IAAA,MAAM,UAAA,GAAa,8BAAA,CAA+BE,mBAAA,CAAe,QAAQ,EAAE,OAAO,CAAA;AAClF,IAAA,MAAM,MAAA,GAAS,IAAIC,iBAAA,CAAU,SAAS,CAAA;AACtC,IAAA,MAAM,UAAA,GAAa,IAAIA,iBAAA,CAAU,OAAA,CAAQ,eAAe,CAAA;AAExD,IAAA,MAAM,GAAA,GAAMC,sCAAA,CAA8B,UAAA,EAAY,MAAM,CAAA;AAE5D,IAAA,MAAM,WAAA,GAAc,MAAM,UAAA,CAAW,cAAA,CAAe,GAAG,CAAA;AAEvD,IAAA,GAAA,CAAI,sCAAA,EAAwC,YAAA,EAAc,iBAAA,EAAmB,WAAW,CAAA;AAExF,IAAA,IAAI,CAAC,WAAA,EAAa;AAChB,MAAA,MAAA,CAAO,sBAAA,GAAyB,IAAA;AAChC,MAAA,OAAO,MAAA;AAAA,IACT;AAEA,IAAA,MAAA,CAAO,sBAAA,GAAyB,IAAI,QAAA,EAAS;AAAA,EAC/C,SAAS,KAAA,EAAO;AACd,IAAA,GAAA,CAAI,sCAAA,EAAwC,SAAA,EAAW,iDAAA,EAAmD,KAAK,CAAA;AAAA,EACjH;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["import { getAssociatedTokenAddressSync } from \"@solana/spl-token\";\nimport { Connection, PublicKey } from \"@solana/web3.js\";\nimport { Csl, OpenAPI, getChainRpcUrl } from '@stableflow/core';\n\nconst SOLANA_RPC_TIMEOUT_MS = 5000;\n\nconst withTimeout = async <T>(promise: Promise<T>, timeoutMs: number) => {\n return await Promise.race([\n promise,\n new Promise<T>((_, reject) => {\n setTimeout(() => reject(new Error(`Solana RPC timeout after ${timeoutMs}ms`)), timeoutMs);\n }),\n ]);\n};\n\nconst isRpcUnavailableError = (error: unknown) => {\n const message = (error as Error)?.message?.toLowerCase?.() || \"\";\n return (\n message.includes(\"fetch\") ||\n message.includes(\"timeout\") ||\n message.includes(\"failed to fetch\") ||\n message.includes(\"503\") ||\n message.includes(\"429\") ||\n message.includes(\"403\") ||\n message.includes(\"401\") ||\n message.includes(\"network\")\n );\n};\n\nexport const createSolanaFallbackConnection = (rpcUrls: string[]) => {\n if (!rpcUrls?.length) {\n throw new Error(\"No Solana RPC URLs configured\");\n }\n\n const cs = new Csl(OpenAPI.DEBUG);\n const csl = cs.log;\n const connections = rpcUrls.map((rpcUrl) => new Connection(rpcUrl, {\n commitment: \"confirmed\",\n }));\n let activeIndex = 0;\n let active: Connection = connections[activeIndex];\n\n return new Proxy(connections[0], {\n get(_, prop, receiver) {\n const activeValue = Reflect.get(active, prop, receiver);\n if (typeof activeValue !== \"function\") {\n return activeValue;\n }\n\n return (...args: unknown[]) => {\n const callAtIndex = (index: number) => {\n const targetConnection = connections[index];\n const method = (targetConnection as any)[prop];\n if (typeof method !== \"function\") {\n return method;\n }\n return method.apply(targetConnection, args);\n };\n\n const tryWithFallback = async () => {\n let index = activeIndex;\n let attempts = 0;\n let lastError: unknown = null;\n\n while (attempts < connections.length) {\n try {\n const result = await callAtIndex(index);\n activeIndex = index;\n active = connections[activeIndex];\n return result;\n } catch (error) {\n lastError = error;\n if (!isRpcUnavailableError(error)) {\n throw error;\n }\n\n const nextIndex = (index + 1) % connections.length;\n csl(\n \"solana rpc fallback\",\n \"yellow-400\",\n \"rpc unavailable, switching endpoint (%d -> %d): %o\",\n index,\n nextIndex,\n error\n );\n index = nextIndex;\n attempts += 1;\n }\n }\n\n throw lastError;\n };\n\n return tryWithFallback();\n };\n },\n }) as Connection;\n};\n\nconst probeRpcHealth = async (rpcUrl: string) => {\n const response = await withTimeout(fetch(rpcUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"getLatestBlockhash\",\n params: [{ commitment: \"confirmed\" }],\n }),\n }), SOLANA_RPC_TIMEOUT_MS);\n\n if (!response.ok) {\n throw new Error(`Solana RPC unavailable: ${rpcUrl}, status=${response.status}`);\n }\n\n const body = await response.json() as {\n result?: unknown;\n error?: { code?: number; message?: string; data?: unknown; };\n };\n\n if (body?.error) {\n throw new Error(\n `Solana RPC error: ${rpcUrl}, code=${body.error.code}, message=${body.error.message || \"unknown\"}`\n );\n }\n\n if (!body?.result) {\n throw new Error(`Solana RPC invalid response: ${rpcUrl}`);\n }\n};\n\nexport const getAvailableSolanaRpcUrl = async (options?: { isQuerySignature?: boolean; }) => {\n const { } = options || {};\n\n const cs = new Csl(OpenAPI.DEBUG);\n const csl = cs.log;\n\n const rpcUrls = getChainRpcUrl(\"Solana\").rpcUrls;\n if (!rpcUrls?.length) {\n throw new Error(\"No Solana RPC URLs configured\");\n }\n\n const formatRpcUrl = (rpcUrl: string) => {\n return rpcUrl;\n };\n\n for (const rpcUrl of rpcUrls) {\n try {\n await probeRpcHealth(rpcUrl);\n return formatRpcUrl(rpcUrl);\n } catch (error) {\n csl(\"solana rpc health\", \"yellow-400\", \"rpc health check failed: %o\", error);\n }\n }\n\n return formatRpcUrl(rpcUrls[0]);\n};\n\nexport const getDestinationAssociatedTokenAddress = async (params: any) => {\n const {\n recipient,\n toToken,\n } = params;\n\n const cs = new Csl(OpenAPI.DEBUG);\n const csl = cs.log;\n\n const result = {\n needCreateTokenAccount: false,\n associatedTokenAddress: \"\",\n };\n\n if (toToken.chainType !== \"sol\") {\n return result;\n }\n\n try {\n const connection = createSolanaFallbackConnection(getChainRpcUrl(\"Solana\").rpcUrls);\n const wallet = new PublicKey(recipient);\n const TOKEN_MINT = new PublicKey(toToken.contractAddress);\n\n const ata = getAssociatedTokenAddressSync(TOKEN_MINT, wallet);\n\n const accountInfo = await connection.getAccountInfo(ata);\n\n csl(\"getDestinationAssociatedTokenAddress\", \"purple-400\", \"accountInfo: %o\", accountInfo);\n\n if (!accountInfo) {\n result.needCreateTokenAccount = true;\n return result;\n }\n\n result.associatedTokenAddress = ata.toBase58();\n } catch (error) {\n csl(\"getDestinationAssociatedTokenAddress\", \"red-500\", \"getDestinationAssociatedTokenAddress failed: %o\", error);\n }\n\n return result;\n};\n"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,160 @@
1
+ import { getAssociatedTokenAddressSync } from '@solana/spl-token';
2
+ import { Connection, PublicKey } from '@solana/web3.js';
3
+ import { Csl, OpenAPI, getChainRpcUrl } from '@stableflow/core';
4
+
5
+ // src/index.ts
6
+ var SOLANA_RPC_TIMEOUT_MS = 5e3;
7
+ var withTimeout = async (promise, timeoutMs) => {
8
+ return await Promise.race([
9
+ promise,
10
+ new Promise((_, reject) => {
11
+ setTimeout(() => reject(new Error(`Solana RPC timeout after ${timeoutMs}ms`)), timeoutMs);
12
+ })
13
+ ]);
14
+ };
15
+ var isRpcUnavailableError = (error) => {
16
+ const message = error?.message?.toLowerCase?.() || "";
17
+ return message.includes("fetch") || message.includes("timeout") || message.includes("failed to fetch") || message.includes("503") || message.includes("429") || message.includes("403") || message.includes("401") || message.includes("network");
18
+ };
19
+ var createSolanaFallbackConnection = (rpcUrls) => {
20
+ if (!rpcUrls?.length) {
21
+ throw new Error("No Solana RPC URLs configured");
22
+ }
23
+ const cs = new Csl(OpenAPI.DEBUG);
24
+ const csl = cs.log;
25
+ const connections = rpcUrls.map((rpcUrl) => new Connection(rpcUrl, {
26
+ commitment: "confirmed"
27
+ }));
28
+ let activeIndex = 0;
29
+ let active = connections[activeIndex];
30
+ return new Proxy(connections[0], {
31
+ get(_, prop, receiver) {
32
+ const activeValue = Reflect.get(active, prop, receiver);
33
+ if (typeof activeValue !== "function") {
34
+ return activeValue;
35
+ }
36
+ return (...args) => {
37
+ const callAtIndex = (index) => {
38
+ const targetConnection = connections[index];
39
+ const method = targetConnection[prop];
40
+ if (typeof method !== "function") {
41
+ return method;
42
+ }
43
+ return method.apply(targetConnection, args);
44
+ };
45
+ const tryWithFallback = async () => {
46
+ let index = activeIndex;
47
+ let attempts = 0;
48
+ let lastError = null;
49
+ while (attempts < connections.length) {
50
+ try {
51
+ const result = await callAtIndex(index);
52
+ activeIndex = index;
53
+ active = connections[activeIndex];
54
+ return result;
55
+ } catch (error) {
56
+ lastError = error;
57
+ if (!isRpcUnavailableError(error)) {
58
+ throw error;
59
+ }
60
+ const nextIndex = (index + 1) % connections.length;
61
+ csl(
62
+ "solana rpc fallback",
63
+ "yellow-400",
64
+ "rpc unavailable, switching endpoint (%d -> %d): %o",
65
+ index,
66
+ nextIndex,
67
+ error
68
+ );
69
+ index = nextIndex;
70
+ attempts += 1;
71
+ }
72
+ }
73
+ throw lastError;
74
+ };
75
+ return tryWithFallback();
76
+ };
77
+ }
78
+ });
79
+ };
80
+ var probeRpcHealth = async (rpcUrl) => {
81
+ const response = await withTimeout(fetch(rpcUrl, {
82
+ method: "POST",
83
+ headers: {
84
+ "Content-Type": "application/json"
85
+ },
86
+ body: JSON.stringify({
87
+ jsonrpc: "2.0",
88
+ id: 1,
89
+ method: "getLatestBlockhash",
90
+ params: [{ commitment: "confirmed" }]
91
+ })
92
+ }), SOLANA_RPC_TIMEOUT_MS);
93
+ if (!response.ok) {
94
+ throw new Error(`Solana RPC unavailable: ${rpcUrl}, status=${response.status}`);
95
+ }
96
+ const body = await response.json();
97
+ if (body?.error) {
98
+ throw new Error(
99
+ `Solana RPC error: ${rpcUrl}, code=${body.error.code}, message=${body.error.message || "unknown"}`
100
+ );
101
+ }
102
+ if (!body?.result) {
103
+ throw new Error(`Solana RPC invalid response: ${rpcUrl}`);
104
+ }
105
+ };
106
+ var getAvailableSolanaRpcUrl = async (options) => {
107
+ const cs = new Csl(OpenAPI.DEBUG);
108
+ const csl = cs.log;
109
+ const rpcUrls = getChainRpcUrl("Solana").rpcUrls;
110
+ if (!rpcUrls?.length) {
111
+ throw new Error("No Solana RPC URLs configured");
112
+ }
113
+ const formatRpcUrl = (rpcUrl) => {
114
+ return rpcUrl;
115
+ };
116
+ for (const rpcUrl of rpcUrls) {
117
+ try {
118
+ await probeRpcHealth(rpcUrl);
119
+ return formatRpcUrl(rpcUrl);
120
+ } catch (error) {
121
+ csl("solana rpc health", "yellow-400", "rpc health check failed: %o", error);
122
+ }
123
+ }
124
+ return formatRpcUrl(rpcUrls[0]);
125
+ };
126
+ var getDestinationAssociatedTokenAddress = async (params) => {
127
+ const {
128
+ recipient,
129
+ toToken
130
+ } = params;
131
+ const cs = new Csl(OpenAPI.DEBUG);
132
+ const csl = cs.log;
133
+ const result = {
134
+ needCreateTokenAccount: false,
135
+ associatedTokenAddress: ""
136
+ };
137
+ if (toToken.chainType !== "sol") {
138
+ return result;
139
+ }
140
+ try {
141
+ const connection = createSolanaFallbackConnection(getChainRpcUrl("Solana").rpcUrls);
142
+ const wallet = new PublicKey(recipient);
143
+ const TOKEN_MINT = new PublicKey(toToken.contractAddress);
144
+ const ata = getAssociatedTokenAddressSync(TOKEN_MINT, wallet);
145
+ const accountInfo = await connection.getAccountInfo(ata);
146
+ csl("getDestinationAssociatedTokenAddress", "purple-400", "accountInfo: %o", accountInfo);
147
+ if (!accountInfo) {
148
+ result.needCreateTokenAccount = true;
149
+ return result;
150
+ }
151
+ result.associatedTokenAddress = ata.toBase58();
152
+ } catch (error) {
153
+ csl("getDestinationAssociatedTokenAddress", "red-500", "getDestinationAssociatedTokenAddress failed: %o", error);
154
+ }
155
+ return result;
156
+ };
157
+
158
+ export { createSolanaFallbackConnection, getAvailableSolanaRpcUrl, getDestinationAssociatedTokenAddress };
159
+ //# sourceMappingURL=index.mjs.map
160
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":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IAAI,GAAA,CAAI,OAAA,CAAQ,KAAK,CAAA;AAChC,EAAA,MAAM,MAAM,EAAA,CAAG,GAAA;AAEf,EAAA,MAAM,MAAA,GAAS;AAAA,IACb,sBAAA,EAAwB,KAAA;AAAA,IACxB,sBAAA,EAAwB;AAAA,GAC1B;AAEA,EAAA,IAAI,OAAA,CAAQ,cAAc,KAAA,EAAO;AAC/B,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,IAAI;AACF,IAAA,MAAM,UAAA,GAAa,8BAAA,CAA+B,cAAA,CAAe,QAAQ,EAAE,OAAO,CAAA;AAClF,IAAA,MAAM,MAAA,GAAS,IAAI,SAAA,CAAU,SAAS,CAAA;AACtC,IAAA,MAAM,UAAA,GAAa,IAAI,SAAA,CAAU,OAAA,CAAQ,eAAe,CAAA;AAExD,IAAA,MAAM,GAAA,GAAM,6BAAA,CAA8B,UAAA,EAAY,MAAM,CAAA;AAE5D,IAAA,MAAM,WAAA,GAAc,MAAM,UAAA,CAAW,cAAA,CAAe,GAAG,CAAA;AAEvD,IAAA,GAAA,CAAI,sCAAA,EAAwC,YAAA,EAAc,iBAAA,EAAmB,WAAW,CAAA;AAExF,IAAA,IAAI,CAAC,WAAA,EAAa;AAChB,MAAA,MAAA,CAAO,sBAAA,GAAyB,IAAA;AAChC,MAAA,OAAO,MAAA;AAAA,IACT;AAEA,IAAA,MAAA,CAAO,sBAAA,GAAyB,IAAI,QAAA,EAAS;AAAA,EAC/C,SAAS,KAAA,EAAO;AACd,IAAA,GAAA,CAAI,sCAAA,EAAwC,SAAA,EAAW,iDAAA,EAAmD,KAAK,CAAA;AAAA,EACjH;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.mjs","sourcesContent":["import { getAssociatedTokenAddressSync } from \"@solana/spl-token\";\nimport { Connection, PublicKey } from \"@solana/web3.js\";\nimport { Csl, OpenAPI, getChainRpcUrl } from '@stableflow/core';\n\nconst SOLANA_RPC_TIMEOUT_MS = 5000;\n\nconst withTimeout = async <T>(promise: Promise<T>, timeoutMs: number) => {\n return await Promise.race([\n promise,\n new Promise<T>((_, reject) => {\n setTimeout(() => reject(new Error(`Solana RPC timeout after ${timeoutMs}ms`)), timeoutMs);\n }),\n ]);\n};\n\nconst isRpcUnavailableError = (error: unknown) => {\n const message = (error as Error)?.message?.toLowerCase?.() || \"\";\n return (\n message.includes(\"fetch\") ||\n message.includes(\"timeout\") ||\n message.includes(\"failed to fetch\") ||\n message.includes(\"503\") ||\n message.includes(\"429\") ||\n message.includes(\"403\") ||\n message.includes(\"401\") ||\n message.includes(\"network\")\n );\n};\n\nexport const createSolanaFallbackConnection = (rpcUrls: string[]) => {\n if (!rpcUrls?.length) {\n throw new Error(\"No Solana RPC URLs configured\");\n }\n\n const cs = new Csl(OpenAPI.DEBUG);\n const csl = cs.log;\n const connections = rpcUrls.map((rpcUrl) => new Connection(rpcUrl, {\n commitment: \"confirmed\",\n }));\n let activeIndex = 0;\n let active: Connection = connections[activeIndex];\n\n return new Proxy(connections[0], {\n get(_, prop, receiver) {\n const activeValue = Reflect.get(active, prop, receiver);\n if (typeof activeValue !== \"function\") {\n return activeValue;\n }\n\n return (...args: unknown[]) => {\n const callAtIndex = (index: number) => {\n const targetConnection = connections[index];\n const method = (targetConnection as any)[prop];\n if (typeof method !== \"function\") {\n return method;\n }\n return method.apply(targetConnection, args);\n };\n\n const tryWithFallback = async () => {\n let index = activeIndex;\n let attempts = 0;\n let lastError: unknown = null;\n\n while (attempts < connections.length) {\n try {\n const result = await callAtIndex(index);\n activeIndex = index;\n active = connections[activeIndex];\n return result;\n } catch (error) {\n lastError = error;\n if (!isRpcUnavailableError(error)) {\n throw error;\n }\n\n const nextIndex = (index + 1) % connections.length;\n csl(\n \"solana rpc fallback\",\n \"yellow-400\",\n \"rpc unavailable, switching endpoint (%d -> %d): %o\",\n index,\n nextIndex,\n error\n );\n index = nextIndex;\n attempts += 1;\n }\n }\n\n throw lastError;\n };\n\n return tryWithFallback();\n };\n },\n }) as Connection;\n};\n\nconst probeRpcHealth = async (rpcUrl: string) => {\n const response = await withTimeout(fetch(rpcUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"getLatestBlockhash\",\n params: [{ commitment: \"confirmed\" }],\n }),\n }), SOLANA_RPC_TIMEOUT_MS);\n\n if (!response.ok) {\n throw new Error(`Solana RPC unavailable: ${rpcUrl}, status=${response.status}`);\n }\n\n const body = await response.json() as {\n result?: unknown;\n error?: { code?: number; message?: string; data?: unknown; };\n };\n\n if (body?.error) {\n throw new Error(\n `Solana RPC error: ${rpcUrl}, code=${body.error.code}, message=${body.error.message || \"unknown\"}`\n );\n }\n\n if (!body?.result) {\n throw new Error(`Solana RPC invalid response: ${rpcUrl}`);\n }\n};\n\nexport const getAvailableSolanaRpcUrl = async (options?: { isQuerySignature?: boolean; }) => {\n const { } = options || {};\n\n const cs = new Csl(OpenAPI.DEBUG);\n const csl = cs.log;\n\n const rpcUrls = getChainRpcUrl(\"Solana\").rpcUrls;\n if (!rpcUrls?.length) {\n throw new Error(\"No Solana RPC URLs configured\");\n }\n\n const formatRpcUrl = (rpcUrl: string) => {\n return rpcUrl;\n };\n\n for (const rpcUrl of rpcUrls) {\n try {\n await probeRpcHealth(rpcUrl);\n return formatRpcUrl(rpcUrl);\n } catch (error) {\n csl(\"solana rpc health\", \"yellow-400\", \"rpc health check failed: %o\", error);\n }\n }\n\n return formatRpcUrl(rpcUrls[0]);\n};\n\nexport const getDestinationAssociatedTokenAddress = async (params: any) => {\n const {\n recipient,\n toToken,\n } = params;\n\n const cs = new Csl(OpenAPI.DEBUG);\n const csl = cs.log;\n\n const result = {\n needCreateTokenAccount: false,\n associatedTokenAddress: \"\",\n };\n\n if (toToken.chainType !== \"sol\") {\n return result;\n }\n\n try {\n const connection = createSolanaFallbackConnection(getChainRpcUrl(\"Solana\").rpcUrls);\n const wallet = new PublicKey(recipient);\n const TOKEN_MINT = new PublicKey(toToken.contractAddress);\n\n const ata = getAssociatedTokenAddressSync(TOKEN_MINT, wallet);\n\n const accountInfo = await connection.getAccountInfo(ata);\n\n csl(\"getDestinationAssociatedTokenAddress\", \"purple-400\", \"accountInfo: %o\", accountInfo);\n\n if (!accountInfo) {\n result.needCreateTokenAccount = true;\n return result;\n }\n\n result.associatedTokenAddress = ata.toBase58();\n } catch (error) {\n csl(\"getDestinationAssociatedTokenAddress\", \"red-500\", \"getDestinationAssociatedTokenAddress failed: %o\", error);\n }\n\n return result;\n};\n"]}
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@stableflow/utils-solana",
3
+ "version": "3.0.0-beta-02a59f37a0-20260515",
4
+ "description": "Solana utilities for StableFlow SDK (RPC fallback, ATA helpers)",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/stableflow-ai/stableflow-sdk.git",
9
+ "directory": "packages/utils-solana"
10
+ },
11
+ "main": "./dist/index.js",
12
+ "module": "./dist/index.mjs",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.mjs",
18
+ "require": "./dist/index.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "sideEffects": false,
25
+ "dependencies": {
26
+ "@stableflow/core": "3.0.0-beta-02a59f37a0-20260515"
27
+ },
28
+ "peerDependencies": {
29
+ "@solana/spl-token": "^0.4.14",
30
+ "@solana/web3.js": "^1.98.4"
31
+ },
32
+ "devDependencies": {
33
+ "@solana/spl-token": "^0.4.14",
34
+ "@solana/web3.js": "^1.98.4",
35
+ "tsup": "^8.5.1",
36
+ "typescript": "^5.9.3"
37
+ },
38
+ "scripts": {
39
+ "build": "tsup",
40
+ "clean": "rm -rf dist"
41
+ }
42
+ }