PHP WebShell

Текущая директория: /opt/BitGoJS/node_modules/@substrate/connect/dist

Просмотр файла: index.cjs.map

{"version":3,"sources":["../src/index.ts","../src/WellKnownChain.ts","../src/connector/getSpec.ts","../src/connector/types.ts","../src/connector/smoldot-light.ts","../src/connector/extension.ts","../src/connector/index.ts"],"sourcesContent":["/**\n * The substrate-connect package makes it possible to connect to Substrate-compatible blockchains with a light client.\n *\n * Connecting to a chain is done in two steps:\n *\n * 1. Call {@link createScClient}, which gives you a so-called *client*.\n * 2. Call {@link ScClient.addChain addChain} or {@link ScClient.addWellKnownChain addWellKnownChain} on this client.\n *\n * Note that this library is a low-level library where you directly send JSON-RPC requests and\n * receive responses.\n *\n * # Adding parachains\n *\n * Connecting to a parachain is done by obtaining a relay chain instance and then calling {@link Chain.addChain addChain}.\n *\n * ```js\n * const client = createScClient();\n * const relayChain = await client.addChain(relayChainSpec);\n * const parachain = await relayChain.addChain(parachainSpec);\n * ```\n *\n * While this will **not** work, and an exception will be thrown when adding the parachain:\n *\n * ```js\n * await createScClient().addChain(relayChainSpec);\n * await createScClient().addChain(parachainSpec);\n * ```\n *\n * # Resources sharing\n *\n * While calling {@link createScClient} multiple times leads to a different observable behaviour\n * when it comes to parachains (see previous section), internally resources are shared\n * between all the clients.\n *\n * In order words, it is not a problem to do this:\n *\n * ```js\n * const relayChainSpec = ...;\n * const chain1 = await createScClient().addChain(relayChainSpec);\n * const chain2 = await createScClient().addChain(relayChainSpec);\n * ```\n *\n * From an API perspective, `chain1` and `chain2` should be treated as two completely separate\n * connections to the same chain. Internally, however, only one \"actual\" connection to that chain\n * will exist.\n *\n * This means that there is no problem in calling {@link createScClient} from within a library for\n * example.\n *\n * # Well-known chains\n *\n * This package contains a list of so-called {@link WellKnownChain}s. This is a list of popular chains\n * that users are likely to connect to. Instead of calling `addChain` with a chain specification,\n * one can call `addWellKnownChain`, passing only the name of a well-known chain as parameter.\n *\n * Using {@link WellKnownChain}s doesn't provide any benefit when the substrate-connect extension is not\n * installed.\n *\n * If, however, the substrate-connect extension is installed, using {@link ScClient.addWellKnownChain addWellKnownChain} has several\n * benefits:\n *\n * - The web page that uses substrate-connect doesn't need to download the chain specification of\n * a well-known chain from the web server, as this chain specification is already known by the\n * extension.\n * - The extension starts connect to well-known chains when the browser initializes, meaning that\n * when {@link ScClient.addWellKnownChain addWellKnownChain} is called, it is likely that the chain in question has already been\n * fully synchronized.\n * - Furthermore, the extension stores the state of all the well-known chains in the browser's\n * local storage. This leads to a very quick initialization time.\n *\n * # Usage with a worker\n * By default, when the substrate-connect extension is not installed, {@link createScClient} will run the smoldot light\n * client entirely in the current thread. This can cause performance issues if other CPU-heavy operations are done in\n * that thread.\n *\n * In order to help with this, it possible to run the smoldot light client in a worker.\n * To do so, you must provide a {@link EmbeddedNodeConfig.workerFactory workerFactory} to {@link createScClient}\n * and setup the worker to import `@substrate/connect/worker`.\n *\n * For example\n *\n * ```js\n * // worker.mjs\n * import \"@substrate/connect/worker\"\n *\n * // main.mjs\n * import { createScClient } from \"@substrate/connect\"\n * createScClient({\n *   embeddedNodeConfig: {\n *     workerFactory: () => new Worker(\"./worker.mjs\"),\n *   },\n * })\n * ```\n *\n * @packageDocumentation\n */\n\nexport { WellKnownChain } from \"./WellKnownChain.js\"\nexport * from \"./connector/index.js\"\n","/**\n * List of popular chains that are likely to be connected to.\n *\n * The values in this enum correspond to the `id` field of the relevant chain specification.\n */\nexport enum WellKnownChain {\n  polkadot = \"polkadot\",\n  ksmcc3 = \"ksmcc3\",\n  rococo_v2_2 = \"rococo_v2_2\",\n  westend2 = \"westend2\",\n}\n","import { WellKnownChain } from \"../WellKnownChain.js\"\n\nconst chains: Map<WellKnownChain, Promise<{ chainSpec: string }>> = new Map()\n\nexport async function getSpec(chain: string): Promise<string> {\n  if (!Object.keys(WellKnownChain).includes(chain))\n    throw new Error(\"Invalid chain name\")\n\n  const knownChain = chain as WellKnownChain\n  if (!chains.has(knownChain))\n    // Dynamic imports needs to be explicit for ParcelJS\n    // See https://github.com/parcel-bundler/parcel/issues/125\n    switch (knownChain) {\n      case WellKnownChain.polkadot: {\n        chains.set(\n          WellKnownChain.polkadot,\n          import(\"@substrate/connect-known-chains/polkadot\"),\n        )\n        break\n      }\n      case WellKnownChain.ksmcc3: {\n        chains.set(\n          WellKnownChain.ksmcc3,\n          import(\"@substrate/connect-known-chains/ksmcc3\"),\n        )\n        break\n      }\n      case WellKnownChain.westend2: {\n        chains.set(\n          WellKnownChain.westend2,\n          import(\"@substrate/connect-known-chains/westend2\"),\n        )\n        break\n      }\n      case WellKnownChain.rococo_v2_2: {\n        chains.set(\n          WellKnownChain.rococo_v2_2,\n          import(\"@substrate/connect-known-chains/rococo_v2_2\"),\n        )\n        break\n      }\n    }\n\n  return (await chains.get(knownChain)!).chainSpec\n}\n","import { WellKnownChain } from \"../WellKnownChain.js\"\n\n/**\n * Active connection to a blockchain.\n */\nexport interface Chain {\n  /**\n   * Enqueues a JSON-RPC request that the client will process as soon as possible.\n   *\n   * The response will be sent back using the callback passed when adding the chain.\n   *\n   * See <https://www.jsonrpc.org/specification> for a specification of the JSON-RPC format. Only\n   * version 2 is supported.\n   * Be aware that some requests will cause notifications to be sent back using the same callback\n   * as the responses.\n   *\n   * No response is generated if the request isn't a valid JSON-RPC request or if the request is\n   * unreasonably large (8 MiB at the time of writing of this comment). The request is then\n   * silently discarded.\n   * If, however, the request is a valid JSON-RPC request but that concerns an unknown method, a\n   * error response is properly generated.\n   *\n   * Two JSON-RPC APIs are supported:\n   *\n   * - The \"legacy\" one, documented here: <https://polkadot.js.org/docs/substrate/rpc>\n   * - The more recent one: <https://github.com/paritytech/json-rpc-interface-spec>\n   *\n   * @param rpc JSON-encoded RPC request.\n   *\n   * @throws {AlreadyDestroyedError} If the chain has been removed.\n   * @throws {JsonRpcDisabledError} If no JSON-RPC callback was passed in the options of the chain.\n   * @throws {CrashError} If the background client has crashed.\n   */\n  sendJsonRpc(rpc: string): void\n\n  /**\n   * Disconnects from the blockchain.\n   *\n   * The JSON-RPC callback will no longer be called.\n   *\n   * Trying to use the chain again will lead to an exception being thrown.\n   *\n   * If this chain is a relay chain, then all parachains that use it will continue to work. Smoldot\n   * automatically keeps alive all relay chains that have an active parachains. There is no need\n   * to track parachains and relaychains, or to destroy them in the correct order, as this is\n   * handled automatically.\n   *\n   * @throws {AlreadyDestroyedError} If the chain has already been removed.\n   * @throws {CrashError} If the background client has crashed.\n   */\n  remove(): void\n\n  /**\n   * Connects to a parachain.\n   *\n   * Throws an exception if the chain specification isn't valid, or if the chain specification\n   * concerns a parachain but no corresponding relay chain can be found.\n   *\n   * Substrate-connect will automatically de-duplicate chains if multiple identical chains are\n   * added, in order to save resources. In other words, it is not a problem to call `addChain`\n   * multiple times with the same chain specifications and obtain multiple `Chain`.\n   * When the same client is used for multiple different purposes, you are in fact strongly\n   * encouraged to trust substrate-connect and not attempt to de-duplicate chains yourself, as\n   * determining whether two chains are identical is complicated and might have security\n   * implications.\n   *\n   * Substrate-connect tries to distribute CPU resources equally between all active `Chain`\n   * objects.\n   *\n   * @param chainSpec Specification of the chain to add.\n   \n   * @param jsonRpcCallback Callback invoked in response to calling {Chain.sendJsonRpc}.\n   * This field is optional. If no callback is provided, the client will save up resources by not\n   * starting the JSON-RPC endpoint, and it is forbidden to call {Chain.sendJsonRpc}.\n   * Will never be called after ̀{Chain.remove} has been called or if a {CrashError} has been\n   * generated.\n   *\n   * @throws {AddChainError} If the chain can't be added.\n   * @throws {CrashError} If the background client has crashed.\n   */\n  addChain: AddChain\n}\n\nexport type JsonRpcCallback = (response: string) => void\n\nexport type AddChain = (\n  chainSpec: string,\n  jsonRpcCallback?: JsonRpcCallback,\n  databaseContent?: string,\n) => Promise<Chain>\n\nexport type AddWellKnownChain = (\n  id: WellKnownChain,\n  jsonRpcCallback?: JsonRpcCallback,\n  databaseContent?: string,\n) => Promise<Chain>\n\n/**\n * Client that allows connecting to chains.\n *\n * Use {ScClient.addChain} or {ScClient.addWellKnownChain} to connect to a\n * chain.\n *\n * If you want to connect to a parachain, you **must** have connected to its corresponding relay\n * chain with the same instance of {ScClient}. The matching between relay chains and\n * parachains is done through the `relay_chain` field in the parachain specification.\n */\nexport interface ScClient {\n  /**\n   * Connects to a chain.\n   *\n   * Throws an exception if the chain specification isn't valid, or if the chain specification\n   * concerns a parachain but no corresponding relay chain can be found.\n   *\n   * Substrate-connect will automatically de-duplicate chains if multiple identical chains are\n   * added, in order to save resources. In other words, it is not a problem to call `addChain`\n   * multiple times with the same chain specifications and obtain multiple `Chain`.\n   * When the same client is used for multiple different purposes, you are in fact strongly\n   * encouraged to trust substrate-connect and not attempt to de-duplicate chains yourself, as\n   * determining whether two chains are identical is complicated and might have security\n   * implications.\n   *\n   * Substrate-connect tries to distribute CPU resources equally between all active `Chain`\n   * objects.\n   *\n   * @param chainSpec Specification of the chain to add.\n   \n   * @param jsonRpcCallback Callback invoked in response to calling {Chain.sendJsonRpc}.\n   * This field is optional. If no callback is provided, the client will save up resources by not\n   * starting the JSON-RPC endpoint, and it is forbidden to call {Chain.sendJsonRpc}.\n   * Will never be called after ̀{Chain.remove} has been called or if a {CrashError} has been\n   * generated.\n   *\n   * @throws {AddChainError} If the chain can't be added.\n   * @throws {CrashError} If the background client has crashed.\n   */\n  addChain: AddChain\n\n  /**\n   * Connects to a chain, by its `id`.\n   *\n   * Throws an exception if no chain with this name is known.\n   *\n   * Substrate-connect will automatically de-duplicate chains if multiple identical chains are\n   * added, in order to save resources. In other words, it is not a problem to call `addChain`\n   * multiple times with the same chain specifications and obtain multiple `Chain`.\n   * When the same client is used for multiple different purposes, you are in fact strongly\n   * encouraged to trust substrate-connect and not attempt to de-duplicate chains yourself, as\n   * determining whether two chains are identical is complicated and might have security\n   * implications.\n   *\n   * Substrate-connect tries to distribute CPU resources equally between all active `Chain`\n   * objects.\n   *\n   * @param id Name of the well-known chain to add.\n   * @param jsonRpcCallback Same parameter as for {ScClient.addChain}\n   *\n   * @throws {AddChainError} If no chain with this name is known.\n   * @throws {CrashError} If the background client has crashed.\n   */\n  addWellKnownChain: AddWellKnownChain\n}\n\nexport class AlreadyDestroyedError extends Error {\n  constructor() {\n    super()\n    this.name = \"AlreadyDestroyedError\"\n  }\n}\n\nexport class CrashError extends Error {\n  constructor(message: string) {\n    super(message)\n    this.name = \"CrashError\"\n  }\n}\n\nexport class JsonRpcDisabledError extends Error {\n  constructor() {\n    super()\n    this.name = \"JsonRpcDisabledError\"\n  }\n}\n","import type {\n  Chain as SChain,\n  Client,\n  ClientOptions,\n  ClientOptionsWithBytecode,\n} from \"smoldot\"\nimport { getSpec } from \"./getSpec.js\"\nimport {\n  type AddWellKnownChain,\n  type Chain,\n  type ScClient,\n  AlreadyDestroyedError,\n  CrashError,\n  JsonRpcDisabledError,\n  JsonRpcCallback,\n  AddChain,\n} from \"./types.js\"\nimport { WellKnownChain } from \"../WellKnownChain.js\"\n\nconst isBrowser = ![typeof window, typeof document].includes(\"undefined\")\n\nlet QueueFullError = class {}\n\nlet startPromise: Promise<(options: ClientOptions) => Client> | null = null\nconst getStart = () => {\n  if (startPromise) return startPromise\n  startPromise = import(\"smoldot\").then((sm) => {\n    QueueFullError = sm.QueueFullError\n    return sm.start\n  })\n  return startPromise\n}\n\nlet startWithByteCodePromise: Promise<\n  (options: ClientOptionsWithBytecode) => Client\n> | null = null\nconst getStartWithByteCode = () => {\n  if (startWithByteCodePromise) return startWithByteCodePromise\n  // @ts-ignore TODO: fix types in smoldot/no-auto-bytecode\n  startWithByteCodePromise = import(\"smoldot/no-auto-bytecode\").then(\n    (sm) => sm.startWithBytecode,\n  )\n  return startWithByteCodePromise\n}\n\nconst clientReferences: Config[] = [] // Note that this can't be a set, as the same config is added/removed multiple times\nlet clientPromise: Promise<Client> | Client | null = null\nlet clientReferencesMaxLogLevel = 3\nconst getClientAndIncRef = (config: Config): Promise<Client> => {\n  if (config.maxLogLevel && config.maxLogLevel > clientReferencesMaxLogLevel)\n    clientReferencesMaxLogLevel = config.maxLogLevel\n\n  if (clientPromise) {\n    clientReferences.push(config)\n    if (clientPromise instanceof Promise) return clientPromise\n    else return Promise.resolve(clientPromise)\n  }\n\n  let worker: Worker | undefined = undefined\n  let portToWorker: MessagePort | undefined = undefined\n  if (config.workerFactory) {\n    worker = config.workerFactory()\n    const { port1, port2 } = new MessageChannel()\n    worker.postMessage(port1, [port1])\n    portToWorker = port2\n  }\n\n  const clientOptions: ClientOptions = {\n    portToWorker,\n    forbidTcp: true, // In order to avoid confusing inconsistencies between browsers and NodeJS, TCP connections are always disabled.\n    forbidNonLocalWs: true, // Prevents browsers from emitting warnings if smoldot tried to establish non-secure WebSocket connections\n    maxLogLevel: 9999999, // The actual level filtering is done in the logCallback\n    cpuRateLimit: 0.5, // Politely limit the CPU usage of the smoldot background worker.\n    logCallback: (level, target, message) => {\n      if (level > clientReferencesMaxLogLevel) return\n\n      // The first parameter of the methods of `console` has some printf-like substitution\n      // capabilities. We don't really need to use this, but not using it means that the logs\n      // might not get printed correctly if they contain `%`.\n      if (level <= 1) {\n        console.error(\"[%s] %s\", target, message)\n      } else if (level === 2) {\n        console.warn(\"[%s] %s\", target, message)\n      } else if (level === 3) {\n        console.info(\"[%s] %s\", target, message)\n      } else if (level === 4) {\n        console.debug(\"[%s] %s\", target, message)\n      } else {\n        console.trace(\"[%s] %s\", target, message)\n      }\n    },\n  }\n\n  const newClientPromise = worker\n    ? getStartWithByteCode().then((start) => {\n        return start({\n          ...clientOptions,\n          bytecode: new Promise((resolve) => {\n            // In NodeJs, onmessage does not exist in Worker from \"node:worker_threads\"\n            if (isBrowser) worker!.onmessage = (event) => resolve(event.data)\n            // @ts-ignore\n            else worker!.on(\"message\", (message) => resolve(message))\n          }),\n        })\n      })\n    : getStart().then((start) => start(clientOptions))\n\n  clientPromise = newClientPromise\n\n  newClientPromise.then((client) => {\n    // Make sure that the client we have just created is still desired\n    if (clientPromise === newClientPromise) clientPromise = client\n    else client.terminate()\n    // Note that if clientPromise != newClientPromise we know for sure that the client that we\n    // return isn't going to be used. We would rather not return a terminated client, but this\n    // isn't possible for type check reasons.\n    return client\n  })\n\n  clientReferences.push(config)\n  return clientPromise\n}\n\n// Must be passed the exact same object as was passed to {getClientAndIncRef}\nconst decRef = (config: Config) => {\n  const idx = clientReferences.indexOf(config)\n  if (idx === -1) throw new Error(\"Internal error within smoldot\")\n  clientReferences.splice(idx, 1)\n\n  // Update `clientReferencesMaxLogLevel`\n  // Note how it is set back to 3 if there is no reference anymore\n  clientReferencesMaxLogLevel = 3\n  for (const cfg of clientReferences.values()) {\n    if (cfg.maxLogLevel && cfg.maxLogLevel > clientReferencesMaxLogLevel)\n      clientReferencesMaxLogLevel = cfg.maxLogLevel\n  }\n\n  if (clientReferences.length === 0) {\n    if (clientPromise && !(clientPromise instanceof Promise))\n      clientPromise.terminate()\n    clientPromise = null\n  }\n}\n\nconst transformErrors = (thunk: () => void) => {\n  try {\n    thunk()\n  } catch (e) {\n    const error = e as Error | undefined\n    if (error?.name === \"JsonRpcDisabledError\") throw new JsonRpcDisabledError()\n    if (error?.name === \"CrashError\") throw new CrashError(error.message)\n    if (error?.name === \"AlreadyDestroyedError\")\n      throw new AlreadyDestroyedError()\n    throw new CrashError(\n      e instanceof Error ? e.message : `Unexpected error ${e}`,\n    )\n  }\n}\n\n/**\n * Configuration that can be passed to {createScClient}.\n */\nexport interface Config {\n  /**\n   * The client prints logs in the console. By default, only log levels 1, 2, and 3 (corresponding\n   * respectively to ERROR, WARN, and INFO) are printed.\n   *\n   * In order to more easily debug problems, you can pass 4 (DEBUG) or more.\n   *\n   * This setting is only taken into account between the moment when you use this chain to add a\n   * chain for the first time, and the moment when all the chains that you have added have been\n   * removed.\n   *\n   * If {createScClient} is called multiple times with multiple different log levels, the highest\n   * value will be used.\n   */\n  maxLogLevel?: number\n\n  /**\n   * Creates a `Worker` that is expected to import `@substrate/connect/worker`.\n   *\n   * If this option isn't set then the smoldot light client will run entirely on the \"current thread\", which might slow\n   * down other components that also run on this thread.\n   */\n  workerFactory?: () => Worker\n}\n\n/**\n * Returns a {ScClient} that connects to chains by executing a light client directly\n * from JavaScript.\n *\n * This is quite expensive in terms of CPU, but it is the only choice when the substrate-connect\n * extension is not installed.\n */\nexport const createScClient = (config?: Config): ScClient => {\n  const configOrDefault = config || { maxLogLevel: 3 }\n\n  const internalAddChain = async (\n    chainSpec: string,\n    jsonRpcCallback?: (msg: string) => void,\n    databaseContent?: string,\n    relayChain?: SChain,\n  ): Promise<Chain> => {\n    const client = await getClientAndIncRef(configOrDefault)\n\n    try {\n      const internalChain = await client.addChain({\n        chainSpec,\n        potentialRelayChains: relayChain ? [relayChain] : undefined,\n        disableJsonRpc: jsonRpcCallback === undefined,\n        databaseContent,\n      })\n\n      ;(async () => {\n        while (true) {\n          let jsonRpcResponse\n          try {\n            jsonRpcResponse = await internalChain.nextJsonRpcResponse()\n          } catch (_) {\n            break\n          }\n\n          // `nextJsonRpcResponse` throws an exception if we pass `disableJsonRpc: true` in the\n          // config. We pass `disableJsonRpc: true` if `jsonRpcCallback` is undefined. Therefore,\n          // this code is never reachable if `jsonRpcCallback` is undefined.\n          try {\n            jsonRpcCallback!(jsonRpcResponse)\n          } catch (error) {\n            console.error(\"JSON-RPC callback has thrown an exception:\", error)\n          }\n        }\n      })()\n\n      return {\n        sendJsonRpc: (rpc) => {\n          transformErrors(() => {\n            try {\n              internalChain.sendJsonRpc(rpc)\n            } catch (error) {\n              if (error instanceof QueueFullError) {\n                // If the queue is full, we immediately send back a JSON-RPC response indicating\n                // the error.\n                try {\n                  const parsedRq = JSON.parse(rpc)\n                  jsonRpcCallback!(\n                    JSON.stringify({\n                      jsonrpc: \"v2\",\n                      id: parsedRq.id,\n                      error: {\n                        code: -32000,\n                        message: \"JSON-RPC server is too busy\",\n                      },\n                    }),\n                  )\n                } catch (_error) {\n                  // An error here counts as a malformed JSON-RPC request, which are ignored.\n                }\n              } else {\n                throw error\n              }\n            }\n          })\n        },\n        remove: () => {\n          try {\n            transformErrors(() => {\n              internalChain.remove()\n            })\n          } finally {\n            decRef(configOrDefault)\n          }\n        },\n        addChain: (\n          chainSpec: string,\n          jsonRpcCallback?: JsonRpcCallback | undefined,\n          databaseContent?: string | undefined,\n        ): Promise<Chain> => {\n          return internalAddChain(\n            chainSpec,\n            jsonRpcCallback,\n            databaseContent,\n            internalChain,\n          )\n        },\n      }\n    } catch (error) {\n      decRef(configOrDefault)\n      throw error\n    }\n  }\n\n  const addChain: AddChain = (chainSpec, jsonRpcCallback, databaseContent) =>\n    internalAddChain(chainSpec, jsonRpcCallback, databaseContent)\n\n  const addWellKnownChain: AddWellKnownChain = async (\n    supposedChain: WellKnownChain,\n    jsonRpcCallback?: (msg: string) => void,\n    databaseContent?: string,\n  ): Promise<Chain> => {\n    // the following line ensures that the http request for the dynamic import\n    // of smoldot and the request for the dynamic import of the spec\n    // happen in parallel\n    getClientAndIncRef(configOrDefault)\n\n    try {\n      return await internalAddChain(\n        await getSpec(supposedChain),\n        jsonRpcCallback,\n        databaseContent,\n      )\n    } finally {\n      decRef(configOrDefault)\n    }\n  }\n\n  return {\n    addChain,\n    addWellKnownChain,\n  }\n}\n","import type { Chain, JsonRpcCallback, ScClient } from \"./types.js\"\nimport type {\n  RawChain,\n  LightClientProvider,\n} from \"@substrate/light-client-extension-helpers/web-page\"\nimport { WellKnownChain } from \"../WellKnownChain.js\"\n\nconst wellKnownChainGenesisHashes: Record<string, string> = {\n  polkadot:\n    \"0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3\",\n  ksmcc3: \"0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe\",\n  westend2:\n    \"0xe143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e\",\n  rococo_v2_2:\n    \"0x6408de7737c59c238890533af25896a2c20608d8b380bb01029acb392781063e\",\n}\n\n/**\n * Returns a {@link ScClient} that connects to chains by asking the substrate-connect extension\n * to do so.\n *\n * This function assumes that the extension is installed and available. It is out of scope of this\n * function to detect whether this is the case.\n * If you try to add a chain without the extension installed, nothing will happen and the\n * `Promise`s will never resolve.\n */\nexport const createScClient = (\n  lightClientProviderPromise: Promise<LightClientProvider>,\n): ScClient => {\n  const internalAddChain = async (\n    isWellKnown: boolean,\n    chainSpecOrWellKnownName: string,\n    jsonRpcCallback: JsonRpcCallback = () => {},\n    relayChainGenesisHash?: string,\n  ): Promise<Chain> => {\n    const lightClientProvider = await lightClientProviderPromise\n\n    let chain: RawChain\n    if (isWellKnown) {\n      const foundChain = Object.values(lightClientProvider.getChains()).find(\n        ({ genesisHash }) =>\n          genesisHash === wellKnownChainGenesisHashes[chainSpecOrWellKnownName],\n      )\n      if (!foundChain) throw new Error(\"Unknown well-known chain\")\n      chain = foundChain\n    } else {\n      chain = await lightClientProvider.getChain(\n        chainSpecOrWellKnownName,\n        relayChainGenesisHash,\n      )\n    }\n\n    const jsonRpcProvider = chain.connect(jsonRpcCallback)\n\n    return {\n      sendJsonRpc(rpc: string): void {\n        jsonRpcProvider.send(rpc)\n      },\n      remove() {\n        jsonRpcProvider.disconnect()\n      },\n      addChain: function (\n        chainSpec: string,\n        jsonRpcCallback?: JsonRpcCallback | undefined,\n      ): Promise<Chain> {\n        return internalAddChain(\n          false,\n          chainSpec,\n          jsonRpcCallback,\n          chain.genesisHash,\n        )\n      },\n    }\n  }\n\n  return {\n    addChain: (chainSpec: string, jsonRpcCallback?: JsonRpcCallback) =>\n      internalAddChain(false, chainSpec, jsonRpcCallback),\n    addWellKnownChain: (\n      name: WellKnownChain,\n      jsonRpcCallback?: JsonRpcCallback,\n    ) => internalAddChain(true, name, jsonRpcCallback),\n  }\n}\n","import {\n  createScClient as smoldotScClient,\n  type Config as EmbeddedNodeConfig,\n} from \"./smoldot-light.js\"\nimport { createScClient as extensionScClient } from \"./extension.js\"\nimport type { ScClient } from \"./types.js\"\nimport type {\n  LightClientProvider,\n  LightClientOnProvider,\n} from \"@substrate/light-client-extension-helpers/web-page\"\n\nexport * from \"./types.js\"\nexport type { EmbeddedNodeConfig }\n\n/**\n * Configuration that can be passed to {createScClient}.\n */\nexport interface Config {\n  /**\n   * If `true`, then the client will always use a node embedded within the page and never use\n   * the substrate-connect extension.\n   *\n   * Defaults to `false`.\n   */\n  forceEmbeddedNode?: boolean\n\n  /**\n   * Configuration to use for the embedded node. Ignored if the extension is present.\n   *\n   * If you want to make sure that this configuration isn't ignored, use this option in\n   * conjunction with {Config.forceEmbeddedNode}.\n   */\n  embeddedNodeConfig?: EmbeddedNodeConfig\n}\n\n/**\n * Returns a {@link ScClient} that connects to chains, either through the substrate-connect\n * extension or by executing a light client directly from JavaScript, depending on whether the\n * extension is installed and available.\n */\nexport const createScClient = (config?: Config): ScClient => {\n  if (config?.forceEmbeddedNode)\n    return smoldotScClient(config?.embeddedNodeConfig)\n\n  const lightClientProviderPromise = getExtensionLightClientProviderPromise()\n  const client = lightClientProviderPromise\n    ? extensionScClient(lightClientProviderPromise)\n    : smoldotScClient(config?.embeddedNodeConfig)\n\n  return {\n    async addChain(chainSpec, jsonRpcCallback, databaseContent) {\n      return (await client).addChain(\n        chainSpec,\n        jsonRpcCallback,\n        databaseContent,\n      )\n    },\n    async addWellKnownChain(id, jsonRpcCallback, databaseContent) {\n      return (await client).addWellKnownChain(\n        id,\n        jsonRpcCallback,\n        databaseContent,\n      )\n    },\n  }\n}\n\nfunction getExtensionLightClientProviderPromise():\n  | Promise<LightClientProvider>\n  | undefined {\n  if (typeof document !== \"object\" || typeof CustomEvent !== \"function\") return\n  let lightClientProviderPromise: Promise<LightClientProvider> | undefined\n  window.dispatchEvent(\n    new CustomEvent<LightClientOnProvider>(\"lightClient:requestProvider\", {\n      detail: {\n        onProvider(detail) {\n          if (\n            detail.info.rdns ===\n            \"io.github.paritytech.SubstrateConnectLightClient\"\n          ) {\n            lightClientProviderPromise = detail.provider\n          }\n        },\n      },\n    }),\n  )\n  return lightClientProviderPromise\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,MAAI,OAAO,aAAa,YAAY,OAAO,gBAAgB;AAAY;AACvE,MAAI;AACJ,SAAO;AAAA,IACL,IAAI,YAAmC,+BAA+B;AAAA,MACpE,QAAQ;AAAA,QACN,WAAW,QAAQ;AACjB,cACE,OAAO,KAAK,SACZ,oDACA;AACA,yCAA6B,OAAO;AAAA,UACtC;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":["createScClient","WellKnownChain","chainSpec","jsonRpcCallback","databaseContent","createScClient","jsonRpcCallback","createScClient"]}

Выполнить команду


Для локальной разработки. Не используйте в интернете!