@luno-kit/core 0.0.12-beta.0 → 0.0.12-beta.2

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.
@@ -0,0 +1,2 @@
1
+ 'use strict';var utils=require('dedot/utils');function m(t){try{let e=utils.decodeAddress(t);return utils.encodeAddress(e),!0}catch{return false}}function l(t,e){try{if(utils.isEvmAddress(t))return t;let n=utils.decodeAddress(t);return e>16383?utils.encodeAddress(n,42):utils.encodeAddress(n,e)}catch(n){throw new Error(`Failed to convert address: ${n.message}`)}}function b(t,e){try{let n=utils.decodeAddress(t),r=utils.decodeAddress(e);return utils.u8aEq(n,r)}catch{return false}}function h(t){try{let e=utils.decodeAddress(t);if(e.length!==32)throw new Error(`Invalid public key length: expected 32 bytes, got ${e.length}`);return e}catch(e){throw new Error(`Failed to get public key: ${e.message}`)}}function w(t,e){if(!t)return [];try{return t.map(n=>{let r;try{let o=utils.decodeAddress(n.address);r=utils.u8aToHex(o);}catch(o){console.error(`Failed to decode address "${n.address}" to extract public key:`,o);}return {address:n.address,name:n.name,publicKey:r,meta:{source:e,genesisHash:n.genesisHash},type:n.type}})}catch(n){throw new Error(`Failed to map injected accounts: ${n.message}`)}}function A(t){return t}function S(t){return t.nativeCurrency.symbol}function $(t="",e="",n="transaction"){if(!t)return "";switch(n){case "transaction":return `${t}/extrinsic/${e}`;case "address":return `${t}/account/${e}`;case "block":return `${t}/block/${e}`;default:return t}}var k=()=>typeof window<"u"&&window.navigator&&window.navigator.userAgent?/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(window.navigator.userAgent.toLowerCase()):false;function I(t,e=0,n=4){if(t==null||t==="")return "0";let r=typeof t=="bigint"?t:BigInt(t);if(e===0)return r.toString();let c=BigInt(10)**BigInt(e),o=r/c,s=r%c;if(s===0n)return o.toString();let u=s.toString().padStart(e,"0").substring(0,n).replace(/0+$/,"");return u?`${o.toString()}.${u}`:o.toString()}function K(t,e=4,n=4){if(!t)return "";if(t.length<=e+n)return t;let r=t.slice(0,e),c=n>0?t.slice(-n):"";return `${r}...${c}`}async function H(t,e){if(!t||!e||!e.signRaw||!e.signPayload)return;let{getPolkadotSignerFromPjs:n}=await import('@polkadot-api/pjs-signer');return n(t,e.signPayload,e.signRaw)}Object.defineProperty(exports,"l",{enumerable:true,get:function(){return utils.formatBalance}});exports.a=m;exports.b=l;exports.c=b;exports.d=h;exports.e=w;exports.f=A;exports.g=S;exports.h=$;exports.i=k;exports.j=I;exports.k=K;exports.m=H;//# sourceMappingURL=chunk-4IW7WG2H.cjs.map
2
+ //# sourceMappingURL=chunk-4IW7WG2H.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/address.ts","../src/utils/chain.ts","../src/utils/device.ts","../src/utils/format.ts","../src/utils/papi.ts"],"names":["isValidAddress","address","decoded","decodeAddress","encodeAddress","convertAddress","ss58Format","isEvmAddress","publicKey","error","isSameAddress","address1","address2","publicKey1","publicKey2","u8aEq","getPublicKey","mapInjectedAccounts","injectedAccounts","sourceId","acc","publicKeyHex","publicKeyBytes","u8aToHex","e","defineChain","chain","getChainToken","getExplorerUrl","explorerUrl","data","type","isMobileDevice","formatBalance","value","decimals","fixedDecimals","bn","base","whole","fraction","truncatedFraction","formatAddress","prefixLength","suffixLength","prefix","suffix","createPapiSigner","signer","getPolkadotSignerFromPjs"],"mappings":"8CAOO,SAASA,EAAeC,CAAAA,CAA0B,CACvD,GAAI,CACF,IAAMC,CAAAA,CAAUC,mBAAAA,CAAcF,CAAO,CAAA,CACrC,OAAAG,mBAAAA,CAAcF,CAAO,CAAA,CACd,CAAA,CACT,MAAgB,CACd,OAAO,MACT,CACF,CAKO,SAASG,EAAeJ,CAAAA,CAAiBK,CAAAA,CAA4B,CAC1E,GAAI,CACF,GAAIC,mBAAaN,CAAO,CAAA,CAAG,OAAOA,CAAAA,CAElC,IAAMO,CAAAA,CAAYL,mBAAAA,CAAcF,CAAO,CAAA,CACvC,OAAIK,CAA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AGC,CAAM,CAAA,GAAA,EAAMC,CAAM,CAAA,CAC9B,CC7CA,eAAeC,CAAAA,CAAiB9C,CAAAA,CAAiB+C,CAAAA,CAAiD,CAGhG,GAFI,CAAC/C,CAAAA,EAAW,CAAC+C,CAAAA,EAEb,CAACA,CAAAA,CAAO,OAAA,EAAW,CAACA,CAAAA,CAAO,WAAA,CAAa,OAE5C,GAAM,CAAE,wBAAA,CAAAC,CAAyB,CAAA,CAAI,MAAM,OAAO,0BAA0B,CAAA,CAE5E,OAAOA,CAAAA,CAAyBhD,CAAAA,CAAS+C,CAAAA,CAAO,WAAA,CAAoBA,CAAAA,CAAO,OAAc,CAC3F","file":"chunk-4IW7WG2H.cjs","sourcesContent":["import type { InjectedAccount } from 'dedot/types';\nimport { decodeAddress, encodeAddress, isEvmAddress, u8aEq, u8aToHex } from 'dedot/utils';\nimport type { Account, HexString } from '../types';\n\n/**\n * check if address is valid\n */\nexport function isValidAddress(address: string): boolean {\n try {\n const decoded = decodeAddress(address);\n encodeAddress(decoded);\n return true;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * convert address to specified SS58 format\n */\nexport function convertAddress(address: string, ss58Format: number): string {\n try {\n if (isEvmAddress(address)) return address;\n\n const publicKey = decodeAddress(address);\n if (ss58Format > 16383) {\n return encodeAddress(publicKey, 42);\n }\n return encodeAddress(publicKey, ss58Format);\n } catch (error: any) {\n throw new Error(`Failed to convert address: ${error.message}`);\n }\n}\n\n/**\n * check if two addresses are the same (ignore SS58 format)\n */\nexport function isSameAddress(address1: string, address2: string): boolean {\n try {\n const publicKey1 = decodeAddress(address1);\n const publicKey2 = decodeAddress(address2);\n\n return u8aEq(publicKey1, publicKey2);\n } catch (error: any) {\n return false;\n }\n}\n\n/**\n * get address public key (Currently, Ethereum addresses are not supported.)\n */\nexport function getPublicKey(address: string): Uint8Array {\n try {\n const publicKey = decodeAddress(address);\n if (publicKey.length !== 32) {\n throw new Error(`Invalid public key length: expected 32 bytes, got ${publicKey.length}`);\n }\n return publicKey;\n } catch (error: any) {\n throw new Error(`Failed to get public key: ${error.message}`);\n }\n}\n\n/**\n * map injected accounts to internal Account type\n * mainly extract address, name, source, and try to decode public key\n */\nexport function mapInjectedAccounts(\n injectedAccounts: InjectedAccount[],\n sourceId: string\n): Account[] {\n if (!injectedAccounts) return [];\n\n try {\n return injectedAccounts.map((acc: InjectedAccount) => {\n let publicKeyHex: HexString | undefined;\n try {\n const publicKeyBytes = decodeAddress(acc.address);\n publicKeyHex = u8aToHex(publicKeyBytes);\n } catch (error) {\n console.error(`Failed to decode address \"${acc.address}\" to extract public key:`, error);\n }\n\n const mappedAccount: Account = {\n address: acc.address,\n name: acc.name,\n publicKey: publicKeyHex,\n meta: {\n source: sourceId,\n genesisHash: acc.genesisHash,\n },\n type: acc.type,\n };\n\n return mappedAccount;\n });\n } catch (e: any) {\n throw new Error(`Failed to map injected accounts: ${e.message}`);\n }\n}\n","import type { Chain } from '../types';\n\nexport function defineChain(chain: Chain): Chain {\n return chain;\n}\n\nexport function getChainToken(chain: Chain): string {\n return chain.nativeCurrency.symbol;\n}\n\nexport function getExplorerUrl(\n explorerUrl = '',\n data = '',\n type: 'transaction' | 'address' | 'block' = 'transaction'\n): string {\n if (!explorerUrl) return '';\n\n switch (type) {\n case 'transaction':\n return `${explorerUrl}/extrinsic/${data}`;\n case 'address':\n return `${explorerUrl}/account/${data}`;\n case 'block':\n return `${explorerUrl}/block/${data}`;\n default:\n return explorerUrl;\n }\n}\n","export const isMobileDevice = () => {\n if (typeof window !== 'undefined' && window.navigator && window.navigator.userAgent) {\n return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(\n window.navigator.userAgent.toLowerCase()\n );\n }\n return false;\n};\n","/**\n * format balance\n */\nexport function formatBalance(\n value: Optional<string | number | bigint>,\n decimals: number = 0,\n fixedDecimals: number = 4\n): string {\n if (value === undefined || value === null || value === '') {\n return '0';\n }\n\n const bn = typeof value === 'bigint' ? value : BigInt(value);\n\n if (decimals === 0) {\n return bn.toString();\n }\n\n const base = BigInt(10) ** BigInt(decimals);\n const whole = bn / base;\n const fraction = bn % base;\n\n if (fraction === 0n) {\n return whole.toString();\n }\n\n const paddedFraction = fraction.toString().padStart(decimals, '0');\n const truncatedFraction = paddedFraction.substring(0, fixedDecimals).replace(/0+$/, '');\n\n return truncatedFraction ? `${whole.toString()}.${truncatedFraction}` : whole.toString();\n}\n\n/**\n * format address display\n */\nexport function formatAddress(\n address?: Optional<string>,\n prefixLength = 4,\n suffixLength = 4\n): string {\n if (!address) return '';\n if (address.length <= prefixLength + suffixLength) return address;\n\n const prefix = address.slice(0, prefixLength);\n const suffix = suffixLength > 0 ? address.slice(-suffixLength) : '';\n\n return `${prefix}...${suffix}`;\n}\n\nexport { formatBalance as formatBalanceWithUnit } from 'dedot/utils';\n","import type { PapiSigner, Signer } from '../types';\n\nasync function createPapiSigner(address: string, signer: Signer): Promise<PapiSigner | undefined> {\n if (!address || !signer) return undefined;\n\n if (!signer.signRaw || !signer.signPayload) return undefined;\n\n const { getPolkadotSignerFromPjs } = await import('@polkadot-api/pjs-signer');\n\n return getPolkadotSignerFromPjs(address, signer.signPayload as any, signer.signRaw as any);\n}\n\nexport { createPapiSigner, type PapiSigner };\n"]}
@@ -0,0 +1,2 @@
1
+ import {decodeAddress,encodeAddress,isEvmAddress,u8aEq,u8aToHex}from'dedot/utils';export{formatBalance as l}from'dedot/utils';function m(t){try{let e=decodeAddress(t);return encodeAddress(e),!0}catch{return false}}function l(t,e){try{if(isEvmAddress(t))return t;let n=decodeAddress(t);return e>16383?encodeAddress(n,42):encodeAddress(n,e)}catch(n){throw new Error(`Failed to convert address: ${n.message}`)}}function b(t,e){try{let n=decodeAddress(t),r=decodeAddress(e);return u8aEq(n,r)}catch{return false}}function h(t){try{let e=decodeAddress(t);if(e.length!==32)throw new Error(`Invalid public key length: expected 32 bytes, got ${e.length}`);return e}catch(e){throw new Error(`Failed to get public key: ${e.message}`)}}function w(t,e){if(!t)return [];try{return t.map(n=>{let r;try{let o=decodeAddress(n.address);r=u8aToHex(o);}catch(o){console.error(`Failed to decode address "${n.address}" to extract public key:`,o);}return {address:n.address,name:n.name,publicKey:r,meta:{source:e,genesisHash:n.genesisHash},type:n.type}})}catch(n){throw new Error(`Failed to map injected accounts: ${n.message}`)}}function A(t){return t}function S(t){return t.nativeCurrency.symbol}function $(t="",e="",n="transaction"){if(!t)return "";switch(n){case "transaction":return `${t}/extrinsic/${e}`;case "address":return `${t}/account/${e}`;case "block":return `${t}/block/${e}`;default:return t}}var k=()=>typeof window<"u"&&window.navigator&&window.navigator.userAgent?/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(window.navigator.userAgent.toLowerCase()):false;function I(t,e=0,n=4){if(t==null||t==="")return "0";let r=typeof t=="bigint"?t:BigInt(t);if(e===0)return r.toString();let c=BigInt(10)**BigInt(e),o=r/c,s=r%c;if(s===0n)return o.toString();let u=s.toString().padStart(e,"0").substring(0,n).replace(/0+$/,"");return u?`${o.toString()}.${u}`:o.toString()}function K(t,e=4,n=4){if(!t)return "";if(t.length<=e+n)return t;let r=t.slice(0,e),c=n>0?t.slice(-n):"";return `${r}...${c}`}async function H(t,e){if(!t||!e||!e.signRaw||!e.signPayload)return;let{getPolkadotSignerFromPjs:n}=await import('@polkadot-api/pjs-signer');return n(t,e.signPayload,e.signRaw)}export{m as a,l as b,b as c,h as d,w as e,A as f,S as g,$ as h,k as i,I as j,K as k,H as m};//# sourceMappingURL=chunk-DRDSIIZY.js.map
2
+ //# sourceMappingURL=chunk-DRDSIIZY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/address.ts","../src/utils/chain.ts","../src/utils/device.ts","../src/utils/format.ts","../src/utils/papi.ts"],"names":["isValidAddress","address","decoded","decodeAddress","encodeAddress","convertAddress","ss58Format","isEvmAddress","publicKey","error","isSameAddress","address1","address2","publicKey1","publicKey2","u8aEq","getPublicKey","mapInjectedAccounts","injectedAccounts","sourceId","acc","publicKeyHex","publicKeyBytes","u8aToHex","e","defineChain","chain","getChainToken","getExplorerUrl","explorerUrl","data","type","isMobileDevice","formatBalance","value","decimals","fixedDecimals","bn","base","whole","fraction","truncatedFraction","formatAddress","prefixLength","suffixLength","prefix","suffix","createPapiSigner","signer","getPolkadotSignerFromPjs"],"mappings":"8HAOO,SAASA,EAAeC,CAAAA,CAA0B,CACvD,GAAI,CACF,IAAMC,CAAAA,CAAUC,aAAAA,CAAcF,CAAO,CAAA,CACrC,OAAAG,aAAAA,CAAcF,CAAO,CAAA,CACd,CAAA,CACT,MAAgB,CACd,OAAO,MACT,CACF,CAKO,SAASG,EAAeJ,CAAAA,CAAiBK,CAAAA,CAA4B,CAC1E,GAAI,CACF,GAAIC,aAAaN,CAAO,CAAA,CAAG,OAAOA,CAAAA,CAElC,IAAMO,CAAAA,CAAYL,aAAAA,CAAcF,CAAO,CAAA,CACvC,OAAIK,CAAAA,CAAa,KAAA,CACRF,aAAAA,CAAcI,CAAAA,CAAW,EAAE,CAAA,CAE7BJ,aAAAA,CAAcI,CAAAA,CAAWF,CAAU,CAC5C,CAAA,MAASG,EAAY,CACnB,MAAM,IAAI,KAAA,CAAM,CAAA,2BAAA,EAA8BA,CAAAA,CAAM,OAAO,CAAA,CAAE,CAC/D,CACF,CAKO,SAASC,CAAAA,CAAcC,CAAAA,CAAkBC,CAAAA,CAA2B,CACzE,GAAI,CACF,IAAMC,CAAAA,CAAaV,aAAAA,CAAcQ,CAAQ,CAAA,CACnCG,CAAAA,CAAaX,aAAAA,CAAcS,CAAQ,CAAA,CAEzC,OAAOG,KAAAA,CAAMF,CAAAA,CAAYC,CAAU,CACrC,CAAA,KAAqB,CACnB,OAAO,MACT,CACF,CAKO,SAASE,CAAAA,CAAaf,CAAAA,CAA6B,CACxD,GAAI,CACF,IAAMO,CAAAA,CAAYL,aAAAA,CAAcF,CAAO,CAAA,CACvC,GAAIO,CAAAA,CAAU,SAAW,EAAA,CACvB,MAAM,IAAI,KAAA,CAAM,CAAA,kD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CAAA,CAEtF,OAAOK,CAAAA,CAAoB,GAAGF,CAAAA,CAAM,QAAA,EAAU,CAAA,CAAA,EAAIE,CAAiB,CAAA,CAAA,CAAKF,CAAAA,CAAM,QAAA,EAChF,CAKO,SAASG,CAAAA,CACdzC,CAAAA,CACA0C,CAAAA,CAAe,EACfC,CAAAA,CAAe,CAAA,CACP,CACR,GAAI,CAAC3C,CAAAA,CAAS,OAAO,EAAA,CACrB,GAAIA,CAAAA,CAAQ,MAAA,EAAU0C,CAAAA,CAAeC,CAAAA,CAAc,OAAO3C,EAE1D,IAAM4C,CAAAA,CAAS5C,CAAAA,CAAQ,KAAA,CAAM,CAAA,CAAG0C,CAAY,EACtCG,CAAAA,CAASF,CAAAA,CAAe,CAAA,CAAI3C,CAAAA,CAAQ,KAAA,CAAM,CAAC2C,CAAY,CAAA,CAAI,EAAA,CAEjE,OAAO,CAAA,EAAGC,CAAM,CAAA,GAAA,EAAMC,CAAM,CAAA,CAC9B,CC7CA,eAAeC,CAAAA,CAAiB9C,CAAAA,CAAiB+C,CAAAA,CAAiD,CAGhG,GAFI,CAAC/C,CAAAA,EAAW,CAAC+C,CAAAA,EAEb,CAACA,CAAAA,CAAO,OAAA,EAAW,CAACA,CAAAA,CAAO,WAAA,CAAa,OAE5C,GAAM,CAAE,wBAAA,CAAAC,CAAyB,CAAA,CAAI,MAAM,OAAO,0BAA0B,CAAA,CAE5E,OAAOA,CAAAA,CAAyBhD,CAAAA,CAAS+C,CAAAA,CAAO,WAAA,CAAoBA,CAAAA,CAAO,OAAc,CAC3F","file":"chunk-DRDSIIZY.js","sourcesContent":["import type { InjectedAccount } from 'dedot/types';\nimport { decodeAddress, encodeAddress, isEvmAddress, u8aEq, u8aToHex } from 'dedot/utils';\nimport type { Account, HexString } from '../types';\n\n/**\n * check if address is valid\n */\nexport function isValidAddress(address: string): boolean {\n try {\n const decoded = decodeAddress(address);\n encodeAddress(decoded);\n return true;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * convert address to specified SS58 format\n */\nexport function convertAddress(address: string, ss58Format: number): string {\n try {\n if (isEvmAddress(address)) return address;\n\n const publicKey = decodeAddress(address);\n if (ss58Format > 16383) {\n return encodeAddress(publicKey, 42);\n }\n return encodeAddress(publicKey, ss58Format);\n } catch (error: any) {\n throw new Error(`Failed to convert address: ${error.message}`);\n }\n}\n\n/**\n * check if two addresses are the same (ignore SS58 format)\n */\nexport function isSameAddress(address1: string, address2: string): boolean {\n try {\n const publicKey1 = decodeAddress(address1);\n const publicKey2 = decodeAddress(address2);\n\n return u8aEq(publicKey1, publicKey2);\n } catch (error: any) {\n return false;\n }\n}\n\n/**\n * get address public key (Currently, Ethereum addresses are not supported.)\n */\nexport function getPublicKey(address: string): Uint8Array {\n try {\n const publicKey = decodeAddress(address);\n if (publicKey.length !== 32) {\n throw new Error(`Invalid public key length: expected 32 bytes, got ${publicKey.length}`);\n }\n return publicKey;\n } catch (error: any) {\n throw new Error(`Failed to get public key: ${error.message}`);\n }\n}\n\n/**\n * map injected accounts to internal Account type\n * mainly extract address, name, source, and try to decode public key\n */\nexport function mapInjectedAccounts(\n injectedAccounts: InjectedAccount[],\n sourceId: string\n): Account[] {\n if (!injectedAccounts) return [];\n\n try {\n return injectedAccounts.map((acc: InjectedAccount) => {\n let publicKeyHex: HexString | undefined;\n try {\n const publicKeyBytes = decodeAddress(acc.address);\n publicKeyHex = u8aToHex(publicKeyBytes);\n } catch (error) {\n console.error(`Failed to decode address \"${acc.address}\" to extract public key:`, error);\n }\n\n const mappedAccount: Account = {\n address: acc.address,\n name: acc.name,\n publicKey: publicKeyHex,\n meta: {\n source: sourceId,\n genesisHash: acc.genesisHash,\n },\n type: acc.type,\n };\n\n return mappedAccount;\n });\n } catch (e: any) {\n throw new Error(`Failed to map injected accounts: ${e.message}`);\n }\n}\n","import type { Chain } from '../types';\n\nexport function defineChain(chain: Chain): Chain {\n return chain;\n}\n\nexport function getChainToken(chain: Chain): string {\n return chain.nativeCurrency.symbol;\n}\n\nexport function getExplorerUrl(\n explorerUrl = '',\n data = '',\n type: 'transaction' | 'address' | 'block' = 'transaction'\n): string {\n if (!explorerUrl) return '';\n\n switch (type) {\n case 'transaction':\n return `${explorerUrl}/extrinsic/${data}`;\n case 'address':\n return `${explorerUrl}/account/${data}`;\n case 'block':\n return `${explorerUrl}/block/${data}`;\n default:\n return explorerUrl;\n }\n}\n","export const isMobileDevice = () => {\n if (typeof window !== 'undefined' && window.navigator && window.navigator.userAgent) {\n return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(\n window.navigator.userAgent.toLowerCase()\n );\n }\n return false;\n};\n","/**\n * format balance\n */\nexport function formatBalance(\n value: Optional<string | number | bigint>,\n decimals: number = 0,\n fixedDecimals: number = 4\n): string {\n if (value === undefined || value === null || value === '') {\n return '0';\n }\n\n const bn = typeof value === 'bigint' ? value : BigInt(value);\n\n if (decimals === 0) {\n return bn.toString();\n }\n\n const base = BigInt(10) ** BigInt(decimals);\n const whole = bn / base;\n const fraction = bn % base;\n\n if (fraction === 0n) {\n return whole.toString();\n }\n\n const paddedFraction = fraction.toString().padStart(decimals, '0');\n const truncatedFraction = paddedFraction.substring(0, fixedDecimals).replace(/0+$/, '');\n\n return truncatedFraction ? `${whole.toString()}.${truncatedFraction}` : whole.toString();\n}\n\n/**\n * format address display\n */\nexport function formatAddress(\n address?: Optional<string>,\n prefixLength = 4,\n suffixLength = 4\n): string {\n if (!address) return '';\n if (address.length <= prefixLength + suffixLength) return address;\n\n const prefix = address.slice(0, prefixLength);\n const suffix = suffixLength > 0 ? address.slice(-suffixLength) : '';\n\n return `${prefix}...${suffix}`;\n}\n\nexport { formatBalance as formatBalanceWithUnit } from 'dedot/utils';\n","import type { PapiSigner, Signer } from '../types';\n\nasync function createPapiSigner(address: string, signer: Signer): Promise<PapiSigner | undefined> {\n if (!address || !signer) return undefined;\n\n if (!signer.signRaw || !signer.signPayload) return undefined;\n\n const { getPolkadotSignerFromPjs } = await import('@polkadot-api/pjs-signer');\n\n return getPolkadotSignerFromPjs(address, signer.signPayload as any, signer.signRaw as any);\n}\n\nexport { createPapiSigner, type PapiSigner };\n"]}
@@ -1,3 +1,3 @@
1
- 'use strict';var chunkUFHE4N3F_cjs=require('../chunk-UFHE4N3F.cjs'),chunkQL6JNH54_cjs=require('../chunk-QL6JNH54.cjs'),chunk5F3MRGVJ_cjs=require('../chunk-5F3MRGVJ.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=chunk5F3MRGVJ_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=chunk5F3MRGVJ_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)&&chunk5F3MRGVJ_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)&&chunk5F3MRGVJ_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=>chunk5F3MRGVJ_cjs.i()?w():!chunk5F3MRGVJ_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 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"}});
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,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-P7YOYVKP.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-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"}});
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
@@ -1,2 +1,2 @@
1
- 'use strict';var chunk5F3MRGVJ_cjs=require('../chunk-5F3MRGVJ.cjs');Object.defineProperty(exports,"convertAddress",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.b}});Object.defineProperty(exports,"createPapiSigner",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.m}});Object.defineProperty(exports,"defineChain",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.f}});Object.defineProperty(exports,"formatAddress",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.k}});Object.defineProperty(exports,"formatBalance",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.j}});Object.defineProperty(exports,"formatBalanceWithUnit",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.l}});Object.defineProperty(exports,"getChainToken",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.g}});Object.defineProperty(exports,"getExplorerUrl",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.h}});Object.defineProperty(exports,"getPublicKey",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.d}});Object.defineProperty(exports,"isMobileDevice",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.i}});Object.defineProperty(exports,"isSameAddress",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.c}});Object.defineProperty(exports,"isValidAddress",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.a}});Object.defineProperty(exports,"mapInjectedAccounts",{enumerable:true,get:function(){return chunk5F3MRGVJ_cjs.e}});//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var chunk4IW7WG2H_cjs=require('../chunk-4IW7WG2H.cjs');Object.defineProperty(exports,"convertAddress",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.b}});Object.defineProperty(exports,"createPapiSigner",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.m}});Object.defineProperty(exports,"defineChain",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.f}});Object.defineProperty(exports,"formatAddress",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.k}});Object.defineProperty(exports,"formatBalance",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.j}});Object.defineProperty(exports,"formatBalanceWithUnit",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.l}});Object.defineProperty(exports,"getChainToken",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.g}});Object.defineProperty(exports,"getExplorerUrl",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.h}});Object.defineProperty(exports,"getPublicKey",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.d}});Object.defineProperty(exports,"isMobileDevice",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.i}});Object.defineProperty(exports,"isSameAddress",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.c}});Object.defineProperty(exports,"isValidAddress",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.a}});Object.defineProperty(exports,"mapInjectedAccounts",{enumerable:true,get:function(){return chunk4IW7WG2H_cjs.e}});//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1,2 +1,2 @@
1
- export{b as convertAddress,m as createPapiSigner,f as defineChain,k as formatAddress,j as formatBalance,l as formatBalanceWithUnit,g as getChainToken,h as getExplorerUrl,d as getPublicKey,i as isMobileDevice,c as isSameAddress,a as isValidAddress,e as mapInjectedAccounts}from'../chunk-P7YOYVKP.js';//# sourceMappingURL=index.js.map
1
+ export{b as convertAddress,m as createPapiSigner,f as defineChain,k as formatAddress,j as formatBalance,l as formatBalanceWithUnit,g as getChainToken,h as getExplorerUrl,d as getPublicKey,i as isMobileDevice,c as isSameAddress,a as isValidAddress,e as mapInjectedAccounts}from'../chunk-DRDSIIZY.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
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-beta.0",
4
+ "version": "0.0.12-beta.2",
5
5
  "type": "module",
6
6
  "keywords": [
7
7
  "polkadot",
@@ -1,2 +0,0 @@
1
- 'use strict';var utils=require('dedot/utils');function y(t){try{let e=utils.decodeAddress(t);return utils.encodeAddress(e),!0}catch{return false}}function m(t,e){try{let n=utils.decodeAddress(t);return utils.encodeAddress(n,e)}catch(n){throw new Error(`Failed to convert address: ${n.message}`)}}function l(t,e){try{let n=utils.decodeAddress(t),r=utils.decodeAddress(e);return utils.u8aEq(n,r)}catch{return false}}function b(t){try{let e=utils.decodeAddress(t);if(e.length!==32)throw new Error(`Invalid public key length: expected 32 bytes, got ${e.length}`);return e}catch(e){throw new Error(`Failed to get public key: ${e.message}`)}}function h(t,e){if(!t)return [];try{return t.map(n=>{let r;try{let o=utils.decodeAddress(n.address);r=utils.u8aToHex(o);}catch(o){console.error(`Failed to decode address "${n.address}" to extract public key:`,o);}return {address:n.address,name:n.name,publicKey:r,meta:{source:e,genesisHash:n.genesisHash},type:n.type}})}catch(n){throw new Error(`Failed to map injected accounts: ${n.message}`)}}function x(t){return t}function A(t){return t.nativeCurrency.symbol}function S(t="",e="",n="transaction"){if(!t)return "";switch(n){case "transaction":return `${t}/extrinsic/${e}`;case "address":return `${t}/account/${e}`;case "block":return `${t}/block/${e}`;default:return t}}var P=()=>typeof window<"u"&&window.navigator&&window.navigator.userAgent?/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(window.navigator.userAgent.toLowerCase()):false;function C(t,e=0,n=4){if(t==null||t==="")return "0";let r=typeof t=="bigint"?t:BigInt(t);if(e===0)return r.toString();let c=BigInt(10)**BigInt(e),o=r/c,a=r%c;if(a===0n)return o.toString();let s=a.toString().padStart(e,"0").substring(0,n).replace(/0+$/,"");return s?`${o.toString()}.${s}`:o.toString()}function F(t,e=4,n=4){if(!t)return "";if(t.length<=e+n)return t;let r=t.slice(0,e),c=n>0?t.slice(-n):"";return `${r}...${c}`}async function E(t,e){if(!t||!e||!e.signRaw||!e.signPayload)return;let{getPolkadotSignerFromPjs:n}=await import('@polkadot-api/pjs-signer');return n(t,e.signPayload,e.signRaw)}Object.defineProperty(exports,"l",{enumerable:true,get:function(){return utils.formatBalance}});exports.a=y;exports.b=m;exports.c=l;exports.d=b;exports.e=h;exports.f=x;exports.g=A;exports.h=S;exports.i=P;exports.j=C;exports.k=F;exports.m=E;//# sourceMappingURL=chunk-5F3MRGVJ.cjs.map
2
- //# sourceMappingURL=chunk-5F3MRGVJ.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/address.ts","../src/utils/chain.ts","../src/utils/device.ts","../src/utils/format.ts","../src/utils/papi.ts"],"names":["isValidAddress","address","decoded","decodeAddress","encodeAddress","convertAddress","ss58Format","publicKey","error","isSameAddress","address1","address2","publicKey1","publicKey2","u8aEq","getPublicKey","mapInjectedAccounts","injectedAccounts","sourceId","acc","publicKeyHex","publicKeyBytes","u8aToHex","e","defineChain","chain","getChainToken","getExplorerUrl","explorerUrl","data","type","isMobileDevice","formatBalance","value","decimals","fixedDecimals","bn","base","whole","fraction","truncatedFraction","formatAddress","prefixLength","suffixLength","prefix","suffix","createPapiSigner","signer","getPolkadotSignerFromPjs"],"mappings":"8CAOO,SAASA,CAAAA,CAAeC,CAAAA,CAA0B,CACvD,GAAI,CACF,IAAMC,CAAAA,CAAUC,mBAAAA,CAAcF,CAAO,EACrC,OAAAG,mBAAAA,CAAcF,CAAO,CAAA,CACd,CAAA,CACT,CAAA,KAAgB,CACd,OAAO,MACT,CACF,CAKO,SAASG,CAAAA,CAAeJ,EAAiBK,CAAAA,CAA4B,C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AGC,CAAM,CAAA,GAAA,EAAMC,CAAM,CAAA,CAC9B,CC7CA,eAAeC,CAAAA,CAAiB7C,CAAAA,CAAiB8C,CAAAA,CAAiD,CAGhG,GAFI,CAAC9C,CAAAA,EAAW,CAAC8C,CAAAA,EAEb,CAACA,CAAAA,CAAO,OAAA,EAAW,CAACA,CAAAA,CAAO,WAAA,CAAa,OAE5C,GAAM,CAAE,wBAAA,CAAAC,CAAyB,CAAA,CAAI,MAAM,OAAO,0BAA0B,CAAA,CAE5E,OAAOA,CAAAA,CAAyB/C,CAAAA,CAAS8C,CAAAA,CAAO,WAAA,CAAoBA,CAAAA,CAAO,OAAc,CAC3F","file":"chunk-5F3MRGVJ.cjs","sourcesContent":["import type { InjectedAccount } from 'dedot/types';\nimport { decodeAddress, encodeAddress, u8aEq, u8aToHex } from 'dedot/utils';\nimport type { Account, HexString } from '../types';\n\n/**\n * check if address is valid\n */\nexport function isValidAddress(address: string): boolean {\n try {\n const decoded = decodeAddress(address);\n encodeAddress(decoded);\n return true;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * convert address to specified SS58 format\n */\nexport function convertAddress(address: string, ss58Format: number): string {\n try {\n const publicKey = decodeAddress(address);\n return encodeAddress(publicKey, ss58Format);\n } catch (error: any) {\n throw new Error(`Failed to convert address: ${error.message}`);\n }\n}\n\n/**\n * check if two addresses are the same (ignore SS58 format)\n */\nexport function isSameAddress(address1: string, address2: string): boolean {\n try {\n const publicKey1 = decodeAddress(address1);\n const publicKey2 = decodeAddress(address2);\n\n return u8aEq(publicKey1, publicKey2);\n } catch (error: any) {\n return false;\n }\n}\n\n/**\n * get address public key (Currently, Ethereum addresses are not supported.)\n */\nexport function getPublicKey(address: string): Uint8Array {\n try {\n const publicKey = decodeAddress(address);\n if (publicKey.length !== 32) {\n throw new Error(`Invalid public key length: expected 32 bytes, got ${publicKey.length}`);\n }\n return publicKey;\n } catch (error: any) {\n throw new Error(`Failed to get public key: ${error.message}`);\n }\n}\n\n/**\n * map injected accounts to internal Account type\n * mainly extract address, name, source, and try to decode public key\n */\nexport function mapInjectedAccounts(\n injectedAccounts: InjectedAccount[],\n sourceId: string\n): Account[] {\n if (!injectedAccounts) return [];\n\n try {\n return injectedAccounts.map((acc: InjectedAccount) => {\n let publicKeyHex: HexString | undefined;\n try {\n const publicKeyBytes = decodeAddress(acc.address);\n publicKeyHex = u8aToHex(publicKeyBytes);\n } catch (error) {\n console.error(`Failed to decode address \"${acc.address}\" to extract public key:`, error);\n }\n\n const mappedAccount: Account = {\n address: acc.address,\n name: acc.name,\n publicKey: publicKeyHex,\n meta: {\n source: sourceId,\n genesisHash: acc.genesisHash,\n },\n type: acc.type,\n };\n\n return mappedAccount;\n });\n } catch (e: any) {\n throw new Error(`Failed to map injected accounts: ${e.message}`);\n }\n}\n","import type { Chain } from '../types';\n\nexport function defineChain(chain: Chain): Chain {\n return chain;\n}\n\nexport function getChainToken(chain: Chain): string {\n return chain.nativeCurrency.symbol;\n}\n\nexport function getExplorerUrl(\n explorerUrl = '',\n data = '',\n type: 'transaction' | 'address' | 'block' = 'transaction'\n): string {\n if (!explorerUrl) return '';\n\n switch (type) {\n case 'transaction':\n return `${explorerUrl}/extrinsic/${data}`;\n case 'address':\n return `${explorerUrl}/account/${data}`;\n case 'block':\n return `${explorerUrl}/block/${data}`;\n default:\n return explorerUrl;\n }\n}\n","export const isMobileDevice = () => {\n if (typeof window !== 'undefined' && window.navigator && window.navigator.userAgent) {\n return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(\n window.navigator.userAgent.toLowerCase()\n );\n }\n return false;\n};\n","/**\n * format balance\n */\nexport function formatBalance(\n value: Optional<string | number | bigint>,\n decimals: number = 0,\n fixedDecimals: number = 4\n): string {\n if (value === undefined || value === null || value === '') {\n return '0';\n }\n\n const bn = typeof value === 'bigint' ? value : BigInt(value);\n\n if (decimals === 0) {\n return bn.toString();\n }\n\n const base = BigInt(10) ** BigInt(decimals);\n const whole = bn / base;\n const fraction = bn % base;\n\n if (fraction === 0n) {\n return whole.toString();\n }\n\n const paddedFraction = fraction.toString().padStart(decimals, '0');\n const truncatedFraction = paddedFraction.substring(0, fixedDecimals).replace(/0+$/, '');\n\n return truncatedFraction ? `${whole.toString()}.${truncatedFraction}` : whole.toString();\n}\n\n/**\n * format address display\n */\nexport function formatAddress(\n address?: Optional<string>,\n prefixLength = 4,\n suffixLength = 4\n): string {\n if (!address) return '';\n if (address.length <= prefixLength + suffixLength) return address;\n\n const prefix = address.slice(0, prefixLength);\n const suffix = suffixLength > 0 ? address.slice(-suffixLength) : '';\n\n return `${prefix}...${suffix}`;\n}\n\nexport { formatBalance as formatBalanceWithUnit } from 'dedot/utils';\n","import type { PapiSigner, Signer } from '../types';\n\nasync function createPapiSigner(address: string, signer: Signer): Promise<PapiSigner | undefined> {\n if (!address || !signer) return undefined;\n\n if (!signer.signRaw || !signer.signPayload) return undefined;\n\n const { getPolkadotSignerFromPjs } = await import('@polkadot-api/pjs-signer');\n\n return getPolkadotSignerFromPjs(address, signer.signPayload as any, signer.signRaw as any);\n}\n\nexport { createPapiSigner, type PapiSigner };\n"]}
@@ -1,2 +0,0 @@
1
- import {decodeAddress,encodeAddress,u8aEq,u8aToHex}from'dedot/utils';export{formatBalance as l}from'dedot/utils';function y(t){try{let e=decodeAddress(t);return encodeAddress(e),!0}catch{return false}}function m(t,e){try{let n=decodeAddress(t);return encodeAddress(n,e)}catch(n){throw new Error(`Failed to convert address: ${n.message}`)}}function l(t,e){try{let n=decodeAddress(t),r=decodeAddress(e);return u8aEq(n,r)}catch{return false}}function b(t){try{let e=decodeAddress(t);if(e.length!==32)throw new Error(`Invalid public key length: expected 32 bytes, got ${e.length}`);return e}catch(e){throw new Error(`Failed to get public key: ${e.message}`)}}function h(t,e){if(!t)return [];try{return t.map(n=>{let r;try{let o=decodeAddress(n.address);r=u8aToHex(o);}catch(o){console.error(`Failed to decode address "${n.address}" to extract public key:`,o);}return {address:n.address,name:n.name,publicKey:r,meta:{source:e,genesisHash:n.genesisHash},type:n.type}})}catch(n){throw new Error(`Failed to map injected accounts: ${n.message}`)}}function x(t){return t}function A(t){return t.nativeCurrency.symbol}function S(t="",e="",n="transaction"){if(!t)return "";switch(n){case "transaction":return `${t}/extrinsic/${e}`;case "address":return `${t}/account/${e}`;case "block":return `${t}/block/${e}`;default:return t}}var P=()=>typeof window<"u"&&window.navigator&&window.navigator.userAgent?/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(window.navigator.userAgent.toLowerCase()):false;function C(t,e=0,n=4){if(t==null||t==="")return "0";let r=typeof t=="bigint"?t:BigInt(t);if(e===0)return r.toString();let c=BigInt(10)**BigInt(e),o=r/c,a=r%c;if(a===0n)return o.toString();let s=a.toString().padStart(e,"0").substring(0,n).replace(/0+$/,"");return s?`${o.toString()}.${s}`:o.toString()}function F(t,e=4,n=4){if(!t)return "";if(t.length<=e+n)return t;let r=t.slice(0,e),c=n>0?t.slice(-n):"";return `${r}...${c}`}async function E(t,e){if(!t||!e||!e.signRaw||!e.signPayload)return;let{getPolkadotSignerFromPjs:n}=await import('@polkadot-api/pjs-signer');return n(t,e.signPayload,e.signRaw)}export{y as a,m as b,l as c,b as d,h as e,x as f,A as g,S as h,P as i,C as j,F as k,E as m};//# sourceMappingURL=chunk-P7YOYVKP.js.map
2
- //# sourceMappingURL=chunk-P7YOYVKP.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/address.ts","../src/utils/chain.ts","../src/utils/device.ts","../src/utils/format.ts","../src/utils/papi.ts"],"names":["isValidAddress","address","decoded","decodeAddress","encodeAddress","convertAddress","ss58Format","publicKey","error","isSameAddress","address1","address2","publicKey1","publicKey2","u8aEq","getPublicKey","mapInjectedAccounts","injectedAccounts","sourceId","acc","publicKeyHex","publicKeyBytes","u8aToHex","e","defineChain","chain","getChainToken","getExplorerUrl","explorerUrl","data","type","isMobileDevice","formatBalance","value","decimals","fixedDecimals","bn","base","whole","fraction","truncatedFraction","formatAddress","prefixLength","suffix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AO,EAAA,CACrB,GAAIA,CAAAA,CAAQ,MAAA,EAAUyC,CAAAA,CAAeC,CAAAA,CAAc,OAAO1C,CAAAA,CAE1D,IAAM2C,EAAS3C,CAAAA,CAAQ,KAAA,CAAM,CAAA,CAAGyC,CAAY,CAAA,CACtCG,CAAAA,CAASF,EAAe,CAAA,CAAI1C,CAAAA,CAAQ,KAAA,CAAM,CAAC0C,CAAY,CAAA,CAAI,GAEjE,OAAO,CAAA,EAAGC,CAAM,CAAA,GAAA,EAAMC,CAAM,CAAA,CAC9B,CC7CA,eAAeC,CAAAA,CAAiB7C,CAAAA,CAAiB8C,CAAAA,CAAiD,CAGhG,GAFI,CAAC9C,CAAAA,EAAW,CAAC8C,CAAAA,EAEb,CAACA,CAAAA,CAAO,OAAA,EAAW,CAACA,CAAAA,CAAO,WAAA,CAAa,OAE5C,GAAM,CAAE,wBAAA,CAAAC,CAAyB,CAAA,CAAI,MAAM,OAAO,0BAA0B,CAAA,CAE5E,OAAOA,CAAAA,CAAyB/C,CAAAA,CAAS8C,CAAAA,CAAO,WAAA,CAAoBA,CAAAA,CAAO,OAAc,CAC3F","file":"chunk-P7YOYVKP.js","sourcesContent":["import type { InjectedAccount } from 'dedot/types';\nimport { decodeAddress, encodeAddress, u8aEq, u8aToHex } from 'dedot/utils';\nimport type { Account, HexString } from '../types';\n\n/**\n * check if address is valid\n */\nexport function isValidAddress(address: string): boolean {\n try {\n const decoded = decodeAddress(address);\n encodeAddress(decoded);\n return true;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * convert address to specified SS58 format\n */\nexport function convertAddress(address: string, ss58Format: number): string {\n try {\n const publicKey = decodeAddress(address);\n return encodeAddress(publicKey, ss58Format);\n } catch (error: any) {\n throw new Error(`Failed to convert address: ${error.message}`);\n }\n}\n\n/**\n * check if two addresses are the same (ignore SS58 format)\n */\nexport function isSameAddress(address1: string, address2: string): boolean {\n try {\n const publicKey1 = decodeAddress(address1);\n const publicKey2 = decodeAddress(address2);\n\n return u8aEq(publicKey1, publicKey2);\n } catch (error: any) {\n return false;\n }\n}\n\n/**\n * get address public key (Currently, Ethereum addresses are not supported.)\n */\nexport function getPublicKey(address: string): Uint8Array {\n try {\n const publicKey = decodeAddress(address);\n if (publicKey.length !== 32) {\n throw new Error(`Invalid public key length: expected 32 bytes, got ${publicKey.length}`);\n }\n return publicKey;\n } catch (error: any) {\n throw new Error(`Failed to get public key: ${error.message}`);\n }\n}\n\n/**\n * map injected accounts to internal Account type\n * mainly extract address, name, source, and try to decode public key\n */\nexport function mapInjectedAccounts(\n injectedAccounts: InjectedAccount[],\n sourceId: string\n): Account[] {\n if (!injectedAccounts) return [];\n\n try {\n return injectedAccounts.map((acc: InjectedAccount) => {\n let publicKeyHex: HexString | undefined;\n try {\n const publicKeyBytes = decodeAddress(acc.address);\n publicKeyHex = u8aToHex(publicKeyBytes);\n } catch (error) {\n console.error(`Failed to decode address \"${acc.address}\" to extract public key:`, error);\n }\n\n const mappedAccount: Account = {\n address: acc.address,\n name: acc.name,\n publicKey: publicKeyHex,\n meta: {\n source: sourceId,\n genesisHash: acc.genesisHash,\n },\n type: acc.type,\n };\n\n return mappedAccount;\n });\n } catch (e: any) {\n throw new Error(`Failed to map injected accounts: ${e.message}`);\n }\n}\n","import type { Chain } from '../types';\n\nexport function defineChain(chain: Chain): Chain {\n return chain;\n}\n\nexport function getChainToken(chain: Chain): string {\n return chain.nativeCurrency.symbol;\n}\n\nexport function getExplorerUrl(\n explorerUrl = '',\n data = '',\n type: 'transaction' | 'address' | 'block' = 'transaction'\n): string {\n if (!explorerUrl) return '';\n\n switch (type) {\n case 'transaction':\n return `${explorerUrl}/extrinsic/${data}`;\n case 'address':\n return `${explorerUrl}/account/${data}`;\n case 'block':\n return `${explorerUrl}/block/${data}`;\n default:\n return explorerUrl;\n }\n}\n","export const isMobileDevice = () => {\n if (typeof window !== 'undefined' && window.navigator && window.navigator.userAgent) {\n return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(\n window.navigator.userAgent.toLowerCase()\n );\n }\n return false;\n};\n","/**\n * format balance\n */\nexport function formatBalance(\n value: Optional<string | number | bigint>,\n decimals: number = 0,\n fixedDecimals: number = 4\n): string {\n if (value === undefined || value === null || value === '') {\n return '0';\n }\n\n const bn = typeof value === 'bigint' ? value : BigInt(value);\n\n if (decimals === 0) {\n return bn.toString();\n }\n\n const base = BigInt(10) ** BigInt(decimals);\n const whole = bn / base;\n const fraction = bn % base;\n\n if (fraction === 0n) {\n return whole.toString();\n }\n\n const paddedFraction = fraction.toString().padStart(decimals, '0');\n const truncatedFraction = paddedFraction.substring(0, fixedDecimals).replace(/0+$/, '');\n\n return truncatedFraction ? `${whole.toString()}.${truncatedFraction}` : whole.toString();\n}\n\n/**\n * format address display\n */\nexport function formatAddress(\n address?: Optional<string>,\n prefixLength = 4,\n suffixLength = 4\n): string {\n if (!address) return '';\n if (address.length <= prefixLength + suffixLength) return address;\n\n const prefix = address.slice(0, prefixLength);\n const suffix = suffixLength > 0 ? address.slice(-suffixLength) : '';\n\n return `${prefix}...${suffix}`;\n}\n\nexport { formatBalance as formatBalanceWithUnit } from 'dedot/utils';\n","import type { PapiSigner, Signer } from '../types';\n\nasync function createPapiSigner(address: string, signer: Signer): Promise<PapiSigner | undefined> {\n if (!address || !signer) return undefined;\n\n if (!signer.signRaw || !signer.signPayload) return undefined;\n\n const { getPolkadotSignerFromPjs } = await import('@polkadot-api/pjs-signer');\n\n return getPolkadotSignerFromPjs(address, signer.signPayload as any, signer.signRaw as any);\n}\n\nexport { createPapiSigner, type PapiSigner };\n"]}