@luno-kit/core 0.0.12-beta.3 → 0.0.12
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/{chain-BcRYsO36.d.cts → chain-gX0PC0aM.d.cts} +7 -2
- package/dist/{chain-BcRYsO36.d.ts → chain-gX0PC0aM.d.ts} +7 -2
- package/dist/chains/index.d.cts +1 -1
- package/dist/chains/index.d.ts +1 -1
- package/dist/chunk-A6UR3Q53.js +2 -0
- package/dist/chunk-A6UR3Q53.js.map +1 -0
- package/dist/chunk-VLCTGT6V.cjs +2 -0
- package/dist/chunk-VLCTGT6V.cjs.map +1 -0
- package/dist/connectors/index.cjs +1 -1
- package/dist/connectors/index.d.cts +1 -1
- package/dist/connectors/index.d.ts +1 -1
- package/dist/connectors/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/types/index.d.cts +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/utils/index.d.cts +1 -1
- package/dist/utils/index.d.ts +1 -1
- package/package.json +1 -1
- package/dist/chunk-UFHE4N3F.cjs +0 -2
- package/dist/chunk-UFHE4N3F.cjs.map +0 -1
- package/dist/chunk-WICFE46E.js +0 -2
- package/dist/chunk-WICFE46E.js.map +0 -1
|
@@ -117,6 +117,10 @@ interface WalletConnectConnectorOptions {
|
|
|
117
117
|
links?: Optional<ConnectorLinks>;
|
|
118
118
|
supportedChains?: Optional<HexString[]>;
|
|
119
119
|
}
|
|
120
|
+
interface ConnectorGroup {
|
|
121
|
+
groupName: string;
|
|
122
|
+
wallets: Connector[];
|
|
123
|
+
}
|
|
120
124
|
|
|
121
125
|
interface RawStorage {
|
|
122
126
|
getItem(key: string): string | null | Promise<string | null>;
|
|
@@ -136,7 +140,7 @@ type LunoApiOptions = Partial<Omit<ApiOptions, 'provider' | 'signer'>> & {
|
|
|
136
140
|
interface CreateConfigParameters extends LunoApiOptions {
|
|
137
141
|
appName?: Optional<string>;
|
|
138
142
|
chains?: Optional<readonly Chain[]>;
|
|
139
|
-
connectors: Connector[];
|
|
143
|
+
connectors: Connector[] | ConnectorGroup[];
|
|
140
144
|
transports?: Optional<Record<string, Transport>>;
|
|
141
145
|
storage?: Optional<LunoStorage>;
|
|
142
146
|
autoConnect?: Optional<boolean>;
|
|
@@ -150,6 +154,7 @@ interface Config extends LunoApiOptions {
|
|
|
150
154
|
readonly appName: string;
|
|
151
155
|
readonly chains: readonly Chain[];
|
|
152
156
|
readonly connectors: readonly Connector[];
|
|
157
|
+
readonly connectorGroups?: readonly ConnectorGroup[];
|
|
153
158
|
readonly transports: Readonly<Record<string, Transport>>;
|
|
154
159
|
readonly storage: LunoStorage;
|
|
155
160
|
readonly autoConnect: boolean;
|
|
@@ -191,4 +196,4 @@ interface Chain {
|
|
|
191
196
|
}>;
|
|
192
197
|
}
|
|
193
198
|
|
|
194
|
-
export { type Account as A, type CreateConfigParameters as C, type HexString as H, type LunoStorage as L, type RawStorage as R, type Signer as S, type Transport as T, type WalletConnectConnectorOptions as W, type Config as a, type Chain as b, type ConnectorLinks as c, type AccountBalance as d, ACCOUNT_TYPE as e, type Connector as f };
|
|
199
|
+
export { type Account as A, type CreateConfigParameters as C, type HexString as H, type LunoStorage as L, type RawStorage as R, type Signer as S, type Transport as T, type WalletConnectConnectorOptions as W, type Config as a, type Chain as b, type ConnectorLinks as c, type AccountBalance as d, ACCOUNT_TYPE as e, type Connector as f, type ConnectorGroup as g };
|
|
@@ -117,6 +117,10 @@ interface WalletConnectConnectorOptions {
|
|
|
117
117
|
links?: Optional<ConnectorLinks>;
|
|
118
118
|
supportedChains?: Optional<HexString[]>;
|
|
119
119
|
}
|
|
120
|
+
interface ConnectorGroup {
|
|
121
|
+
groupName: string;
|
|
122
|
+
wallets: Connector[];
|
|
123
|
+
}
|
|
120
124
|
|
|
121
125
|
interface RawStorage {
|
|
122
126
|
getItem(key: string): string | null | Promise<string | null>;
|
|
@@ -136,7 +140,7 @@ type LunoApiOptions = Partial<Omit<ApiOptions, 'provider' | 'signer'>> & {
|
|
|
136
140
|
interface CreateConfigParameters extends LunoApiOptions {
|
|
137
141
|
appName?: Optional<string>;
|
|
138
142
|
chains?: Optional<readonly Chain[]>;
|
|
139
|
-
connectors: Connector[];
|
|
143
|
+
connectors: Connector[] | ConnectorGroup[];
|
|
140
144
|
transports?: Optional<Record<string, Transport>>;
|
|
141
145
|
storage?: Optional<LunoStorage>;
|
|
142
146
|
autoConnect?: Optional<boolean>;
|
|
@@ -150,6 +154,7 @@ interface Config extends LunoApiOptions {
|
|
|
150
154
|
readonly appName: string;
|
|
151
155
|
readonly chains: readonly Chain[];
|
|
152
156
|
readonly connectors: readonly Connector[];
|
|
157
|
+
readonly connectorGroups?: readonly ConnectorGroup[];
|
|
153
158
|
readonly transports: Readonly<Record<string, Transport>>;
|
|
154
159
|
readonly storage: LunoStorage;
|
|
155
160
|
readonly autoConnect: boolean;
|
|
@@ -191,4 +196,4 @@ interface Chain {
|
|
|
191
196
|
}>;
|
|
192
197
|
}
|
|
193
198
|
|
|
194
|
-
export { type Account as A, type CreateConfigParameters as C, type HexString as H, type LunoStorage as L, type RawStorage as R, type Signer as S, type Transport as T, type WalletConnectConnectorOptions as W, type Config as a, type Chain as b, type ConnectorLinks as c, type AccountBalance as d, ACCOUNT_TYPE as e, type Connector as f };
|
|
199
|
+
export { type Account as A, type CreateConfigParameters as C, type HexString as H, type LunoStorage as L, type RawStorage as R, type Signer as S, type Transport as T, type WalletConnectConnectorOptions as W, type Config as a, type Chain as b, type ConnectorLinks as c, type AccountBalance as d, ACCOUNT_TYPE as e, type Connector as f, type ConnectorGroup as g };
|
package/dist/chains/index.d.cts
CHANGED
package/dist/chains/index.d.ts
CHANGED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {WsProvider}from'dedot';function p({storage:o,keyPrefix:a="luno."}){let r=e=>`${a}${e}`;return {async getItem(e){try{let t=r(e),n=await o.getItem(t);return n==null?null:String(n)}catch(t){return console.error(`[LunoStorage] Error getting item "${e}" (full key: "${r(e)}"):`,t),null}},async setItem(e,t){try{let n=r(e);await o.setItem(n,t);}catch(n){console.error(`[LunoStorage] Error setting item "${e}" (full key: "${r(e)}"):`,n);}},async removeItem(e){try{let t=r(e);await o.removeItem(t);}catch(t){console.error(`[LunoStorage] Error removing item "${e}" (full key: "${r(e)}"):`,t);}}}}var S={getItem:async o=>null,setItem:async(o,a)=>{},removeItem:async o=>{}},v=p({storage:typeof window<"u"&&window.localStorage?window.localStorage:S,keyPrefix:"luno."});function P(o){let a={};for(let r of o){let e=r.rpcUrls.webSocket;e?a[r.genesisHash]=e:console.warn(`No WebSocket URL found for chain "${r.name}" (${r.genesisHash}). Skipping transport generation.`);}return a}function u(o){return o.length>0&&"groupName"in o[0]&&"wallets"in o[0]}function T(o){let{appName:a="My Luno App",chains:r=[],connectors:e,transports:t={},storage:n=v,autoConnect:m=true,cacheMetadata:f=true,metadata:y,scaledResponses:d,customTypes:h,customRpc:w,subscan:C}=o,i=u(e)?e.filter(s=>s.wallets.length>0):void 0,c=u(e)?e.flatMap(s=>s.wallets):e;if(!c||c.length===0)throw new Error("No connectors provided. Wallet connection features will be unavailable.");let l=r.length>0?P(r):{},g=t?{...l,...t}:l;if(r.length>0)for(let s of r)g[s.genesisHash]||console.warn(`Missing transport for chain "${s.name}" (genesisHash: ${s.genesisHash}). Chain functionality may be limited.`);return {customRpc:w,customTypes:h,cacheMetadata:f,metadata:y,scaledResponses:d,appName:a,chains:Object.freeze([...r]),connectors:Object.freeze([...c]),connectorGroups:i?Object.freeze([...i]):void 0,transports:Object.freeze({...g}),storage:n,autoConnect:m,subscan:C}}function k(o){return new WsProvider(o)}export{p as a,T as b,k as c};//# sourceMappingURL=chunk-A6UR3Q53.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-A6UR3Q53.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config/createStorage.ts","../src/config/createConfig.ts","../src/config/providers.ts"],"names":["createStorage","storage","keyPrefix","getKey","suffix","keySuffix","fullKey","value","error","noopStorage","_key","_value","defaultLunoStorage","generateTransportsFromChains","chains","transports","chain","wsUrl","isConnectorGroupArray","input","createConfig","parameters","appName","connectorsInput","autoConnect","cacheMetadata","metadata","scaledResponses","customTypes","customRpc","subscan","connectorGroups","g","connectors","transportsFromChains","finalTransports","wsProvider","url","WsProvider"],"mappings":"+BAgBO,SAASA,CAAAA,CAAc,CAC5B,OAAA,CAAAC,CAAAA,CACA,UAAAC,CAAAA,CAAY,OACd,EAAyC,CACvC,IAAMC,EAAUC,CAAAA,EAA2B,CAAA,EAAGF,CAAS,CAAA,EAAGE,CAAM,GAEhE,OAAO,CACL,MAAM,OAAA,CAAQC,CAAAA,CAA2C,CACvD,GAAI,CACF,IAAMC,EAAUH,CAAAA,CAAOE,CAAS,EAE1BE,CAAAA,CAAQ,MAAMN,EAAQ,OAAA,CAAQK,CAAO,EAE3C,OAAOC,CAAAA,EAAS,KAAO,IAAA,CAAO,MAAA,CAAOA,CAAK,CAC5C,CAAA,MAASC,CAAAA,CAAO,CACd,OAAA,OAAA,CAAQ,KAAA,CACN,qCAAqCH,CAAS,CAAA,cAAA,EAAiBF,EAAOE,CAAS,CAAC,MAChFG,CACF,CAAA,CACO,IACT,CACF,CAAA,CAEA,MAAM,OAAA,CAAQH,CAAAA,CAAmBE,EAA8B,CAC7D,GAAI,CACF,IAAMD,CAAAA,CAAUH,CAAAA,CAAOE,CAAS,CAAA,CAEhC,MAAMJ,EAAQ,OAAA,CAAQK,CAAAA,CAASC,CAAK,EACtC,CAAA,MAASC,EAAO,CACd,OAAA,CAAQ,KAAA,CACN,CAAA,kCAAA,EAAqCH,CAAS,CAAA,cAAA,EAAiBF,EAAOE,CAAS,CAAC,MAChFG,CACF,EAEF,CACF,CAAA,CAEA,MAAM,UAAA,CAAWH,CAAAA,CAAkC,CACjD,GAAI,CACF,IAAMC,CAAAA,CAA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AA,CACA,MAAA,CAAQ,MAAA,CAAO,MAAA,CAAO,CAAC,GAAGR,CAAM,CAAC,CAAA,CACjC,WAAY,MAAA,CAAO,MAAA,CAAO,CAAC,GAAGmB,CAAU,CAAC,CAAA,CACzC,eAAA,CAAiBF,EACZ,MAAA,CAAO,MAAA,CAAO,CAAC,GAAGA,CAAe,CAAC,CAAA,CACnC,MAAA,CACJ,UAAA,CAAY,MAAA,CAAO,MAAA,CAAO,CAAE,GAAGI,CAAgB,CAAC,EAChD,OAAA,CAAAlC,CAAAA,CACA,YAAAuB,CAAAA,CAEA,OAAA,CAAAM,CACF,CAGF,CCpGO,SAASM,CAAAA,CAAWC,CAAAA,CAA4B,CACrD,OAAO,IAAIC,UAAAA,CAAWD,CAAe,CACvC","file":"chunk-A6UR3Q53.js","sourcesContent":["import type { LunoStorage, RawStorage } from '../types';\n\n// Defines the parameters for the createStorage function.\nexport interface CreateStorageParameters {\n storage: RawStorage;\n keyPrefix?: Optional<string>; // Optional key prefix, e.g., \"luno.\"\n}\n\n/**\n * Creates a LunoStorage object that wraps a raw storage mechanism (like localStorage)\n * to provide a consistent async API with key prefixing and error handling.\n *\n * @param storage The raw storage mechanism (e.g., window.localStorage).\n * @param keyPrefix An optional prefix for all storage keys to avoid collisions.\n * @returns A LunoStorage object.\n */\nexport function createStorage({\n storage,\n keyPrefix = 'luno.', // Default key prefix\n}: CreateStorageParameters): LunoStorage {\n const getKey = (suffix: string): string => `${keyPrefix}${suffix}`;\n\n return {\n async getItem(keySuffix: string): Promise<string | null> {\n try {\n const fullKey = getKey(keySuffix);\n // Await to handle both sync and async RawStorage getItem methods consistently\n const value = await storage.getItem(fullKey);\n // Normalize undefined or null to null\n return value == null ? null : String(value);\n } catch (error) {\n console.error(\n `[LunoStorage] Error getting item \"${keySuffix}\" (full key: \"${getKey(keySuffix)}\"):`,\n error\n );\n return null; // Return null on error to indicate failure\n }\n },\n\n async setItem(keySuffix: string, value: string): Promise<void> {\n try {\n const fullKey = getKey(keySuffix);\n // Await to handle both sync and async RawStorage setItem methods consistently\n await storage.setItem(fullKey, value);\n } catch (error) {\n console.error(\n `[LunoStorage] Error setting item \"${keySuffix}\" (full key: \"${getKey(keySuffix)}\"):`,\n error\n );\n // Errors during setItem are logged but don't typically need to be propagated further in the same way getItem might.\n }\n },\n\n async removeItem(keySuffix: string): Promise<void> {\n try {\n const fullKey = getKey(keySuffix);\n // Await to handle both sync and async RawStorage removeItem methods consistently\n await storage.removeItem(fullKey);\n } catch (error) {\n console.error(\n `[LunoStorage] Error removing item \"${keySuffix}\" (full key: \"${getKey(keySuffix)}\"):`,\n error\n );\n }\n },\n };\n}\n","import type {\n Chain,\n Config,\n Connector,\n ConnectorGroup,\n CreateConfigParameters,\n RawStorage,\n Transport,\n} from '../types';\nimport { createStorage } from './createStorage';\n\nconst noopStorage: RawStorage = {\n getItem: async (_key: string) => null,\n setItem: async (_key: string, _value: string) => {},\n removeItem: async (_key: string) => {},\n};\n\nconst defaultLunoStorage = createStorage({\n storage: typeof window !== 'undefined' && window.localStorage ? window.localStorage : noopStorage,\n keyPrefix: 'luno.',\n});\n\nfunction generateTransportsFromChains(chains: readonly Chain[]): Record<string, Transport> {\n const transports: Record<string, Transport> = {};\n\n for (const chain of chains) {\n const wsUrl = chain.rpcUrls.webSocket;\n if (wsUrl) {\n transports[chain.genesisHash] = wsUrl;\n } else {\n console.warn(\n `No WebSocket URL found for chain \"${chain.name}\" (${chain.genesisHash}). Skipping transport generation.`\n );\n }\n }\n\n return transports;\n}\n\nfunction isConnectorGroupArray(input: Connector[] | ConnectorGroup[]): input is ConnectorGroup[] {\n return input.length > 0 && 'groupName' in input[0] && 'wallets' in input[0];\n}\n\nexport function createConfig(parameters: CreateConfigParameters): Config {\n const {\n appName = 'My Luno App',\n chains = [],\n connectors: connectorsInput,\n transports = {},\n storage = defaultLunoStorage,\n autoConnect = true,\n cacheMetadata = true,\n metadata,\n scaledResponses,\n customTypes,\n customRpc,\n subscan,\n } = parameters;\n\n const connectorGroups = isConnectorGroupArray(connectorsInput)\n ? connectorsInput.filter((g) => g.wallets.length > 0)\n : undefined;\n\n const connectors = isConnectorGroupArray(connectorsInput)\n ? connectorsInput.flatMap((g) => g.wallets)\n : connectorsInput;\n\n if (!connectors || connectors.length === 0) {\n throw new Error('No connectors provided. Wallet connection features will be unavailable.');\n }\n\n const transportsFromChains = chains.length > 0 ? generateTransportsFromChains(chains) : {};\n\n const finalTransports = transports\n ? { ...transportsFromChains, ...transports }\n : transportsFromChains;\n\n if (chains.length > 0) {\n for (const chain of chains) {\n if (!finalTransports[chain.genesisHash]) {\n console.warn(\n `Missing transport for chain \"${chain.name}\" (genesisHash: ${chain.genesisHash}). Chain functionality may be limited.`\n );\n }\n }\n }\n\n const config = {\n customRpc,\n customTypes,\n cacheMetadata,\n metadata,\n scaledResponses,\n\n appName,\n chains: Object.freeze([...chains]) as readonly Chain[],\n connectors: Object.freeze([...connectors]) as readonly Connector[],\n connectorGroups: connectorGroups\n ? (Object.freeze([...connectorGroups]) as readonly ConnectorGroup[])\n : undefined,\n transports: Object.freeze({ ...finalTransports }) as Readonly<Record<string, Transport>>,\n storage,\n autoConnect,\n\n subscan,\n };\n\n return config;\n}\n","import { WsProvider } from 'dedot';\nimport type { Transport } from '../types';\n\n/**\n * create a WebSocket Transport (WsProvider) instance.\n * @param url - WebSocket RPC URL or URL array (for fallback).\n * @returns WsProvider instance.\n */\nexport function wsProvider(url: Transport): WsProvider {\n return new WsProvider(url as string[]);\n}\n\nexport type { Transport };\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var dedot=require('dedot');function p({storage:o,keyPrefix:a="luno."}){let r=e=>`${a}${e}`;return {async getItem(e){try{let t=r(e),n=await o.getItem(t);return n==null?null:String(n)}catch(t){return console.error(`[LunoStorage] Error getting item "${e}" (full key: "${r(e)}"):`,t),null}},async setItem(e,t){try{let n=r(e);await o.setItem(n,t);}catch(n){console.error(`[LunoStorage] Error setting item "${e}" (full key: "${r(e)}"):`,n);}},async removeItem(e){try{let t=r(e);await o.removeItem(t);}catch(t){console.error(`[LunoStorage] Error removing item "${e}" (full key: "${r(e)}"):`,t);}}}}var S={getItem:async o=>null,setItem:async(o,a)=>{},removeItem:async o=>{}},v=p({storage:typeof window<"u"&&window.localStorage?window.localStorage:S,keyPrefix:"luno."});function P(o){let a={};for(let r of o){let e=r.rpcUrls.webSocket;e?a[r.genesisHash]=e:console.warn(`No WebSocket URL found for chain "${r.name}" (${r.genesisHash}). Skipping transport generation.`);}return a}function u(o){return o.length>0&&"groupName"in o[0]&&"wallets"in o[0]}function T(o){let{appName:a="My Luno App",chains:r=[],connectors:e,transports:t={},storage:n=v,autoConnect:m=true,cacheMetadata:f=true,metadata:y,scaledResponses:d,customTypes:h,customRpc:w,subscan:C}=o,i=u(e)?e.filter(s=>s.wallets.length>0):void 0,c=u(e)?e.flatMap(s=>s.wallets):e;if(!c||c.length===0)throw new Error("No connectors provided. Wallet connection features will be unavailable.");let l=r.length>0?P(r):{},g=t?{...l,...t}:l;if(r.length>0)for(let s of r)g[s.genesisHash]||console.warn(`Missing transport for chain "${s.name}" (genesisHash: ${s.genesisHash}). Chain functionality may be limited.`);return {customRpc:w,customTypes:h,cacheMetadata:f,metadata:y,scaledResponses:d,appName:a,chains:Object.freeze([...r]),connectors:Object.freeze([...c]),connectorGroups:i?Object.freeze([...i]):void 0,transports:Object.freeze({...g}),storage:n,autoConnect:m,subscan:C}}function k(o){return new dedot.WsProvider(o)}exports.a=p;exports.b=T;exports.c=k;//# sourceMappingURL=chunk-VLCTGT6V.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-VLCTGT6V.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config/createStorage.ts","../src/config/createConfig.ts","../src/config/providers.ts"],"names":["createStorage","storage","keyPrefix","getKey","suffix","keySuffix","fullKey","value","error","noopStorage","_key","_value","defaultLunoStorage","generateTransportsFromChains","chains","transports","chain","wsUrl","isConnectorGroupArray","input","createConfig","parameters","appName","connectorsInput","autoConnect","cacheMetadata","metadata","scaledResponses","customTypes","customRpc","subscan","connectorGroups","g","connectors","transportsFromChains","finalTransports","wsProvider","url","WsProvider"],"mappings":"wCAgBO,SAASA,CAAAA,CAAc,CAC5B,OAAA,CAAAC,CAAAA,CACA,UAAAC,CAAAA,CAAY,OACd,EAAyC,CACvC,IAAMC,EAAUC,CAAAA,EAA2B,CAAA,EAAGF,CAAS,CAAA,EAAGE,CAAM,GAEhE,OAAO,CACL,MAAM,OAAA,CAAQC,CAAAA,CAA2C,CACvD,GAAI,CACF,IAAMC,EAAUH,CAAAA,CAAOE,CAAS,EAE1BE,CAAAA,CAAQ,MAAMN,EAAQ,OAAA,CAAQK,CAAO,EAE3C,OAAOC,CAAAA,EAAS,KAAO,IAAA,CAAO,MAAA,CAAOA,CAAK,CAC5C,CAAA,MAASC,CAAAA,CAAO,CACd,OAAA,OAAA,CAAQ,KAAA,CACN,qCAAqCH,CAAS,CAAA,cAAA,EAAiBF,EAAOE,CAAS,CAAC,MAChFG,CACF,CAAA,CACO,IACT,CACF,CAAA,CAEA,MAAM,OAAA,CAAQH,CAAAA,CAAmBE,EAA8B,CAC7D,GAAI,CACF,IAAMD,CAAAA,CAAUH,CAAAA,CAAOE,CAAS,CAAA,CAEhC,MAAMJ,EAAQ,OAAA,CAAQK,CAAAA,CAASC,CAAK,EACtC,CAAA,MAASC,EAAO,CACd,OAAA,CAAQ,KAAA,CACN,CAAA,kCAAA,EAAqCH,CAAS,CAAA,cAAA,EAAiBF,EAAOE,CAAS,CAAC,MAChFG,CACF,EAEF,CACF,CAAA,CAEA,MAAM,UAAA,CAAWH,CAAAA,CAAkC,CACjD,GAAI,CACF,IAAMC,CAAAA,CAAUH,EAAOE,CAAS,CAAA,CAEhC,MAAMJ,CAAAA,CAAQ,UAAA,CAAWK,CAAO,EAClC,CAAA,MAASE,EAAO,CACd,OAAA,CAAQ,MACN,CAAA,mCAAA,EAAsCH,CA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A,CACzC,eAAA,CAAiBF,EACZ,MAAA,CAAO,MAAA,CAAO,CAAC,GAAGA,CAAe,CAAC,CAAA,CACnC,MAAA,CACJ,UAAA,CAAY,MAAA,CAAO,MAAA,CAAO,CAAE,GAAGI,CAAgB,CAAC,EAChD,OAAA,CAAAlC,CAAAA,CACA,YAAAuB,CAAAA,CAEA,OAAA,CAAAM,CACF,CAGF,CCpGO,SAASM,CAAAA,CAAWC,CAAAA,CAA4B,CACrD,OAAO,IAAIC,gBAAAA,CAAWD,CAAe,CACvC","file":"chunk-VLCTGT6V.cjs","sourcesContent":["import type { LunoStorage, RawStorage } from '../types';\n\n// Defines the parameters for the createStorage function.\nexport interface CreateStorageParameters {\n storage: RawStorage;\n keyPrefix?: Optional<string>; // Optional key prefix, e.g., \"luno.\"\n}\n\n/**\n * Creates a LunoStorage object that wraps a raw storage mechanism (like localStorage)\n * to provide a consistent async API with key prefixing and error handling.\n *\n * @param storage The raw storage mechanism (e.g., window.localStorage).\n * @param keyPrefix An optional prefix for all storage keys to avoid collisions.\n * @returns A LunoStorage object.\n */\nexport function createStorage({\n storage,\n keyPrefix = 'luno.', // Default key prefix\n}: CreateStorageParameters): LunoStorage {\n const getKey = (suffix: string): string => `${keyPrefix}${suffix}`;\n\n return {\n async getItem(keySuffix: string): Promise<string | null> {\n try {\n const fullKey = getKey(keySuffix);\n // Await to handle both sync and async RawStorage getItem methods consistently\n const value = await storage.getItem(fullKey);\n // Normalize undefined or null to null\n return value == null ? null : String(value);\n } catch (error) {\n console.error(\n `[LunoStorage] Error getting item \"${keySuffix}\" (full key: \"${getKey(keySuffix)}\"):`,\n error\n );\n return null; // Return null on error to indicate failure\n }\n },\n\n async setItem(keySuffix: string, value: string): Promise<void> {\n try {\n const fullKey = getKey(keySuffix);\n // Await to handle both sync and async RawStorage setItem methods consistently\n await storage.setItem(fullKey, value);\n } catch (error) {\n console.error(\n `[LunoStorage] Error setting item \"${keySuffix}\" (full key: \"${getKey(keySuffix)}\"):`,\n error\n );\n // Errors during setItem are logged but don't typically need to be propagated further in the same way getItem might.\n }\n },\n\n async removeItem(keySuffix: string): Promise<void> {\n try {\n const fullKey = getKey(keySuffix);\n // Await to handle both sync and async RawStorage removeItem methods consistently\n await storage.removeItem(fullKey);\n } catch (error) {\n console.error(\n `[LunoStorage] Error removing item \"${keySuffix}\" (full key: \"${getKey(keySuffix)}\"):`,\n error\n );\n }\n },\n };\n}\n","import type {\n Chain,\n Config,\n Connector,\n ConnectorGroup,\n CreateConfigParameters,\n RawStorage,\n Transport,\n} from '../types';\nimport { createStorage } from './createStorage';\n\nconst noopStorage: RawStorage = {\n getItem: async (_key: string) => null,\n setItem: async (_key: string, _value: string) => {},\n removeItem: async (_key: string) => {},\n};\n\nconst defaultLunoStorage = createStorage({\n storage: typeof window !== 'undefined' && window.localStorage ? window.localStorage : noopStorage,\n keyPrefix: 'luno.',\n});\n\nfunction generateTransportsFromChains(chains: readonly Chain[]): Record<string, Transport> {\n const transports: Record<string, Transport> = {};\n\n for (const chain of chains) {\n const wsUrl = chain.rpcUrls.webSocket;\n if (wsUrl) {\n transports[chain.genesisHash] = wsUrl;\n } else {\n console.warn(\n `No WebSocket URL found for chain \"${chain.name}\" (${chain.genesisHash}). Skipping transport generation.`\n );\n }\n }\n\n return transports;\n}\n\nfunction isConnectorGroupArray(input: Connector[] | ConnectorGroup[]): input is ConnectorGroup[] {\n return input.length > 0 && 'groupName' in input[0] && 'wallets' in input[0];\n}\n\nexport function createConfig(parameters: CreateConfigParameters): Config {\n const {\n appName = 'My Luno App',\n chains = [],\n connectors: connectorsInput,\n transports = {},\n storage = defaultLunoStorage,\n autoConnect = true,\n cacheMetadata = true,\n metadata,\n scaledResponses,\n customTypes,\n customRpc,\n subscan,\n } = parameters;\n\n const connectorGroups = isConnectorGroupArray(connectorsInput)\n ? connectorsInput.filter((g) => g.wallets.length > 0)\n : undefined;\n\n const connectors = isConnectorGroupArray(connectorsInput)\n ? connectorsInput.flatMap((g) => g.wallets)\n : connectorsInput;\n\n if (!connectors || connectors.length === 0) {\n throw new Error('No connectors provided. Wallet connection features will be unavailable.');\n }\n\n const transportsFromChains = chains.length > 0 ? generateTransportsFromChains(chains) : {};\n\n const finalTransports = transports\n ? { ...transportsFromChains, ...transports }\n : transportsFromChains;\n\n if (chains.length > 0) {\n for (const chain of chains) {\n if (!finalTransports[chain.genesisHash]) {\n console.warn(\n `Missing transport for chain \"${chain.name}\" (genesisHash: ${chain.genesisHash}). Chain functionality may be limited.`\n );\n }\n }\n }\n\n const config = {\n customRpc,\n customTypes,\n cacheMetadata,\n metadata,\n scaledResponses,\n\n appName,\n chains: Object.freeze([...chains]) as readonly Chain[],\n connectors: Object.freeze([...connectors]) as readonly Connector[],\n connectorGroups: connectorGroups\n ? (Object.freeze([...connectorGroups]) as readonly ConnectorGroup[])\n : undefined,\n transports: Object.freeze({ ...finalTransports }) as Readonly<Record<string, Transport>>,\n storage,\n autoConnect,\n\n subscan,\n };\n\n return config;\n}\n","import { WsProvider } from 'dedot';\nimport type { Transport } from '../types';\n\n/**\n * create a WebSocket Transport (WsProvider) instance.\n * @param url - WebSocket RPC URL or URL array (for fallback).\n * @returns WsProvider instance.\n */\nexport function wsProvider(url: Transport): WsProvider {\n return new WsProvider(url as string[]);\n}\n\nexport type { Transport };\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var chunkUFHE4N3F_cjs=require('../chunk-UFHE4N3F.cjs'),chunkQL6JNH54_cjs=require('../chunk-QL6JNH54.cjs'),chunk4IW7WG2H_cjs=require('../chunk-4IW7WG2H.cjs'),eventemitter3=require('eventemitter3'),utils=require('dedot/utils'),dedot=require('dedot'),codecs=require('dedot/codecs'),merkleizedMetadata=require('dedot/merkleized-metadata');var u=class extends eventemitter3.EventEmitter{constructor(){super();this.links={};this.accounts=[];this.signer=void 0;this.connectionUri=void 0;}async getAccounts(){return [...this.accounts]}async getSigner(){return this.signer||console.warn(`Connector ${this.id}: Signer not available. Connection might be incomplete or failed.`),this.signer}hasConnectionUri(){return false}async getConnectionUri(){return this.connectionUri}};var s=class extends u{constructor(e){super();this.unsubscribe=null;this.specificInjector=void 0;this.id=e.id,this.name=e.name,this.icon=e.icon,this.links=e.links,this.injectorId=e.injectorId||e.id;}isInstalled(){if(typeof window>"u")return false;let e=window.injectedWeb3;return typeof e=="object"&&typeof e[this.injectorId]<"u"}async isAvailable(){return this.isInstalled()}async connect(e){if(this.signer)return [...this.accounts];if(!await this.isAvailable())throw new Error(`${this.name} extension not found or not enabled.`);try{if(this.specificInjector=await window.injectedWeb3[this.injectorId].enable(e),!this.specificInjector)throw new Error(`Failed to enable the '${this.id}' extension.`);if(this.signer=this.specificInjector.signer,!this.signer)throw new Error(`Could not get signer from ${this.name}.`);let t=await this.specificInjector.accounts.get();if(t.length===0)throw new Error(`No accounts found in ${this.name}. Make sure accounts are visible and access is granted.`);return this.accounts=chunk4IW7WG2H_cjs.e(t,this.id),await this.startSubscription(),this.emit("connect",[...this.accounts]),[...this.accounts]}catch(t){throw console.error(`Connector ${this.id}: Connection failed:`,t),await this.cleanup(),t}}async disconnect(){await this.cleanup(),this.emit("disconnect");}async signMessage(e,t){if(!t||!e)return;let i=await this.getSigner();if(!i||!i?.signRaw)throw new Error("Signer is not available or does not support signRaw.");if(!(await this.getAccounts()).some(n=>n.address.toLowerCase()===t.toLowerCase()))throw new Error(`Address ${t} is not managed by ${this.name}.`);try{let n=utils.stringToHex(e);return (await i.signRaw({address:t,data:n,type:"bytes"})).signature}catch(n){throw new Error(`Connector ${this.id}: Failed to sign message: ${n.message}`)}}async startSubscription(){if(await this.cleanupSubscription(),!this.specificInjector)throw new Error(`Connector ${this.id}: Cannot subscribe, specificInjector not available.`);try{this.unsubscribe=this.specificInjector.accounts.subscribe(e=>{let t=chunk4IW7WG2H_cjs.e(e,this.id);JSON.stringify(this.accounts)!==JSON.stringify(t)&&(this.accounts=t,this.emit("accountsChanged",[...this.accounts]));});}catch(e){console.error(`Connector ${this.id}: Failed to subscribe to accounts:`,e),this.unsubscribe=null;}}async cleanupSubscription(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);}async cleanup(){await this.cleanupSubscription(),this.accounts=[],this.signer=void 0,this.specificInjector=void 0;}};var Q=()=>new s({id:"enkrypt",name:"Enkrypt",icon:chunkQL6JNH54_cjs.h,links:{browserExtension:"https://www.enkrypt.com"}});var V=()=>new s({id:"fearless-wallet",name:"Fearless",icon:chunkQL6JNH54_cjs.i,links:{browserExtension:"https://fearlesswallet.io"}});function L(a,p=354){return `m/44'/${p}'/${a}'/0'/0'`}var k=class extends u{constructor(e){super();this.id="ledger";this.name="Ledger";this.icon=chunkQL6JNH54_cjs.k;this.links={};this.app=null;this.transport=null;this.accountIndex=0;this.chains=e.chains;}isInstalled(){return false}async isAvailable(){return !!(typeof navigator<"u"&&navigator.usb)}async ensureTransportOpen(){if(!this.transport)throw new Error("Transport not initialized");this.transport.device?.opened||await this.transport.open();}async ensureTransportClosed(){this.transport?.device?.opened&&await this.transport.close();}async connect(e,t,i){if(!await this.isAvailable())throw new Error("WebUSB is not supported in this browser.");try{let{Buffer:o}=await import('buffer');globalThis.Buffer=o;let{default:n}=await import('@ledgerhq/hw-transport-webusb');try{this.transport=await n.create();}catch(g){if(g.name==="SecurityError"||g.message?.includes("user gesture"))throw new Error("Ledger connection requires user interaction. Please click the connect button to connect your Ledger device.");this.transport=await n.request();}let{PolkadotGenericApp:r}=await import('@zondax/ledger-substrate'),l=new r(this.transport);this.app=l,await this.ensureTransportOpen();let d=L(this.accountIndex),c=await l.getAddressEd25519(d,0,!1);if(!c||!c.address)throw new Error("Failed to retrieve address from Ledger.");let m=c.pubKey?`0x${c.pubKey}`:void 0;return this.accounts=[{address:c.address,publicKey:m,name:"Ledger Wallet",type:"sr25519",meta:{source:"ledger",accountIndex:0,bip44Path:d}}],this.signer=await this.getSigner(),this.emit("connect",[...this.accounts]),[...this.accounts]}catch(o){throw console.error(`Connector ${this.id}: Connection failed:`,o),await this.cleanup(),o}}async disconnect(){await this.cleanup(),this.emit("disconnect");}async signMessage(e,t){let i=await this.getSigner();if(!i)throw new Error("No signer provided");let o=utils.stringToHex(e);return (await i.signRaw({address:t,data:o,type:"bytes"})).signature}async getSigner(){return {signRaw:async e=>{throw new Error("Ledger not supported signRaw!")},signPayload:async e=>{if(!this.app)throw new Error("Ledger not connected");let t=this.chains.find(J=>J.genesisHash===e.genesisHash);if(!t)throw new Error("Chain not found in your configuration chains");await this.ensureTransportOpen();let i=L(this.accountIndex),o=chunkUFHE4N3F_cjs.c(t.rpcUrls.webSocket),n=new dedot.LegacyClient(o);await n.connect();let r=await o.send("state_getMetadata",[]),l={tokenSymbol:t.nativeCurrency?.symbol||"DOT",decimals:t.nativeCurrency?.decimals||10},d=new merkleizedMetadata.MerkleizedMetadata(r,l),c=new dedot.ExtraSignedExtension(n,{signerAddress:e.address,payloadOptions:{metadataHash:utils.u8aToHex(d.digest())}});await c.init();let m=c.toRawPayload(e.method).data,g=d.proofForExtrinsicPayload(m),_=Buffer.from(utils.hexToU8a(m)),N=Buffer.from(g),{signature:S}=await this.app.signWithMetadataEd25519(i,_,N),{signatureTypeId:B,callTypeId:q}=n.registry.metadata.extrinsic,F=n.registry.findCodec(B),K=n.registry.findCodec(q),D=F.tryDecode(utils.u8aToHex(S)),z=K.tryDecode(e.method),j=new codecs.Extrinsic(n.registry,z);return j.attachSignature({address:e.address,signature:D,extra:c.data}),{id:0,signature:utils.u8aToHex(S),signedTransaction:j.toHex()}}}}async cleanup(){if(this.transport)try{await this.ensureTransportClosed();}catch(e){console.warn("Error closing transport:",e);}this.transport=null,this.app=null,this.accounts=[],this.signer=void 0;}},oe=a=>new k(a);var x=class extends s{constructor(e){super({...e});this.mimirReady=false;this.mimirInject();}isInstalled(){return this.mimirReady}async mimirInject(){try{if(!(typeof window<"u"&&window!==window.parent))return;let{isMimirReady:t,MIMIR_REGEXP:i,inject:o}=await import('@mimirdev/apps-inject'),n=await t();n&&i.test(n)&&(o(),this.mimirReady=!0);}catch(e){console.error("Failed to inject Mimir:",e);}}async connect(e){if(!this.mimirReady){let{MIMIR_REGEXP:t}=await import('@mimirdev/apps-inject');if(!window.origin||!t.test(window.origin)){window.open(`https://app.mimir.global/explorer/${encodeURIComponent(window.origin)}`);return}}return super.connect(e)}};function re(){return new x({id:"mimir",name:"Mimir",icon:chunkQL6JNH54_cjs.l,links:{browserExtension:"https://mimir.global"}})}var I=class extends s{constructor(){super({id:"nova-mobile",name:"Nova",icon:chunkQL6JNH54_cjs.m,injectorId:"polkadot-js",links:{deepLink:"https://app.novawallet.io/open/dapp"}});}isInstalled(){if(typeof window>"u")return false;let p=window.injectedWeb3;return typeof p=="object"&&typeof p["polkadot-js"]<"u"&&window.walletExtension?.isNovaWallet===true}async isAvailable(){return this.isInstalled()}},w=()=>new I;var h=class extends u{constructor(e){super();this.supportedChains=[];this.unsubscribe=null;this.id=e.id||"walletconnect",this.name=e.name||"WalletConnect",this.links=e.links||{},this.icon=e.icon||chunkQL6JNH54_cjs.w,this.projectId=e.projectId,this.relayUrl=e.relayUrl||"wss://relay.walletconnect.com",this.metadata=e.metadata,this.supportedChains=e.supportedChains||[];}isInstalled(){return false}async isAvailable(){return true}convertChainIdToCaipId(e){return e.map(t=>`polkadot:${(t.genesisHash||t).replace("0x","").slice(0,32)}`)}async connect(e,t){if(!this.projectId)throw new Error(`${this.name} requires a projectId. Please visit https://cloud.walletconnect.com to get one.`);let i=t?.length?t:this.supportedChains.length?this.supportedChains:void 0;if(!i||i.length===0)throw new Error(`${this.name} requires chains configuration.`);this.connectedChains=i;let{UniversalProvider:o}=await import('@walletconnect/universal-provider');try{if(this.provider=await o.init({projectId:this.projectId,relayUrl:this.relayUrl,metadata:this.metadata||{name:e,description:"LunoKit DApp",url:typeof window<"u"?window.location.origin:"",icons:[this.icon]}}),this.provider.session){this.session=this.provider.session;let c=this.getAccountsFromSession(i);return this.accounts=c,await this.startSubscription(),this.emit("connect",[...this.accounts]),[...this.accounts]}if(!this.provider?.client)throw new Error("Provider not initialized or not connected");let{uri:n,approval:r}=await this.provider.client.connect({requiredNamespaces:{polkadot:{methods:["polkadot_signMessage","polkadot_sendTransaction","polkadot_signTransaction","polkadot_requestAccounts"],chains:this.convertChainIdToCaipId(i),events:["accountsChanged","chainChanged","connect"]}},optionalNamespaces:{polkadot:{methods:["polkadot_signMessage","polkadot_sendTransaction","polkadot_signTransaction","polkadot_requestAccounts"],chains:this.convertChainIdToCaipId(i),events:["accountsChanged","chainChanged","connect"]}}});this.emit("get_uri",n);let l=await r();this.session=l,this.provider.session=l,this.connectionUri=void 0;let d=this.getAccountsFromSession(i);return this.accounts=d,await this.startSubscription(),this.emit("connect",[...this.accounts]),[...this.accounts]}catch(n){throw this.connectionUri=void 0,n}}getAccountsFromSession(e){let t=[e[0].genesisHash||e[0]],i=this.convertChainIdToCaipId(t)[0],o=this.session?.namespaces.polkadot.accounts.flat().filter(r=>r.includes(i)).map(r=>r.replace(`${i}:`,""));if(o&&o.length===0){console.error("No accounts found for the specified chain, please connect to the correct chain");let r=this.convertChainIdToCaipId(e)[0];o=this.session?.namespaces.polkadot.accounts.flat().filter(l=>l.includes(r)).map(l=>l.replace(`${r}:`,""));}let n=o.map(r=>({address:r,name:`${this.name} Account`,meta:{source:this.id},publicKey:void 0}));return this.emit("accountsChanged",[...n]),n}async disconnect(){try{this.provider&&await Promise.race([await this.provider.disconnect(),new Promise((e,t)=>setTimeout(()=>t(new Error("Disconnect timeout")),5e3))]);}catch{}await this.cleanup(),this.emit("disconnect");}async signMessage(e,t){if(!this.provider?.client||!this.session?.topic)throw new Error("Provider not initialized or not connected");try{let i=await this.getSigner();if(!i)throw new Error("No signer provided");let{signature:o}=await i.signRaw({address:t,data:e,type:"bytes"});return o}catch(i){throw console.error("Sign message error:",i),i}}hasConnectionUri(){return true}async getConnectionUri(){return this.connectionUri?this.connectionUri:new Promise(e=>{this.once("get_uri",t=>{this.connectionUri=t,e(t);});})}async getSigner(){if(!(!this.provider?.client||!this.session))return {signPayload:async e=>{let t=`polkadot:${e.genesisHash.replace("0x","").slice(0,32)}`,o=this.session.namespaces.polkadot.accounts.find(d=>{let c=d.replace(`${t}:`,"");return d.includes(t)&&chunk4IW7WG2H_cjs.c(e.address,c)});if(!o)throw new Error(`Chain ${e.genesisHash} is not supported by the wallet.}`);let n=o.replace(`${t}:`,""),r={...e,address:n};return await this.provider?.client?.request({topic:this.session.topic,chainId:`polkadot:${r.genesisHash.replace("0x","").slice(0,32)}`,request:{method:"polkadot_signTransaction",params:{address:n,transactionPayload:r}}})},signRaw:async e=>{let t=this.convertChainIdToCaipId(this.connectedChains)[0],o=this.session.namespaces.polkadot.accounts.find(d=>{let c=d.replace(`${t}:`,"");return d.includes(t)&&chunk4IW7WG2H_cjs.c(e.address,c)});if(!o)throw new Error(`No accounts available for chain ${t}`);let n=o.replace(`${t}:`,""),r={...e};return await this.provider.client.request({topic:this.session.topic,chainId:t,request:{method:"polkadot_signMessage",params:{address:n,message:r.data,type:r.type}}})}}}async startSubscription(){if(await this.cleanupSubscription(),!this.provider?.client||!this.session)throw new Error(`Connector ${this.id}: Cannot subscribe, provider or session not available.`);try{let e=async()=>{await this.cleanup(),this.emit("disconnect");};this.provider.client.on("session_delete",e),this.unsubscribe=()=>{this.provider?.client?.off("session_delete",e);};}catch{this.unsubscribe=null;}}async cleanupSubscription(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);}async cleanup(){await this.cleanupSubscription(),this.accounts=[],this.signer=void 0,this.provider=void 0,this.session=void 0;}},se=a=>new h(a);var ae=a=>chunk4IW7WG2H_cjs.i()?w():!chunk4IW7WG2H_cjs.i()&&"mobileOnly"in a&&a.mobileOnly?(console.error("Nova Wallet mobile connector is being used on a desktop device. This may not work as expected."),w()):new h({id:"nova",name:"Nova",icon:chunkQL6JNH54_cjs.m,links:{browserExtension:"https://novawallet.io"},...a});var ce=()=>new s({id:"OneKey",name:"OneKey",icon:chunkQL6JNH54_cjs.n,links:{browserExtension:"https://chromewebstore.google.com/detail/onekey-secure-crypto-wall/jnmbobjmhlngoefaiojfljckilhhlhcj"}});var le=()=>new s({id:"polkadot-js",name:"Polkadot{.js}",icon:chunkQL6JNH54_cjs.s,links:{browserExtension:"https://polkadot.js.org/extension"}});var de=()=>new s({id:"polkagate",name:"Polkagate",icon:chunkQL6JNH54_cjs.t,links:{browserExtension:"https://chromewebstore.google.com/detail/polkagate-the-gateway-to/ginchbkmljhldofnbjabmeophlhdldgp"}});var pe=()=>new s({id:"subwallet-js",name:"SubWallet",icon:chunkQL6JNH54_cjs.u,links:{browserExtension:"https://chromewebstore.google.com/detail/subwallet-polkadot-wallet/onhogfjeacnfoofkfgppdlbmlmnplgbn",deepLink:"https://mobile.subwallet.app/browser"}});var ue=()=>new s({id:"talisman",name:"Talisman",icon:chunkQL6JNH54_cjs.v,links:{browserExtension:"https://chromewebstore.google.com/detail/talisman-wallet/fijngjgcjhjmmpcmkeiomlglpeiijkld"}});
|
|
1
|
+
'use strict';var chunkVLCTGT6V_cjs=require('../chunk-VLCTGT6V.cjs'),chunkQL6JNH54_cjs=require('../chunk-QL6JNH54.cjs'),chunk4IW7WG2H_cjs=require('../chunk-4IW7WG2H.cjs'),eventemitter3=require('eventemitter3'),utils=require('dedot/utils'),dedot=require('dedot'),codecs=require('dedot/codecs'),merkleizedMetadata=require('dedot/merkleized-metadata');var u=class extends eventemitter3.EventEmitter{constructor(){super();this.links={};this.accounts=[];this.signer=void 0;this.connectionUri=void 0;}async getAccounts(){return [...this.accounts]}async getSigner(){return this.signer||console.warn(`Connector ${this.id}: Signer not available. Connection might be incomplete or failed.`),this.signer}hasConnectionUri(){return false}async getConnectionUri(){return this.connectionUri}};var s=class extends u{constructor(e){super();this.unsubscribe=null;this.specificInjector=void 0;this.id=e.id,this.name=e.name,this.icon=e.icon,this.links=e.links,this.injectorId=e.injectorId||e.id;}isInstalled(){if(typeof window>"u")return false;let e=window.injectedWeb3;return typeof e=="object"&&typeof e[this.injectorId]<"u"}async isAvailable(){return this.isInstalled()}async connect(e){if(this.signer)return [...this.accounts];if(!await this.isAvailable())throw new Error(`${this.name} extension not found or not enabled.`);try{if(this.specificInjector=await window.injectedWeb3[this.injectorId].enable(e),!this.specificInjector)throw new Error(`Failed to enable the '${this.id}' extension.`);if(this.signer=this.specificInjector.signer,!this.signer)throw new Error(`Could not get signer from ${this.name}.`);let t=await this.specificInjector.accounts.get();if(t.length===0)throw new Error(`No accounts found in ${this.name}. Make sure accounts are visible and access is granted.`);return this.accounts=chunk4IW7WG2H_cjs.e(t,this.id),await this.startSubscription(),this.emit("connect",[...this.accounts]),[...this.accounts]}catch(t){throw console.error(`Connector ${this.id}: Connection failed:`,t),await this.cleanup(),t}}async disconnect(){await this.cleanup(),this.emit("disconnect");}async signMessage(e,t){if(!t||!e)return;let i=await this.getSigner();if(!i||!i?.signRaw)throw new Error("Signer is not available or does not support signRaw.");if(!(await this.getAccounts()).some(n=>n.address.toLowerCase()===t.toLowerCase()))throw new Error(`Address ${t} is not managed by ${this.name}.`);try{let n=utils.stringToHex(e);return (await i.signRaw({address:t,data:n,type:"bytes"})).signature}catch(n){throw new Error(`Connector ${this.id}: Failed to sign message: ${n.message}`)}}async startSubscription(){if(await this.cleanupSubscription(),!this.specificInjector)throw new Error(`Connector ${this.id}: Cannot subscribe, specificInjector not available.`);try{this.unsubscribe=this.specificInjector.accounts.subscribe(e=>{let t=chunk4IW7WG2H_cjs.e(e,this.id);JSON.stringify(this.accounts)!==JSON.stringify(t)&&(this.accounts=t,this.emit("accountsChanged",[...this.accounts]));});}catch(e){console.error(`Connector ${this.id}: Failed to subscribe to accounts:`,e),this.unsubscribe=null;}}async cleanupSubscription(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);}async cleanup(){await this.cleanupSubscription(),this.accounts=[],this.signer=void 0,this.specificInjector=void 0;}};var Q=()=>new s({id:"enkrypt",name:"Enkrypt",icon:chunkQL6JNH54_cjs.h,links:{browserExtension:"https://www.enkrypt.com"}});var V=()=>new s({id:"fearless-wallet",name:"Fearless",icon:chunkQL6JNH54_cjs.i,links:{browserExtension:"https://fearlesswallet.io"}});function L(a,p=354){return `m/44'/${p}'/${a}'/0'/0'`}var k=class extends u{constructor(e){super();this.id="ledger";this.name="Ledger";this.icon=chunkQL6JNH54_cjs.k;this.links={};this.app=null;this.transport=null;this.accountIndex=0;this.chains=e.chains;}isInstalled(){return false}async isAvailable(){return !!(typeof navigator<"u"&&navigator.usb)}async ensureTransportOpen(){if(!this.transport)throw new Error("Transport not initialized");this.transport.device?.opened||await this.transport.open();}async ensureTransportClosed(){this.transport?.device?.opened&&await this.transport.close();}async connect(e,t,i){if(!await this.isAvailable())throw new Error("WebUSB is not supported in this browser.");try{let{Buffer:o}=await import('buffer');globalThis.Buffer=o;let{default:n}=await import('@ledgerhq/hw-transport-webusb');try{this.transport=await n.create();}catch(g){if(g.name==="SecurityError"||g.message?.includes("user gesture"))throw new Error("Ledger connection requires user interaction. Please click the connect button to connect your Ledger device.");this.transport=await n.request();}let{PolkadotGenericApp:r}=await import('@zondax/ledger-substrate'),l=new r(this.transport);this.app=l,await this.ensureTransportOpen();let d=L(this.accountIndex),c=await l.getAddressEd25519(d,0,!1);if(!c||!c.address)throw new Error("Failed to retrieve address from Ledger.");let m=c.pubKey?`0x${c.pubKey}`:void 0;return this.accounts=[{address:c.address,publicKey:m,name:"Ledger Wallet",type:"sr25519",meta:{source:"ledger",accountIndex:0,bip44Path:d}}],this.signer=await this.getSigner(),this.emit("connect",[...this.accounts]),[...this.accounts]}catch(o){throw console.error(`Connector ${this.id}: Connection failed:`,o),await this.cleanup(),o}}async disconnect(){await this.cleanup(),this.emit("disconnect");}async signMessage(e,t){let i=await this.getSigner();if(!i)throw new Error("No signer provided");let o=utils.stringToHex(e);return (await i.signRaw({address:t,data:o,type:"bytes"})).signature}async getSigner(){return {signRaw:async e=>{throw new Error("Ledger not supported signRaw!")},signPayload:async e=>{if(!this.app)throw new Error("Ledger not connected");let t=this.chains.find(J=>J.genesisHash===e.genesisHash);if(!t)throw new Error("Chain not found in your configuration chains");await this.ensureTransportOpen();let i=L(this.accountIndex),o=chunkVLCTGT6V_cjs.c(t.rpcUrls.webSocket),n=new dedot.LegacyClient(o);await n.connect();let r=await o.send("state_getMetadata",[]),l={tokenSymbol:t.nativeCurrency?.symbol||"DOT",decimals:t.nativeCurrency?.decimals||10},d=new merkleizedMetadata.MerkleizedMetadata(r,l),c=new dedot.ExtraSignedExtension(n,{signerAddress:e.address,payloadOptions:{metadataHash:utils.u8aToHex(d.digest())}});await c.init();let m=c.toRawPayload(e.method).data,g=d.proofForExtrinsicPayload(m),_=Buffer.from(utils.hexToU8a(m)),N=Buffer.from(g),{signature:S}=await this.app.signWithMetadataEd25519(i,_,N),{signatureTypeId:B,callTypeId:q}=n.registry.metadata.extrinsic,F=n.registry.findCodec(B),K=n.registry.findCodec(q),D=F.tryDecode(utils.u8aToHex(S)),z=K.tryDecode(e.method),j=new codecs.Extrinsic(n.registry,z);return j.attachSignature({address:e.address,signature:D,extra:c.data}),{id:0,signature:utils.u8aToHex(S),signedTransaction:j.toHex()}}}}async cleanup(){if(this.transport)try{await this.ensureTransportClosed();}catch(e){console.warn("Error closing transport:",e);}this.transport=null,this.app=null,this.accounts=[],this.signer=void 0;}},oe=a=>new k(a);var x=class extends s{constructor(e){super({...e});this.mimirReady=false;this.mimirInject();}isInstalled(){return this.mimirReady}async mimirInject(){try{if(!(typeof window<"u"&&window!==window.parent))return;let{isMimirReady:t,MIMIR_REGEXP:i,inject:o}=await import('@mimirdev/apps-inject'),n=await t();n&&i.test(n)&&(o(),this.mimirReady=!0);}catch(e){console.error("Failed to inject Mimir:",e);}}async connect(e){if(!this.mimirReady){let{MIMIR_REGEXP:t}=await import('@mimirdev/apps-inject');if(!window.origin||!t.test(window.origin)){window.open(`https://app.mimir.global/explorer/${encodeURIComponent(window.origin)}`);return}}return super.connect(e)}};function re(){return new x({id:"mimir",name:"Mimir",icon:chunkQL6JNH54_cjs.l,links:{browserExtension:"https://mimir.global"}})}var I=class extends s{constructor(){super({id:"nova-mobile",name:"Nova",icon:chunkQL6JNH54_cjs.m,injectorId:"polkadot-js",links:{deepLink:"https://app.novawallet.io/open/dapp"}});}isInstalled(){if(typeof window>"u")return false;let p=window.injectedWeb3;return typeof p=="object"&&typeof p["polkadot-js"]<"u"&&window.walletExtension?.isNovaWallet===true}async isAvailable(){return this.isInstalled()}},w=()=>new I;var h=class extends u{constructor(e){super();this.supportedChains=[];this.unsubscribe=null;this.id=e.id||"walletconnect",this.name=e.name||"WalletConnect",this.links=e.links||{},this.icon=e.icon||chunkQL6JNH54_cjs.w,this.projectId=e.projectId,this.relayUrl=e.relayUrl||"wss://relay.walletconnect.com",this.metadata=e.metadata,this.supportedChains=e.supportedChains||[];}isInstalled(){return false}async isAvailable(){return true}convertChainIdToCaipId(e){return e.map(t=>`polkadot:${(t.genesisHash||t).replace("0x","").slice(0,32)}`)}async connect(e,t){if(!this.projectId)throw new Error(`${this.name} requires a projectId. Please visit https://cloud.walletconnect.com to get one.`);let i=t?.length?t:this.supportedChains.length?this.supportedChains:void 0;if(!i||i.length===0)throw new Error(`${this.name} requires chains configuration.`);this.connectedChains=i;let{UniversalProvider:o}=await import('@walletconnect/universal-provider');try{if(this.provider=await o.init({projectId:this.projectId,relayUrl:this.relayUrl,metadata:this.metadata||{name:e,description:"LunoKit DApp",url:typeof window<"u"?window.location.origin:"",icons:[this.icon]}}),this.provider.session){this.session=this.provider.session;let c=this.getAccountsFromSession(i);return this.accounts=c,await this.startSubscription(),this.emit("connect",[...this.accounts]),[...this.accounts]}if(!this.provider?.client)throw new Error("Provider not initialized or not connected");let{uri:n,approval:r}=await this.provider.client.connect({requiredNamespaces:{polkadot:{methods:["polkadot_signMessage","polkadot_sendTransaction","polkadot_signTransaction","polkadot_requestAccounts"],chains:this.convertChainIdToCaipId(i),events:["accountsChanged","chainChanged","connect"]}},optionalNamespaces:{polkadot:{methods:["polkadot_signMessage","polkadot_sendTransaction","polkadot_signTransaction","polkadot_requestAccounts"],chains:this.convertChainIdToCaipId(i),events:["accountsChanged","chainChanged","connect"]}}});this.emit("get_uri",n);let l=await r();this.session=l,this.provider.session=l,this.connectionUri=void 0;let d=this.getAccountsFromSession(i);return this.accounts=d,await this.startSubscription(),this.emit("connect",[...this.accounts]),[...this.accounts]}catch(n){throw this.connectionUri=void 0,n}}getAccountsFromSession(e){let t=[e[0].genesisHash||e[0]],i=this.convertChainIdToCaipId(t)[0],o=this.session?.namespaces.polkadot.accounts.flat().filter(r=>r.includes(i)).map(r=>r.replace(`${i}:`,""));if(o&&o.length===0){console.error("No accounts found for the specified chain, please connect to the correct chain");let r=this.convertChainIdToCaipId(e)[0];o=this.session?.namespaces.polkadot.accounts.flat().filter(l=>l.includes(r)).map(l=>l.replace(`${r}:`,""));}let n=o.map(r=>({address:r,name:`${this.name} Account`,meta:{source:this.id},publicKey:void 0}));return this.emit("accountsChanged",[...n]),n}async disconnect(){try{this.provider&&await Promise.race([await this.provider.disconnect(),new Promise((e,t)=>setTimeout(()=>t(new Error("Disconnect timeout")),5e3))]);}catch{}await this.cleanup(),this.emit("disconnect");}async signMessage(e,t){if(!this.provider?.client||!this.session?.topic)throw new Error("Provider not initialized or not connected");try{let i=await this.getSigner();if(!i)throw new Error("No signer provided");let{signature:o}=await i.signRaw({address:t,data:e,type:"bytes"});return o}catch(i){throw console.error("Sign message error:",i),i}}hasConnectionUri(){return true}async getConnectionUri(){return this.connectionUri?this.connectionUri:new Promise(e=>{this.once("get_uri",t=>{this.connectionUri=t,e(t);});})}async getSigner(){if(!(!this.provider?.client||!this.session))return {signPayload:async e=>{let t=`polkadot:${e.genesisHash.replace("0x","").slice(0,32)}`,o=this.session.namespaces.polkadot.accounts.find(d=>{let c=d.replace(`${t}:`,"");return d.includes(t)&&chunk4IW7WG2H_cjs.c(e.address,c)});if(!o)throw new Error(`Chain ${e.genesisHash} is not supported by the wallet.}`);let n=o.replace(`${t}:`,""),r={...e,address:n};return await this.provider?.client?.request({topic:this.session.topic,chainId:`polkadot:${r.genesisHash.replace("0x","").slice(0,32)}`,request:{method:"polkadot_signTransaction",params:{address:n,transactionPayload:r}}})},signRaw:async e=>{let t=this.convertChainIdToCaipId(this.connectedChains)[0],o=this.session.namespaces.polkadot.accounts.find(d=>{let c=d.replace(`${t}:`,"");return d.includes(t)&&chunk4IW7WG2H_cjs.c(e.address,c)});if(!o)throw new Error(`No accounts available for chain ${t}`);let n=o.replace(`${t}:`,""),r={...e};return await this.provider.client.request({topic:this.session.topic,chainId:t,request:{method:"polkadot_signMessage",params:{address:n,message:r.data,type:r.type}}})}}}async startSubscription(){if(await this.cleanupSubscription(),!this.provider?.client||!this.session)throw new Error(`Connector ${this.id}: Cannot subscribe, provider or session not available.`);try{let e=async()=>{await this.cleanup(),this.emit("disconnect");};this.provider.client.on("session_delete",e),this.unsubscribe=()=>{this.provider?.client?.off("session_delete",e);};}catch{this.unsubscribe=null;}}async cleanupSubscription(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);}async cleanup(){await this.cleanupSubscription(),this.accounts=[],this.signer=void 0,this.provider=void 0,this.session=void 0;}},se=a=>new h(a);var ae=a=>chunk4IW7WG2H_cjs.i()?w():!chunk4IW7WG2H_cjs.i()&&"mobileOnly"in a&&a.mobileOnly?(console.error("Nova Wallet mobile connector is being used on a desktop device. This may not work as expected."),w()):new h({id:"nova",name:"Nova",icon:chunkQL6JNH54_cjs.m,links:{browserExtension:"https://novawallet.io"},...a});var ce=()=>new s({id:"OneKey",name:"OneKey",icon:chunkQL6JNH54_cjs.n,links:{browserExtension:"https://chromewebstore.google.com/detail/onekey-secure-crypto-wall/jnmbobjmhlngoefaiojfljckilhhlhcj"}});var le=()=>new s({id:"polkadot-js",name:"Polkadot{.js}",icon:chunkQL6JNH54_cjs.s,links:{browserExtension:"https://polkadot.js.org/extension"}});var de=()=>new s({id:"polkagate",name:"Polkagate",icon:chunkQL6JNH54_cjs.t,links:{browserExtension:"https://chromewebstore.google.com/detail/polkagate-the-gateway-to/ginchbkmljhldofnbjabmeophlhdldgp"}});var pe=()=>new s({id:"subwallet-js",name:"SubWallet",icon:chunkQL6JNH54_cjs.u,links:{browserExtension:"https://chromewebstore.google.com/detail/subwallet-polkadot-wallet/onhogfjeacnfoofkfgppdlbmlmnplgbn",deepLink:"https://mobile.subwallet.app/browser"}});var ue=()=>new s({id:"talisman",name:"Talisman",icon:chunkQL6JNH54_cjs.v,links:{browserExtension:"https://chromewebstore.google.com/detail/talisman-wallet/fijngjgcjhjmmpcmkeiomlglpeiijkld"}});
|
|
2
2
|
exports.BaseConnector=u;exports.InjectConnector=s;exports.enkryptConnector=Q;exports.fearlessConnector=V;exports.ledgerConnector=oe;exports.mimirConnector=re;exports.novaConnector=ae;exports.novaMobileConnector=w;exports.onekeyConnector=ce;exports.polkadotjsConnector=le;exports.polkagateConnector=de;exports.subwalletConnector=pe;exports.talismanConnector=ue;exports.walletConnectConnector=se;//# sourceMappingURL=index.cjs.map
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from 'eventemitter3';
|
|
2
|
-
import { c as ConnectorLinks, A as Account, S as Signer, b as Chain, W as WalletConnectConnectorOptions } from '../chain-
|
|
2
|
+
import { c as ConnectorLinks, A as Account, S as Signer, b as Chain, W as WalletConnectConnectorOptions } from '../chain-gX0PC0aM.cjs';
|
|
3
3
|
import 'dedot/types';
|
|
4
4
|
import 'dedot';
|
|
5
5
|
import 'dedot/shape';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from 'eventemitter3';
|
|
2
|
-
import { c as ConnectorLinks, A as Account, S as Signer, b as Chain, W as WalletConnectConnectorOptions } from '../chain-
|
|
2
|
+
import { c as ConnectorLinks, A as Account, S as Signer, b as Chain, W as WalletConnectConnectorOptions } from '../chain-gX0PC0aM.js';
|
|
3
3
|
import 'dedot/types';
|
|
4
4
|
import 'dedot';
|
|
5
5
|
import 'dedot/shape';
|
package/dist/connectors/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {c}from'../chunk-WICFE46E.js';import {h as h$1,i,k as k$1,l,m,w as w$1,n,s as s$1,t,u as u$1,v}from'../chunk-4237KM7K.js';import {e,c as c$1,i as i$1}from'../chunk-DRDSIIZY.js';import {EventEmitter}from'eventemitter3';import {stringToHex,u8aToHex,hexToU8a}from'dedot/utils';import {LegacyClient,ExtraSignedExtension}from'dedot';import {Extrinsic}from'dedot/codecs';import {MerkleizedMetadata}from'dedot/merkleized-metadata';var u=class extends EventEmitter{constructor(){super();this.links={};this.accounts=[];this.signer=void 0;this.connectionUri=void 0;}async getAccounts(){return [...this.accounts]}async getSigner(){return this.signer||console.warn(`Connector ${this.id}: Signer not available. Connection might be incomplete or failed.`),this.signer}hasConnectionUri(){return false}async getConnectionUri(){return this.connectionUri}};var s=class extends u{constructor(e){super();this.unsubscribe=null;this.specificInjector=void 0;this.id=e.id,this.name=e.name,this.icon=e.icon,this.links=e.links,this.injectorId=e.injectorId||e.id;}isInstalled(){if(typeof window>"u")return false;let e=window.injectedWeb3;return typeof e=="object"&&typeof e[this.injectorId]<"u"}async isAvailable(){return this.isInstalled()}async connect(e$1){if(this.signer)return [...this.accounts];if(!await this.isAvailable())throw new Error(`${this.name} extension not found or not enabled.`);try{if(this.specificInjector=await window.injectedWeb3[this.injectorId].enable(e$1),!this.specificInjector)throw new Error(`Failed to enable the '${this.id}' extension.`);if(this.signer=this.specificInjector.signer,!this.signer)throw new Error(`Could not get signer from ${this.name}.`);let t=await this.specificInjector.accounts.get();if(t.length===0)throw new Error(`No accounts found in ${this.name}. Make sure accounts are visible and access is granted.`);return this.accounts=e(t,this.id),await this.startSubscription(),this.emit("connect",[...this.accounts]),[...this.accounts]}catch(t){throw console.error(`Connector ${this.id}: Connection failed:`,t),await this.cleanup(),t}}async disconnect(){await this.cleanup(),this.emit("disconnect");}async signMessage(e,t){if(!t||!e)return;let i=await this.getSigner();if(!i||!i?.signRaw)throw new Error("Signer is not available or does not support signRaw.");if(!(await this.getAccounts()).some(n=>n.address.toLowerCase()===t.toLowerCase()))throw new Error(`Address ${t} is not managed by ${this.name}.`);try{let n=stringToHex(e);return (await i.signRaw({address:t,data:n,type:"bytes"})).signature}catch(n){throw new Error(`Connector ${this.id}: Failed to sign message: ${n.message}`)}}async startSubscription(){if(await this.cleanupSubscription(),!this.specificInjector)throw new Error(`Connector ${this.id}: Cannot subscribe, specificInjector not available.`);try{this.unsubscribe=this.specificInjector.accounts.subscribe(e$1=>{let t=e(e$1,this.id);JSON.stringify(this.accounts)!==JSON.stringify(t)&&(this.accounts=t,this.emit("accountsChanged",[...this.accounts]));});}catch(e){console.error(`Connector ${this.id}: Failed to subscribe to accounts:`,e),this.unsubscribe=null;}}async cleanupSubscription(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);}async cleanup(){await this.cleanupSubscription(),this.accounts=[],this.signer=void 0,this.specificInjector=void 0;}};var Q=()=>new s({id:"enkrypt",name:"Enkrypt",icon:h$1,links:{browserExtension:"https://www.enkrypt.com"}});var V=()=>new s({id:"fearless-wallet",name:"Fearless",icon:i,links:{browserExtension:"https://fearlesswallet.io"}});function L(a,p=354){return `m/44'/${p}'/${a}'/0'/0'`}var k=class extends u{constructor(e){super();this.id="ledger";this.name="Ledger";this.icon=k$1;this.links={};this.app=null;this.transport=null;this.accountIndex=0;this.chains=e.chains;}isInstalled(){return false}async isAvailable(){return !!(typeof navigator<"u"&&navigator.usb)}async ensureTransportOpen(){if(!this.transport)throw new Error("Transport not initialized");this.transport.device?.opened||await this.transport.open();}async ensureTransportClosed(){this.transport?.device?.opened&&await this.transport.close();}async connect(e,t,i){if(!await this.isAvailable())throw new Error("WebUSB is not supported in this browser.");try{let{Buffer:o}=await import('buffer');globalThis.Buffer=o;let{default:n}=await import('@ledgerhq/hw-transport-webusb');try{this.transport=await n.create();}catch(g){if(g.name==="SecurityError"||g.message?.includes("user gesture"))throw new Error("Ledger connection requires user interaction. Please click the connect button to connect your Ledger device.");this.transport=await n.request();}let{PolkadotGenericApp:r}=await import('@zondax/ledger-substrate'),l=new r(this.transport);this.app=l,await this.ensureTransportOpen();let d=L(this.accountIndex),c=await l.getAddressEd25519(d,0,!1);if(!c||!c.address)throw new Error("Failed to retrieve address from Ledger.");let m=c.pubKey?`0x${c.pubKey}`:void 0;return this.accounts=[{address:c.address,publicKey:m,name:"Ledger Wallet",type:"sr25519",meta:{source:"ledger",accountIndex:0,bip44Path:d}}],this.signer=await this.getSigner(),this.emit("connect",[...this.accounts]),[...this.accounts]}catch(o){throw console.error(`Connector ${this.id}: Connection failed:`,o),await this.cleanup(),o}}async disconnect(){await this.cleanup(),this.emit("disconnect");}async signMessage(e,t){let i=await this.getSigner();if(!i)throw new Error("No signer provided");let o=stringToHex(e);return (await i.signRaw({address:t,data:o,type:"bytes"})).signature}async getSigner(){return {signRaw:async e=>{throw new Error("Ledger not supported signRaw!")},signPayload:async e=>{if(!this.app)throw new Error("Ledger not connected");let t=this.chains.find(J=>J.genesisHash===e.genesisHash);if(!t)throw new Error("Chain not found in your configuration chains");await this.ensureTransportOpen();let i=L(this.accountIndex),o=c(t.rpcUrls.webSocket),n=new LegacyClient(o);await n.connect();let r=await o.send("state_getMetadata",[]),l={tokenSymbol:t.nativeCurrency?.symbol||"DOT",decimals:t.nativeCurrency?.decimals||10},d=new MerkleizedMetadata(r,l),c$1=new ExtraSignedExtension(n,{signerAddress:e.address,payloadOptions:{metadataHash:u8aToHex(d.digest())}});await c$1.init();let m=c$1.toRawPayload(e.method).data,g=d.proofForExtrinsicPayload(m),_=Buffer.from(hexToU8a(m)),N=Buffer.from(g),{signature:S}=await this.app.signWithMetadataEd25519(i,_,N),{signatureTypeId:B,callTypeId:q}=n.registry.metadata.extrinsic,F=n.registry.findCodec(B),K=n.registry.findCodec(q),D=F.tryDecode(u8aToHex(S)),z=K.tryDecode(e.method),j=new Extrinsic(n.registry,z);return j.attachSignature({address:e.address,signature:D,extra:c$1.data}),{id:0,signature:u8aToHex(S),signedTransaction:j.toHex()}}}}async cleanup(){if(this.transport)try{await this.ensureTransportClosed();}catch(e){console.warn("Error closing transport:",e);}this.transport=null,this.app=null,this.accounts=[],this.signer=void 0;}},oe=a=>new k(a);var x=class extends s{constructor(e){super({...e});this.mimirReady=false;this.mimirInject();}isInstalled(){return this.mimirReady}async mimirInject(){try{if(!(typeof window<"u"&&window!==window.parent))return;let{isMimirReady:t,MIMIR_REGEXP:i,inject:o}=await import('@mimirdev/apps-inject'),n=await t();n&&i.test(n)&&(o(),this.mimirReady=!0);}catch(e){console.error("Failed to inject Mimir:",e);}}async connect(e){if(!this.mimirReady){let{MIMIR_REGEXP:t}=await import('@mimirdev/apps-inject');if(!window.origin||!t.test(window.origin)){window.open(`https://app.mimir.global/explorer/${encodeURIComponent(window.origin)}`);return}}return super.connect(e)}};function re(){return new x({id:"mimir",name:"Mimir",icon:l,links:{browserExtension:"https://mimir.global"}})}var I=class extends s{constructor(){super({id:"nova-mobile",name:"Nova",icon:m,injectorId:"polkadot-js",links:{deepLink:"https://app.novawallet.io/open/dapp"}});}isInstalled(){if(typeof window>"u")return false;let p=window.injectedWeb3;return typeof p=="object"&&typeof p["polkadot-js"]<"u"&&window.walletExtension?.isNovaWallet===true}async isAvailable(){return this.isInstalled()}},w=()=>new I;var h=class extends u{constructor(e){super();this.supportedChains=[];this.unsubscribe=null;this.id=e.id||"walletconnect",this.name=e.name||"WalletConnect",this.links=e.links||{},this.icon=e.icon||w$1,this.projectId=e.projectId,this.relayUrl=e.relayUrl||"wss://relay.walletconnect.com",this.metadata=e.metadata,this.supportedChains=e.supportedChains||[];}isInstalled(){return false}async isAvailable(){return true}convertChainIdToCaipId(e){return e.map(t=>`polkadot:${(t.genesisHash||t).replace("0x","").slice(0,32)}`)}async connect(e,t){if(!this.projectId)throw new Error(`${this.name} requires a projectId. Please visit https://cloud.walletconnect.com to get one.`);let i=t?.length?t:this.supportedChains.length?this.supportedChains:void 0;if(!i||i.length===0)throw new Error(`${this.name} requires chains configuration.`);this.connectedChains=i;let{UniversalProvider:o}=await import('@walletconnect/universal-provider');try{if(this.provider=await o.init({projectId:this.projectId,relayUrl:this.relayUrl,metadata:this.metadata||{name:e,description:"LunoKit DApp",url:typeof window<"u"?window.location.origin:"",icons:[this.icon]}}),this.provider.session){this.session=this.provider.session;let c=this.getAccountsFromSession(i);return this.accounts=c,await this.startSubscription(),this.emit("connect",[...this.accounts]),[...this.accounts]}if(!this.provider?.client)throw new Error("Provider not initialized or not connected");let{uri:n,approval:r}=await this.provider.client.connect({requiredNamespaces:{polkadot:{methods:["polkadot_signMessage","polkadot_sendTransaction","polkadot_signTransaction","polkadot_requestAccounts"],chains:this.convertChainIdToCaipId(i),events:["accountsChanged","chainChanged","connect"]}},optionalNamespaces:{polkadot:{methods:["polkadot_signMessage","polkadot_sendTransaction","polkadot_signTransaction","polkadot_requestAccounts"],chains:this.convertChainIdToCaipId(i),events:["accountsChanged","chainChanged","connect"]}}});this.emit("get_uri",n);let l=await r();this.session=l,this.provider.session=l,this.connectionUri=void 0;let d=this.getAccountsFromSession(i);return this.accounts=d,await this.startSubscription(),this.emit("connect",[...this.accounts]),[...this.accounts]}catch(n){throw this.connectionUri=void 0,n}}getAccountsFromSession(e){let t=[e[0].genesisHash||e[0]],i=this.convertChainIdToCaipId(t)[0],o=this.session?.namespaces.polkadot.accounts.flat().filter(r=>r.includes(i)).map(r=>r.replace(`${i}:`,""));if(o&&o.length===0){console.error("No accounts found for the specified chain, please connect to the correct chain");let r=this.convertChainIdToCaipId(e)[0];o=this.session?.namespaces.polkadot.accounts.flat().filter(l=>l.includes(r)).map(l=>l.replace(`${r}:`,""));}let n=o.map(r=>({address:r,name:`${this.name} Account`,meta:{source:this.id},publicKey:void 0}));return this.emit("accountsChanged",[...n]),n}async disconnect(){try{this.provider&&await Promise.race([await this.provider.disconnect(),new Promise((e,t)=>setTimeout(()=>t(new Error("Disconnect timeout")),5e3))]);}catch{}await this.cleanup(),this.emit("disconnect");}async signMessage(e,t){if(!this.provider?.client||!this.session?.topic)throw new Error("Provider not initialized or not connected");try{let i=await this.getSigner();if(!i)throw new Error("No signer provided");let{signature:o}=await i.signRaw({address:t,data:e,type:"bytes"});return o}catch(i){throw console.error("Sign message error:",i),i}}hasConnectionUri(){return true}async getConnectionUri(){return this.connectionUri?this.connectionUri:new Promise(e=>{this.once("get_uri",t=>{this.connectionUri=t,e(t);});})}async getSigner(){if(!(!this.provider?.client||!this.session))return {signPayload:async e=>{let t=`polkadot:${e.genesisHash.replace("0x","").slice(0,32)}`,o=this.session.namespaces.polkadot.accounts.find(d=>{let c=d.replace(`${t}:`,"");return d.includes(t)&&c$1(e.address,c)});if(!o)throw new Error(`Chain ${e.genesisHash} is not supported by the wallet.}`);let n=o.replace(`${t}:`,""),r={...e,address:n};return await this.provider?.client?.request({topic:this.session.topic,chainId:`polkadot:${r.genesisHash.replace("0x","").slice(0,32)}`,request:{method:"polkadot_signTransaction",params:{address:n,transactionPayload:r}}})},signRaw:async e=>{let t=this.convertChainIdToCaipId(this.connectedChains)[0],o=this.session.namespaces.polkadot.accounts.find(d=>{let c=d.replace(`${t}:`,"");return d.includes(t)&&c$1(e.address,c)});if(!o)throw new Error(`No accounts available for chain ${t}`);let n=o.replace(`${t}:`,""),r={...e};return await this.provider.client.request({topic:this.session.topic,chainId:t,request:{method:"polkadot_signMessage",params:{address:n,message:r.data,type:r.type}}})}}}async startSubscription(){if(await this.cleanupSubscription(),!this.provider?.client||!this.session)throw new Error(`Connector ${this.id}: Cannot subscribe, provider or session not available.`);try{let e=async()=>{await this.cleanup(),this.emit("disconnect");};this.provider.client.on("session_delete",e),this.unsubscribe=()=>{this.provider?.client?.off("session_delete",e);};}catch{this.unsubscribe=null;}}async cleanupSubscription(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);}async cleanup(){await this.cleanupSubscription(),this.accounts=[],this.signer=void 0,this.provider=void 0,this.session=void 0;}},se=a=>new h(a);var ae=a=>i$1()?w():!i$1()&&"mobileOnly"in a&&a.mobileOnly?(console.error("Nova Wallet mobile connector is being used on a desktop device. This may not work as expected."),w()):new h({id:"nova",name:"Nova",icon:m,links:{browserExtension:"https://novawallet.io"},...a});var ce=()=>new s({id:"OneKey",name:"OneKey",icon:n,links:{browserExtension:"https://chromewebstore.google.com/detail/onekey-secure-crypto-wall/jnmbobjmhlngoefaiojfljckilhhlhcj"}});var le=()=>new s({id:"polkadot-js",name:"Polkadot{.js}",icon:s$1,links:{browserExtension:"https://polkadot.js.org/extension"}});var de=()=>new s({id:"polkagate",name:"Polkagate",icon:t,links:{browserExtension:"https://chromewebstore.google.com/detail/polkagate-the-gateway-to/ginchbkmljhldofnbjabmeophlhdldgp"}});var pe=()=>new s({id:"subwallet-js",name:"SubWallet",icon:u$1,links:{browserExtension:"https://chromewebstore.google.com/detail/subwallet-polkadot-wallet/onhogfjeacnfoofkfgppdlbmlmnplgbn",deepLink:"https://mobile.subwallet.app/browser"}});var ue=()=>new s({id:"talisman",name:"Talisman",icon:v,links:{browserExtension:"https://chromewebstore.google.com/detail/talisman-wallet/fijngjgcjhjmmpcmkeiomlglpeiijkld"}});
|
|
1
|
+
import {c}from'../chunk-A6UR3Q53.js';import {h as h$1,i,k as k$1,l,m,w as w$1,n,s as s$1,t,u as u$1,v}from'../chunk-4237KM7K.js';import {e,c as c$1,i as i$1}from'../chunk-DRDSIIZY.js';import {EventEmitter}from'eventemitter3';import {stringToHex,u8aToHex,hexToU8a}from'dedot/utils';import {LegacyClient,ExtraSignedExtension}from'dedot';import {Extrinsic}from'dedot/codecs';import {MerkleizedMetadata}from'dedot/merkleized-metadata';var u=class extends EventEmitter{constructor(){super();this.links={};this.accounts=[];this.signer=void 0;this.connectionUri=void 0;}async getAccounts(){return [...this.accounts]}async getSigner(){return this.signer||console.warn(`Connector ${this.id}: Signer not available. Connection might be incomplete or failed.`),this.signer}hasConnectionUri(){return false}async getConnectionUri(){return this.connectionUri}};var s=class extends u{constructor(e){super();this.unsubscribe=null;this.specificInjector=void 0;this.id=e.id,this.name=e.name,this.icon=e.icon,this.links=e.links,this.injectorId=e.injectorId||e.id;}isInstalled(){if(typeof window>"u")return false;let e=window.injectedWeb3;return typeof e=="object"&&typeof e[this.injectorId]<"u"}async isAvailable(){return this.isInstalled()}async connect(e$1){if(this.signer)return [...this.accounts];if(!await this.isAvailable())throw new Error(`${this.name} extension not found or not enabled.`);try{if(this.specificInjector=await window.injectedWeb3[this.injectorId].enable(e$1),!this.specificInjector)throw new Error(`Failed to enable the '${this.id}' extension.`);if(this.signer=this.specificInjector.signer,!this.signer)throw new Error(`Could not get signer from ${this.name}.`);let t=await this.specificInjector.accounts.get();if(t.length===0)throw new Error(`No accounts found in ${this.name}. Make sure accounts are visible and access is granted.`);return this.accounts=e(t,this.id),await this.startSubscription(),this.emit("connect",[...this.accounts]),[...this.accounts]}catch(t){throw console.error(`Connector ${this.id}: Connection failed:`,t),await this.cleanup(),t}}async disconnect(){await this.cleanup(),this.emit("disconnect");}async signMessage(e,t){if(!t||!e)return;let i=await this.getSigner();if(!i||!i?.signRaw)throw new Error("Signer is not available or does not support signRaw.");if(!(await this.getAccounts()).some(n=>n.address.toLowerCase()===t.toLowerCase()))throw new Error(`Address ${t} is not managed by ${this.name}.`);try{let n=stringToHex(e);return (await i.signRaw({address:t,data:n,type:"bytes"})).signature}catch(n){throw new Error(`Connector ${this.id}: Failed to sign message: ${n.message}`)}}async startSubscription(){if(await this.cleanupSubscription(),!this.specificInjector)throw new Error(`Connector ${this.id}: Cannot subscribe, specificInjector not available.`);try{this.unsubscribe=this.specificInjector.accounts.subscribe(e$1=>{let t=e(e$1,this.id);JSON.stringify(this.accounts)!==JSON.stringify(t)&&(this.accounts=t,this.emit("accountsChanged",[...this.accounts]));});}catch(e){console.error(`Connector ${this.id}: Failed to subscribe to accounts:`,e),this.unsubscribe=null;}}async cleanupSubscription(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);}async cleanup(){await this.cleanupSubscription(),this.accounts=[],this.signer=void 0,this.specificInjector=void 0;}};var Q=()=>new s({id:"enkrypt",name:"Enkrypt",icon:h$1,links:{browserExtension:"https://www.enkrypt.com"}});var V=()=>new s({id:"fearless-wallet",name:"Fearless",icon:i,links:{browserExtension:"https://fearlesswallet.io"}});function L(a,p=354){return `m/44'/${p}'/${a}'/0'/0'`}var k=class extends u{constructor(e){super();this.id="ledger";this.name="Ledger";this.icon=k$1;this.links={};this.app=null;this.transport=null;this.accountIndex=0;this.chains=e.chains;}isInstalled(){return false}async isAvailable(){return !!(typeof navigator<"u"&&navigator.usb)}async ensureTransportOpen(){if(!this.transport)throw new Error("Transport not initialized");this.transport.device?.opened||await this.transport.open();}async ensureTransportClosed(){this.transport?.device?.opened&&await this.transport.close();}async connect(e,t,i){if(!await this.isAvailable())throw new Error("WebUSB is not supported in this browser.");try{let{Buffer:o}=await import('buffer');globalThis.Buffer=o;let{default:n}=await import('@ledgerhq/hw-transport-webusb');try{this.transport=await n.create();}catch(g){if(g.name==="SecurityError"||g.message?.includes("user gesture"))throw new Error("Ledger connection requires user interaction. Please click the connect button to connect your Ledger device.");this.transport=await n.request();}let{PolkadotGenericApp:r}=await import('@zondax/ledger-substrate'),l=new r(this.transport);this.app=l,await this.ensureTransportOpen();let d=L(this.accountIndex),c=await l.getAddressEd25519(d,0,!1);if(!c||!c.address)throw new Error("Failed to retrieve address from Ledger.");let m=c.pubKey?`0x${c.pubKey}`:void 0;return this.accounts=[{address:c.address,publicKey:m,name:"Ledger Wallet",type:"sr25519",meta:{source:"ledger",accountIndex:0,bip44Path:d}}],this.signer=await this.getSigner(),this.emit("connect",[...this.accounts]),[...this.accounts]}catch(o){throw console.error(`Connector ${this.id}: Connection failed:`,o),await this.cleanup(),o}}async disconnect(){await this.cleanup(),this.emit("disconnect");}async signMessage(e,t){let i=await this.getSigner();if(!i)throw new Error("No signer provided");let o=stringToHex(e);return (await i.signRaw({address:t,data:o,type:"bytes"})).signature}async getSigner(){return {signRaw:async e=>{throw new Error("Ledger not supported signRaw!")},signPayload:async e=>{if(!this.app)throw new Error("Ledger not connected");let t=this.chains.find(J=>J.genesisHash===e.genesisHash);if(!t)throw new Error("Chain not found in your configuration chains");await this.ensureTransportOpen();let i=L(this.accountIndex),o=c(t.rpcUrls.webSocket),n=new LegacyClient(o);await n.connect();let r=await o.send("state_getMetadata",[]),l={tokenSymbol:t.nativeCurrency?.symbol||"DOT",decimals:t.nativeCurrency?.decimals||10},d=new MerkleizedMetadata(r,l),c$1=new ExtraSignedExtension(n,{signerAddress:e.address,payloadOptions:{metadataHash:u8aToHex(d.digest())}});await c$1.init();let m=c$1.toRawPayload(e.method).data,g=d.proofForExtrinsicPayload(m),_=Buffer.from(hexToU8a(m)),N=Buffer.from(g),{signature:S}=await this.app.signWithMetadataEd25519(i,_,N),{signatureTypeId:B,callTypeId:q}=n.registry.metadata.extrinsic,F=n.registry.findCodec(B),K=n.registry.findCodec(q),D=F.tryDecode(u8aToHex(S)),z=K.tryDecode(e.method),j=new Extrinsic(n.registry,z);return j.attachSignature({address:e.address,signature:D,extra:c$1.data}),{id:0,signature:u8aToHex(S),signedTransaction:j.toHex()}}}}async cleanup(){if(this.transport)try{await this.ensureTransportClosed();}catch(e){console.warn("Error closing transport:",e);}this.transport=null,this.app=null,this.accounts=[],this.signer=void 0;}},oe=a=>new k(a);var x=class extends s{constructor(e){super({...e});this.mimirReady=false;this.mimirInject();}isInstalled(){return this.mimirReady}async mimirInject(){try{if(!(typeof window<"u"&&window!==window.parent))return;let{isMimirReady:t,MIMIR_REGEXP:i,inject:o}=await import('@mimirdev/apps-inject'),n=await t();n&&i.test(n)&&(o(),this.mimirReady=!0);}catch(e){console.error("Failed to inject Mimir:",e);}}async connect(e){if(!this.mimirReady){let{MIMIR_REGEXP:t}=await import('@mimirdev/apps-inject');if(!window.origin||!t.test(window.origin)){window.open(`https://app.mimir.global/explorer/${encodeURIComponent(window.origin)}`);return}}return super.connect(e)}};function re(){return new x({id:"mimir",name:"Mimir",icon:l,links:{browserExtension:"https://mimir.global"}})}var I=class extends s{constructor(){super({id:"nova-mobile",name:"Nova",icon:m,injectorId:"polkadot-js",links:{deepLink:"https://app.novawallet.io/open/dapp"}});}isInstalled(){if(typeof window>"u")return false;let p=window.injectedWeb3;return typeof p=="object"&&typeof p["polkadot-js"]<"u"&&window.walletExtension?.isNovaWallet===true}async isAvailable(){return this.isInstalled()}},w=()=>new I;var h=class extends u{constructor(e){super();this.supportedChains=[];this.unsubscribe=null;this.id=e.id||"walletconnect",this.name=e.name||"WalletConnect",this.links=e.links||{},this.icon=e.icon||w$1,this.projectId=e.projectId,this.relayUrl=e.relayUrl||"wss://relay.walletconnect.com",this.metadata=e.metadata,this.supportedChains=e.supportedChains||[];}isInstalled(){return false}async isAvailable(){return true}convertChainIdToCaipId(e){return e.map(t=>`polkadot:${(t.genesisHash||t).replace("0x","").slice(0,32)}`)}async connect(e,t){if(!this.projectId)throw new Error(`${this.name} requires a projectId. Please visit https://cloud.walletconnect.com to get one.`);let i=t?.length?t:this.supportedChains.length?this.supportedChains:void 0;if(!i||i.length===0)throw new Error(`${this.name} requires chains configuration.`);this.connectedChains=i;let{UniversalProvider:o}=await import('@walletconnect/universal-provider');try{if(this.provider=await o.init({projectId:this.projectId,relayUrl:this.relayUrl,metadata:this.metadata||{name:e,description:"LunoKit DApp",url:typeof window<"u"?window.location.origin:"",icons:[this.icon]}}),this.provider.session){this.session=this.provider.session;let c=this.getAccountsFromSession(i);return this.accounts=c,await this.startSubscription(),this.emit("connect",[...this.accounts]),[...this.accounts]}if(!this.provider?.client)throw new Error("Provider not initialized or not connected");let{uri:n,approval:r}=await this.provider.client.connect({requiredNamespaces:{polkadot:{methods:["polkadot_signMessage","polkadot_sendTransaction","polkadot_signTransaction","polkadot_requestAccounts"],chains:this.convertChainIdToCaipId(i),events:["accountsChanged","chainChanged","connect"]}},optionalNamespaces:{polkadot:{methods:["polkadot_signMessage","polkadot_sendTransaction","polkadot_signTransaction","polkadot_requestAccounts"],chains:this.convertChainIdToCaipId(i),events:["accountsChanged","chainChanged","connect"]}}});this.emit("get_uri",n);let l=await r();this.session=l,this.provider.session=l,this.connectionUri=void 0;let d=this.getAccountsFromSession(i);return this.accounts=d,await this.startSubscription(),this.emit("connect",[...this.accounts]),[...this.accounts]}catch(n){throw this.connectionUri=void 0,n}}getAccountsFromSession(e){let t=[e[0].genesisHash||e[0]],i=this.convertChainIdToCaipId(t)[0],o=this.session?.namespaces.polkadot.accounts.flat().filter(r=>r.includes(i)).map(r=>r.replace(`${i}:`,""));if(o&&o.length===0){console.error("No accounts found for the specified chain, please connect to the correct chain");let r=this.convertChainIdToCaipId(e)[0];o=this.session?.namespaces.polkadot.accounts.flat().filter(l=>l.includes(r)).map(l=>l.replace(`${r}:`,""));}let n=o.map(r=>({address:r,name:`${this.name} Account`,meta:{source:this.id},publicKey:void 0}));return this.emit("accountsChanged",[...n]),n}async disconnect(){try{this.provider&&await Promise.race([await this.provider.disconnect(),new Promise((e,t)=>setTimeout(()=>t(new Error("Disconnect timeout")),5e3))]);}catch{}await this.cleanup(),this.emit("disconnect");}async signMessage(e,t){if(!this.provider?.client||!this.session?.topic)throw new Error("Provider not initialized or not connected");try{let i=await this.getSigner();if(!i)throw new Error("No signer provided");let{signature:o}=await i.signRaw({address:t,data:e,type:"bytes"});return o}catch(i){throw console.error("Sign message error:",i),i}}hasConnectionUri(){return true}async getConnectionUri(){return this.connectionUri?this.connectionUri:new Promise(e=>{this.once("get_uri",t=>{this.connectionUri=t,e(t);});})}async getSigner(){if(!(!this.provider?.client||!this.session))return {signPayload:async e=>{let t=`polkadot:${e.genesisHash.replace("0x","").slice(0,32)}`,o=this.session.namespaces.polkadot.accounts.find(d=>{let c=d.replace(`${t}:`,"");return d.includes(t)&&c$1(e.address,c)});if(!o)throw new Error(`Chain ${e.genesisHash} is not supported by the wallet.}`);let n=o.replace(`${t}:`,""),r={...e,address:n};return await this.provider?.client?.request({topic:this.session.topic,chainId:`polkadot:${r.genesisHash.replace("0x","").slice(0,32)}`,request:{method:"polkadot_signTransaction",params:{address:n,transactionPayload:r}}})},signRaw:async e=>{let t=this.convertChainIdToCaipId(this.connectedChains)[0],o=this.session.namespaces.polkadot.accounts.find(d=>{let c=d.replace(`${t}:`,"");return d.includes(t)&&c$1(e.address,c)});if(!o)throw new Error(`No accounts available for chain ${t}`);let n=o.replace(`${t}:`,""),r={...e};return await this.provider.client.request({topic:this.session.topic,chainId:t,request:{method:"polkadot_signMessage",params:{address:n,message:r.data,type:r.type}}})}}}async startSubscription(){if(await this.cleanupSubscription(),!this.provider?.client||!this.session)throw new Error(`Connector ${this.id}: Cannot subscribe, provider or session not available.`);try{let e=async()=>{await this.cleanup(),this.emit("disconnect");};this.provider.client.on("session_delete",e),this.unsubscribe=()=>{this.provider?.client?.off("session_delete",e);};}catch{this.unsubscribe=null;}}async cleanupSubscription(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);}async cleanup(){await this.cleanupSubscription(),this.accounts=[],this.signer=void 0,this.provider=void 0,this.session=void 0;}},se=a=>new h(a);var ae=a=>i$1()?w():!i$1()&&"mobileOnly"in a&&a.mobileOnly?(console.error("Nova Wallet mobile connector is being used on a desktop device. This may not work as expected."),w()):new h({id:"nova",name:"Nova",icon:m,links:{browserExtension:"https://novawallet.io"},...a});var ce=()=>new s({id:"OneKey",name:"OneKey",icon:n,links:{browserExtension:"https://chromewebstore.google.com/detail/onekey-secure-crypto-wall/jnmbobjmhlngoefaiojfljckilhhlhcj"}});var le=()=>new s({id:"polkadot-js",name:"Polkadot{.js}",icon:s$1,links:{browserExtension:"https://polkadot.js.org/extension"}});var de=()=>new s({id:"polkagate",name:"Polkagate",icon:t,links:{browserExtension:"https://chromewebstore.google.com/detail/polkagate-the-gateway-to/ginchbkmljhldofnbjabmeophlhdldgp"}});var pe=()=>new s({id:"subwallet-js",name:"SubWallet",icon:u$1,links:{browserExtension:"https://chromewebstore.google.com/detail/subwallet-polkadot-wallet/onhogfjeacnfoofkfgppdlbmlmnplgbn",deepLink:"https://mobile.subwallet.app/browser"}});var ue=()=>new s({id:"talisman",name:"Talisman",icon:v,links:{browserExtension:"https://chromewebstore.google.com/detail/talisman-wallet/fijngjgcjhjmmpcmkeiomlglpeiijkld"}});
|
|
2
2
|
export{u as BaseConnector,s as InjectConnector,Q as enkryptConnector,V as fearlessConnector,oe as ledgerConnector,re as mimirConnector,ae as novaConnector,w as novaMobileConnector,ce as onekeyConnector,le as polkadotjsConnector,de as polkagateConnector,pe as subwalletConnector,ue as talismanConnector,se as walletConnectConnector};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkVLCTGT6V_cjs=require('./chunk-VLCTGT6V.cjs');Object.defineProperty(exports,"createConfig",{enumerable:true,get:function(){return chunkVLCTGT6V_cjs.b}});Object.defineProperty(exports,"createStorage",{enumerable:true,get:function(){return chunkVLCTGT6V_cjs.a}});Object.defineProperty(exports,"wsProvider",{enumerable:true,get:function(){return chunkVLCTGT6V_cjs.c}});//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as CreateConfigParameters, a as Config, R as RawStorage, L as LunoStorage, T as Transport } from './chain-
|
|
1
|
+
import { C as CreateConfigParameters, a as Config, R as RawStorage, L as LunoStorage, T as Transport } from './chain-gX0PC0aM.cjs';
|
|
2
2
|
import { WsProvider } from 'dedot';
|
|
3
3
|
import 'dedot/types';
|
|
4
4
|
import 'dedot/shape';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as CreateConfigParameters, a as Config, R as RawStorage, L as LunoStorage, T as Transport } from './chain-
|
|
1
|
+
import { C as CreateConfigParameters, a as Config, R as RawStorage, L as LunoStorage, T as Transport } from './chain-gX0PC0aM.js';
|
|
2
2
|
import { WsProvider } from 'dedot';
|
|
3
3
|
import 'dedot/types';
|
|
4
4
|
import 'dedot/shape';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as createConfig,a as createStorage,c as wsProvider}from'./chunk-
|
|
1
|
+
export{b as createConfig,a as createStorage,c as wsProvider}from'./chunk-A6UR3Q53.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/types/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { e as ACCOUNT_TYPE, A as Account, d as AccountBalance, b as Chain, a as Config, f as Connector, c as ConnectorLinks, C as CreateConfigParameters, H as HexString, L as LunoStorage, R as RawStorage, S as Signer, T as Transport, W as WalletConnectConnectorOptions } from '../chain-
|
|
1
|
+
export { e as ACCOUNT_TYPE, A as Account, d as AccountBalance, b as Chain, a as Config, f as Connector, g as ConnectorGroup, c as ConnectorLinks, C as CreateConfigParameters, H as HexString, L as LunoStorage, R as RawStorage, S as Signer, T as Transport, W as WalletConnectConnectorOptions } from '../chain-gX0PC0aM.cjs';
|
|
2
2
|
export { PolkadotSigner as PapiSigner } from '@polkadot-api/pjs-signer';
|
|
3
3
|
import 'dedot/types';
|
|
4
4
|
import 'dedot';
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { e as ACCOUNT_TYPE, A as Account, d as AccountBalance, b as Chain, a as Config, f as Connector, c as ConnectorLinks, C as CreateConfigParameters, H as HexString, L as LunoStorage, R as RawStorage, S as Signer, T as Transport, W as WalletConnectConnectorOptions } from '../chain-
|
|
1
|
+
export { e as ACCOUNT_TYPE, A as Account, d as AccountBalance, b as Chain, a as Config, f as Connector, g as ConnectorGroup, c as ConnectorLinks, C as CreateConfigParameters, H as HexString, L as LunoStorage, R as RawStorage, S as Signer, T as Transport, W as WalletConnectConnectorOptions } from '../chain-gX0PC0aM.js';
|
|
2
2
|
export { PolkadotSigner as PapiSigner } from '@polkadot-api/pjs-signer';
|
|
3
3
|
import 'dedot/types';
|
|
4
4
|
import 'dedot';
|
package/dist/utils/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { InjectedAccount } from 'dedot/types';
|
|
2
|
-
import { A as Account, b as Chain, S as Signer } from '../chain-
|
|
2
|
+
import { A as Account, b as Chain, S as Signer } from '../chain-gX0PC0aM.cjs';
|
|
3
3
|
import { PolkadotSigner } from '@polkadot-api/pjs-signer';
|
|
4
4
|
export { PolkadotSigner as PapiSigner } from '@polkadot-api/pjs-signer';
|
|
5
5
|
export { formatBalance as formatBalanceWithUnit } from 'dedot/utils';
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { InjectedAccount } from 'dedot/types';
|
|
2
|
-
import { A as Account, b as Chain, S as Signer } from '../chain-
|
|
2
|
+
import { A as Account, b as Chain, S as Signer } from '../chain-gX0PC0aM.js';
|
|
3
3
|
import { PolkadotSigner } from '@polkadot-api/pjs-signer';
|
|
4
4
|
export { PolkadotSigner as PapiSigner } from '@polkadot-api/pjs-signer';
|
|
5
5
|
export { formatBalance as formatBalanceWithUnit } from 'dedot/utils';
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@luno-kit/core",
|
|
3
3
|
"description": "Core module for Luno, providing foundational utilities, types, configuration, and connectors for Polkadot wallet interactions.",
|
|
4
|
-
"version": "0.0.12
|
|
4
|
+
"version": "0.0.12",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"polkadot",
|
package/dist/chunk-UFHE4N3F.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
'use strict';var dedot=require('dedot');function g({storage:t,keyPrefix:a="luno."}){let r=e=>`${a}${e}`;return {async getItem(e){try{let o=r(e),n=await t.getItem(o);return n==null?null:String(n)}catch(o){return console.error(`[LunoStorage] Error getting item "${e}" (full key: "${r(e)}"):`,o),null}},async setItem(e,o){try{let n=r(e);await t.setItem(n,o);}catch(n){console.error(`[LunoStorage] Error setting item "${e}" (full key: "${r(e)}"):`,n);}},async removeItem(e){try{let o=r(e);await t.removeItem(o);}catch(o){console.error(`[LunoStorage] Error removing item "${e}" (full key: "${r(e)}"):`,o);}}}}var h={getItem:async t=>null,setItem:async(t,a)=>{},removeItem:async t=>{}},w=g({storage:typeof window<"u"&&window.localStorage?window.localStorage:h,keyPrefix:"luno."});function C(t){let a={};for(let r of t){let e=r.rpcUrls.webSocket;e?a[r.genesisHash]=e:console.warn(`No WebSocket URL found for chain "${r.name}" (${r.genesisHash}). Skipping transport generation.`);}return a}function R(t){let{appName:a="My Luno App",chains:r=[],connectors:e,transports:o={},storage:n=w,autoConnect:l=true,cacheMetadata:p=true,metadata:m,scaledResponses:u,customTypes:f,customRpc:y,subscan:d}=t;if(!e||e.length===0)throw new Error("No connectors provided. Wallet connection features will be unavailable.");let i=r.length>0?C(r):{},c=o?{...i,...o}:i;if(r.length>0)for(let s of r)c[s.genesisHash]||console.warn(`Missing transport for chain "${s.name}" (genesisHash: ${s.genesisHash}). Chain functionality may be limited.`);return {customRpc:y,customTypes:f,cacheMetadata:p,metadata:m,scaledResponses:u,appName:a,chains:Object.freeze([...r]),connectors:Object.freeze([...e]),transports:Object.freeze({...c}),storage:n,autoConnect:l,subscan:d}}function I(t){return new dedot.WsProvider(t)}exports.a=g;exports.b=R;exports.c=I;//# sourceMappingURL=chunk-UFHE4N3F.cjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-UFHE4N3F.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config/createStorage.ts","../src/config/createConfig.ts","../src/config/providers.ts"],"names":["createStorage","storage","keyPrefix","getKey","suffix","keySuffix","fullKey","value","error","noopStorage","_key","_value","defaultLunoStorage","generateTransportsFromChains","chains","transports","chain","wsUrl","createConfig","parameters","appName","connectors","autoConnect","cacheMetadata","metadata","scaledResponses","customTypes","customRpc","subscan","transportsFromChains","finalTransports","wsProvider","url","WsProvider"],"mappings":"wCAgBO,SAASA,EAAc,CAC5B,OAAA,CAAAC,EACA,SAAA,CAAAC,CAAAA,CAAY,OACd,CAAA,CAAyC,CACvC,IAAMC,CAAAA,CAAUC,GAA2B,CAAA,EAAGF,CAAS,GAAGE,CAAM,CAAA,CAAA,CAEhE,OAAO,CACL,MAAM,OAAA,CAAQC,CAAAA,CAA2C,CACvD,GAAI,CACF,IAAMC,CAAAA,CAAUH,CAAAA,CAAOE,CAAS,CAAA,CAE1BE,CAAAA,CAAQ,MAAMN,CAAAA,CAAQ,QAAQK,CAAO,CAAA,CAE3C,OAAOC,CAAAA,EAAS,IAAA,CAAO,KAAO,MAAA,CAAOA,CAAK,CAC5C,CAAA,MAASC,EAAO,CACd,OAAA,OAAA,CAAQ,MACN,CAAA,kCAAA,EAAqCH,CAAS,iBAAiBF,CAAAA,CAAOE,CAAS,CAAC,CAAA,GAAA,CAAA,CAChFG,CACF,CAAA,CACO,IACT,CACF,CAAA,CAEA,MAAM,QAAQH,CAAAA,CAAmBE,CAAAA,CAA8B,CAC7D,GAAI,CACF,IAAMD,CAAAA,CAAUH,EAAOE,CAAS,CAAA,CAEhC,MAAMJ,CAAAA,CAAQ,OAAA,CAAQK,CAAAA,CAASC,CAAK,EACtC,CAAA,MAASC,CAAAA,CAAO,CACd,OAAA,CAAQ,KAAA,CACN,qCAAqCH,CAAS,CAAA,cAAA,EAAiBF,CAAAA,CAAOE,CAAS,CAAC,CAAA,GAAA,CAAA,CAChFG,CACF,EAEF,CACF,CAAA,CAEA,MAAM,UAAA,CAAWH,CAAAA,CAAkC,CACjD,GAAI,CACF,IAAMC,CAAAA,CAAUH,EAAOE,CAAS,CAAA,CAEhC,MAAMJ,CAAAA,CAAQ,UAAA,CAAWK,CAAO,EAClC,OAASE,CAAAA,CAAO,CACd,QAAQ,KAAA,CACN,CAAA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AAW,EACvC,MAAM,IAAI,MAAM,yEAAyE,CAAA,CAG3F,IAAMQ,CAAAA,CAAuBf,EAAO,MAAA,CAAS,CAAA,CAAID,EAA6BC,CAAM,CAAA,CAAI,EAAC,CAEnFgB,CAAAA,CAAkBf,CAAAA,CACpB,CAAE,GAAGc,CAAAA,CAAsB,GAAGd,CAAW,CAAA,CACzCc,CAAAA,CAEJ,GAAIf,CAAAA,CAAO,MAAA,CAAS,CAAA,CAClB,IAAA,IAAWE,KAASF,CAAAA,CACbgB,CAAAA,CAAgBd,EAAM,WAAW,CAAA,EACpC,QAAQ,IAAA,CACN,CAAA,6BAAA,EAAgCA,CAAAA,CAAM,IAAI,mBAAmBA,CAAAA,CAAM,WAAW,wCAChF,CAAA,CAsBN,OAjBe,CACb,SAAA,CAAAW,CAAAA,CACA,WAAA,CAAAD,CAAAA,CACA,cAAAH,CAAAA,CACA,QAAA,CAAAC,EACA,eAAA,CAAAC,CAAAA,CAEA,QAAAL,CAAAA,CACA,MAAA,CAAQ,MAAA,CAAO,MAAA,CAAO,CAAC,GAAGN,CAAM,CAAC,CAAA,CACjC,UAAA,CAAY,OAAO,MAAA,CAAO,CAAC,GAAGO,CAAU,CAAC,CAAA,CACzC,UAAA,CAAY,OAAO,MAAA,CAAO,CAAE,GAAGS,CAAgB,CAAC,CAAA,CAChD,OAAA,CAAA7B,EACA,WAAA,CAAAqB,CAAAA,CAEA,QAAAM,CACF,CAGF,CCpFO,SAASG,EAAWC,CAAAA,CAA4B,CACrD,OAAO,IAAIC,gBAAAA,CAAWD,CAAe,CACvC","file":"chunk-UFHE4N3F.cjs","sourcesContent":["import type { LunoStorage, RawStorage } from '../types';\n\n// Defines the parameters for the createStorage function.\nexport interface CreateStorageParameters {\n storage: RawStorage;\n keyPrefix?: Optional<string>; // Optional key prefix, e.g., \"luno.\"\n}\n\n/**\n * Creates a LunoStorage object that wraps a raw storage mechanism (like localStorage)\n * to provide a consistent async API with key prefixing and error handling.\n *\n * @param storage The raw storage mechanism (e.g., window.localStorage).\n * @param keyPrefix An optional prefix for all storage keys to avoid collisions.\n * @returns A LunoStorage object.\n */\nexport function createStorage({\n storage,\n keyPrefix = 'luno.', // Default key prefix\n}: CreateStorageParameters): LunoStorage {\n const getKey = (suffix: string): string => `${keyPrefix}${suffix}`;\n\n return {\n async getItem(keySuffix: string): Promise<string | null> {\n try {\n const fullKey = getKey(keySuffix);\n // Await to handle both sync and async RawStorage getItem methods consistently\n const value = await storage.getItem(fullKey);\n // Normalize undefined or null to null\n return value == null ? null : String(value);\n } catch (error) {\n console.error(\n `[LunoStorage] Error getting item \"${keySuffix}\" (full key: \"${getKey(keySuffix)}\"):`,\n error\n );\n return null; // Return null on error to indicate failure\n }\n },\n\n async setItem(keySuffix: string, value: string): Promise<void> {\n try {\n const fullKey = getKey(keySuffix);\n // Await to handle both sync and async RawStorage setItem methods consistently\n await storage.setItem(fullKey, value);\n } catch (error) {\n console.error(\n `[LunoStorage] Error setting item \"${keySuffix}\" (full key: \"${getKey(keySuffix)}\"):`,\n error\n );\n // Errors during setItem are logged but don't typically need to be propagated further in the same way getItem might.\n }\n },\n\n async removeItem(keySuffix: string): Promise<void> {\n try {\n const fullKey = getKey(keySuffix);\n // Await to handle both sync and async RawStorage removeItem methods consistently\n await storage.removeItem(fullKey);\n } catch (error) {\n console.error(\n `[LunoStorage] Error removing item \"${keySuffix}\" (full key: \"${getKey(keySuffix)}\"):`,\n error\n );\n }\n },\n };\n}\n","import type {\n Chain,\n Config,\n Connector,\n CreateConfigParameters,\n RawStorage,\n Transport,\n} from '../types';\nimport { createStorage } from './createStorage';\n\nconst noopStorage: RawStorage = {\n getItem: async (_key: string) => null,\n setItem: async (_key: string, _value: string) => {},\n removeItem: async (_key: string) => {},\n};\n\nconst defaultLunoStorage = createStorage({\n storage: typeof window !== 'undefined' && window.localStorage ? window.localStorage : noopStorage,\n keyPrefix: 'luno.',\n});\n\nfunction generateTransportsFromChains(chains: readonly Chain[]): Record<string, Transport> {\n const transports: Record<string, Transport> = {};\n\n for (const chain of chains) {\n const wsUrl = chain.rpcUrls.webSocket;\n if (wsUrl) {\n transports[chain.genesisHash] = wsUrl;\n } else {\n console.warn(\n `No WebSocket URL found for chain \"${chain.name}\" (${chain.genesisHash}). Skipping transport generation.`\n );\n }\n }\n\n return transports;\n}\n\nexport function createConfig(parameters: CreateConfigParameters): Config {\n const {\n appName = 'My Luno App',\n chains = [],\n connectors,\n transports = {},\n storage = defaultLunoStorage,\n autoConnect = true,\n cacheMetadata = true,\n metadata,\n scaledResponses,\n customTypes,\n customRpc,\n subscan,\n } = parameters;\n\n if (!connectors || connectors.length === 0) {\n throw new Error('No connectors provided. Wallet connection features will be unavailable.');\n }\n\n const transportsFromChains = chains.length > 0 ? generateTransportsFromChains(chains) : {};\n\n const finalTransports = transports\n ? { ...transportsFromChains, ...transports }\n : transportsFromChains;\n\n if (chains.length > 0) {\n for (const chain of chains) {\n if (!finalTransports[chain.genesisHash]) {\n console.warn(\n `Missing transport for chain \"${chain.name}\" (genesisHash: ${chain.genesisHash}). Chain functionality may be limited.`\n );\n }\n }\n }\n\n const config = {\n customRpc,\n customTypes,\n cacheMetadata,\n metadata,\n scaledResponses,\n\n appName,\n chains: Object.freeze([...chains]) as readonly Chain[],\n connectors: Object.freeze([...connectors]) as readonly Connector[],\n transports: Object.freeze({ ...finalTransports }) as Readonly<Record<string, Transport>>,\n storage,\n autoConnect,\n\n subscan,\n };\n\n return config;\n}\n","import { WsProvider } from 'dedot';\nimport type { Transport } from '../types';\n\n/**\n * create a WebSocket Transport (WsProvider) instance.\n * @param url - WebSocket RPC URL or URL array (for fallback).\n * @returns WsProvider instance.\n */\nexport function wsProvider(url: Transport): WsProvider {\n return new WsProvider(url as string[]);\n}\n\nexport type { Transport };\n"]}
|
package/dist/chunk-WICFE46E.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {WsProvider}from'dedot';function g({storage:t,keyPrefix:a="luno."}){let r=e=>`${a}${e}`;return {async getItem(e){try{let o=r(e),n=await t.getItem(o);return n==null?null:String(n)}catch(o){return console.error(`[LunoStorage] Error getting item "${e}" (full key: "${r(e)}"):`,o),null}},async setItem(e,o){try{let n=r(e);await t.setItem(n,o);}catch(n){console.error(`[LunoStorage] Error setting item "${e}" (full key: "${r(e)}"):`,n);}},async removeItem(e){try{let o=r(e);await t.removeItem(o);}catch(o){console.error(`[LunoStorage] Error removing item "${e}" (full key: "${r(e)}"):`,o);}}}}var h={getItem:async t=>null,setItem:async(t,a)=>{},removeItem:async t=>{}},w=g({storage:typeof window<"u"&&window.localStorage?window.localStorage:h,keyPrefix:"luno."});function C(t){let a={};for(let r of t){let e=r.rpcUrls.webSocket;e?a[r.genesisHash]=e:console.warn(`No WebSocket URL found for chain "${r.name}" (${r.genesisHash}). Skipping transport generation.`);}return a}function R(t){let{appName:a="My Luno App",chains:r=[],connectors:e,transports:o={},storage:n=w,autoConnect:l=true,cacheMetadata:p=true,metadata:m,scaledResponses:u,customTypes:f,customRpc:y,subscan:d}=t;if(!e||e.length===0)throw new Error("No connectors provided. Wallet connection features will be unavailable.");let i=r.length>0?C(r):{},c=o?{...i,...o}:i;if(r.length>0)for(let s of r)c[s.genesisHash]||console.warn(`Missing transport for chain "${s.name}" (genesisHash: ${s.genesisHash}). Chain functionality may be limited.`);return {customRpc:y,customTypes:f,cacheMetadata:p,metadata:m,scaledResponses:u,appName:a,chains:Object.freeze([...r]),connectors:Object.freeze([...e]),transports:Object.freeze({...c}),storage:n,autoConnect:l,subscan:d}}function I(t){return new WsProvider(t)}export{g as a,R as b,I as c};//# sourceMappingURL=chunk-WICFE46E.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-WICFE46E.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config/createStorage.ts","../src/config/createConfig.ts","../src/config/providers.ts"],"names":["createStorage","storage","keyPrefix","getKey","suffix","keySuffix","fullKey","value","error","noopStorage","_key","_value","defaultLunoStorage","generateTransportsFromChains","chains","transports","chain","wsUrl","createConfig","parameters","appName","connectors","autoConnect","cacheMetadata","metadata","scaledResponses","customTypes","customRpc","subscan","transportsFromChains","finalTransports","wsProvider","url","WsProvider"],"mappings":"+BAgBO,SAASA,EAAc,CAC5B,OAAA,CAAAC,EACA,SAAA,CAAAC,CAAAA,CAAY,OACd,CAAA,CAAyC,CACvC,IAAMC,CAAAA,CAAUC,GAA2B,CAAA,EAAGF,CAAS,GAAGE,CAAM,CAAA,CAAA,CAEhE,OAAO,CACL,MAAM,OAAA,CAAQC,CAAAA,CAA2C,CACvD,GAAI,CACF,IAAMC,CAAAA,CAAUH,CAAAA,CAAOE,CAAS,CAAA,CAE1BE,CAAAA,CAAQ,MAAMN,CAAAA,CAAQ,QAAQK,CAAO,CAAA,CAE3C,OAAOC,CAAAA,EAAS,IAAA,CAAO,KAAO,MAAA,CAAOA,CAAK,CAC5C,CAAA,MAASC,EAAO,CACd,OAAA,OAAA,CAAQ,MACN,CAAA,kCAAA,EAAqCH,CAAS,iBAAiBF,CAAAA,CAAOE,CAAS,CAAC,CAAA,GAAA,CAAA,CAChFG,CACF,CAAA,CACO,IACT,CACF,CAAA,CAEA,MAAM,QAAQH,CAAAA,CAAmBE,CAAAA,CAA8B,CAC7D,GAAI,CACF,IAAMD,CAAAA,CAAUH,EAAOE,CAAS,CAAA,CAEhC,MAAMJ,CAAAA,CAAQ,OAAA,CAAQK,CAAAA,CAASC,CAAK,EACtC,CAAA,MAASC,CAAAA,CAAO,CACd,OAAA,CAAQ,KAAA,CACN,qCAAqCH,CAAS,CAAA,cAAA,EAAiBF,CAAAA,CAAOE,CAAS,CAAC,CAAA,GAAA,CAAA,CAChFG,CACF,EAEF,CACF,CAAA,CAEA,MAAM,UAAA,CAAWH,CAAAA,CAAkC,CACjD,GAAI,CACF,IAAMC,CAAAA,CAAUH,EAAOE,CAAS,CAAA,CAEhC,MAAMJ,CAAAA,CAAQ,UAAA,CAAWK,CAAO,EAClC,OAASE,CAAAA,CAAO,CAC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AcA,CAAAA,CAAW,MAAA,GAAW,EACvC,MAAM,IAAI,MAAM,yEAAyE,CAAA,CAG3F,IAAMQ,CAAAA,CAAuBf,EAAO,MAAA,CAAS,CAAA,CAAID,EAA6BC,CAAM,CAAA,CAAI,EAAC,CAEnFgB,CAAAA,CAAkBf,CAAAA,CACpB,CAAE,GAAGc,CAAAA,CAAsB,GAAGd,CAAW,CAAA,CACzCc,CAAAA,CAEJ,GAAIf,CAAAA,CAAO,MAAA,CAAS,CAAA,CAClB,IAAA,IAAWE,KAASF,CAAAA,CACbgB,CAAAA,CAAgBd,EAAM,WAAW,CAAA,EACpC,QAAQ,IAAA,CACN,CAAA,6BAAA,EAAgCA,CAAAA,CAAM,IAAI,mBAAmBA,CAAAA,CAAM,WAAW,wCAChF,CAAA,CAsBN,OAjBe,CACb,SAAA,CAAAW,CAAAA,CACA,WAAA,CAAAD,CAAAA,CACA,cAAAH,CAAAA,CACA,QAAA,CAAAC,EACA,eAAA,CAAAC,CAAAA,CAEA,QAAAL,CAAAA,CACA,MAAA,CAAQ,MAAA,CAAO,MAAA,CAAO,CAAC,GAAGN,CAAM,CAAC,CAAA,CACjC,UAAA,CAAY,OAAO,MAAA,CAAO,CAAC,GAAGO,CAAU,CAAC,CAAA,CACzC,UAAA,CAAY,OAAO,MAAA,CAAO,CAAE,GAAGS,CAAgB,CAAC,CAAA,CAChD,OAAA,CAAA7B,EACA,WAAA,CAAAqB,CAAAA,CAEA,QAAAM,CACF,CAGF,CCpFO,SAASG,EAAWC,CAAAA,CAA4B,CACrD,OAAO,IAAIC,UAAAA,CAAWD,CAAe,CACvC","file":"chunk-WICFE46E.js","sourcesContent":["import type { LunoStorage, RawStorage } from '../types';\n\n// Defines the parameters for the createStorage function.\nexport interface CreateStorageParameters {\n storage: RawStorage;\n keyPrefix?: Optional<string>; // Optional key prefix, e.g., \"luno.\"\n}\n\n/**\n * Creates a LunoStorage object that wraps a raw storage mechanism (like localStorage)\n * to provide a consistent async API with key prefixing and error handling.\n *\n * @param storage The raw storage mechanism (e.g., window.localStorage).\n * @param keyPrefix An optional prefix for all storage keys to avoid collisions.\n * @returns A LunoStorage object.\n */\nexport function createStorage({\n storage,\n keyPrefix = 'luno.', // Default key prefix\n}: CreateStorageParameters): LunoStorage {\n const getKey = (suffix: string): string => `${keyPrefix}${suffix}`;\n\n return {\n async getItem(keySuffix: string): Promise<string | null> {\n try {\n const fullKey = getKey(keySuffix);\n // Await to handle both sync and async RawStorage getItem methods consistently\n const value = await storage.getItem(fullKey);\n // Normalize undefined or null to null\n return value == null ? null : String(value);\n } catch (error) {\n console.error(\n `[LunoStorage] Error getting item \"${keySuffix}\" (full key: \"${getKey(keySuffix)}\"):`,\n error\n );\n return null; // Return null on error to indicate failure\n }\n },\n\n async setItem(keySuffix: string, value: string): Promise<void> {\n try {\n const fullKey = getKey(keySuffix);\n // Await to handle both sync and async RawStorage setItem methods consistently\n await storage.setItem(fullKey, value);\n } catch (error) {\n console.error(\n `[LunoStorage] Error setting item \"${keySuffix}\" (full key: \"${getKey(keySuffix)}\"):`,\n error\n );\n // Errors during setItem are logged but don't typically need to be propagated further in the same way getItem might.\n }\n },\n\n async removeItem(keySuffix: string): Promise<void> {\n try {\n const fullKey = getKey(keySuffix);\n // Await to handle both sync and async RawStorage removeItem methods consistently\n await storage.removeItem(fullKey);\n } catch (error) {\n console.error(\n `[LunoStorage] Error removing item \"${keySuffix}\" (full key: \"${getKey(keySuffix)}\"):`,\n error\n );\n }\n },\n };\n}\n","import type {\n Chain,\n Config,\n Connector,\n CreateConfigParameters,\n RawStorage,\n Transport,\n} from '../types';\nimport { createStorage } from './createStorage';\n\nconst noopStorage: RawStorage = {\n getItem: async (_key: string) => null,\n setItem: async (_key: string, _value: string) => {},\n removeItem: async (_key: string) => {},\n};\n\nconst defaultLunoStorage = createStorage({\n storage: typeof window !== 'undefined' && window.localStorage ? window.localStorage : noopStorage,\n keyPrefix: 'luno.',\n});\n\nfunction generateTransportsFromChains(chains: readonly Chain[]): Record<string, Transport> {\n const transports: Record<string, Transport> = {};\n\n for (const chain of chains) {\n const wsUrl = chain.rpcUrls.webSocket;\n if (wsUrl) {\n transports[chain.genesisHash] = wsUrl;\n } else {\n console.warn(\n `No WebSocket URL found for chain \"${chain.name}\" (${chain.genesisHash}). Skipping transport generation.`\n );\n }\n }\n\n return transports;\n}\n\nexport function createConfig(parameters: CreateConfigParameters): Config {\n const {\n appName = 'My Luno App',\n chains = [],\n connectors,\n transports = {},\n storage = defaultLunoStorage,\n autoConnect = true,\n cacheMetadata = true,\n metadata,\n scaledResponses,\n customTypes,\n customRpc,\n subscan,\n } = parameters;\n\n if (!connectors || connectors.length === 0) {\n throw new Error('No connectors provided. Wallet connection features will be unavailable.');\n }\n\n const transportsFromChains = chains.length > 0 ? generateTransportsFromChains(chains) : {};\n\n const finalTransports = transports\n ? { ...transportsFromChains, ...transports }\n : transportsFromChains;\n\n if (chains.length > 0) {\n for (const chain of chains) {\n if (!finalTransports[chain.genesisHash]) {\n console.warn(\n `Missing transport for chain \"${chain.name}\" (genesisHash: ${chain.genesisHash}). Chain functionality may be limited.`\n );\n }\n }\n }\n\n const config = {\n customRpc,\n customTypes,\n cacheMetadata,\n metadata,\n scaledResponses,\n\n appName,\n chains: Object.freeze([...chains]) as readonly Chain[],\n connectors: Object.freeze([...connectors]) as readonly Connector[],\n transports: Object.freeze({ ...finalTransports }) as Readonly<Record<string, Transport>>,\n storage,\n autoConnect,\n\n subscan,\n };\n\n return config;\n}\n","import { WsProvider } from 'dedot';\nimport type { Transport } from '../types';\n\n/**\n * create a WebSocket Transport (WsProvider) instance.\n * @param url - WebSocket RPC URL or URL array (for fallback).\n * @returns WsProvider instance.\n */\nexport function wsProvider(url: Transport): WsProvider {\n return new WsProvider(url as string[]);\n}\n\nexport type { Transport };\n"]}
|