@qntx/wallet-engine 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1057 -20
- package/dist/apps-fiat24.d.mts +202 -0
- package/dist/apps-fiat24.mjs +1378 -0
- package/dist/apps-fiat24.mjs.map +1 -0
- package/dist/apps-hyperliquid.d.mts +549 -0
- package/dist/apps-hyperliquid.mjs +2742 -0
- package/dist/apps-hyperliquid.mjs.map +1 -0
- package/dist/apps-polymarket.d.mts +729 -0
- package/dist/apps-polymarket.mjs +3786 -0
- package/dist/apps-polymarket.mjs.map +1 -0
- package/dist/apps.d.mts +136 -0
- package/dist/apps.mjs +535 -0
- package/dist/apps.mjs.map +1 -0
- package/dist/connect-BY1C5ZRI.mjs +210 -0
- package/dist/connect-BY1C5ZRI.mjs.map +1 -0
- package/dist/connect.d.mts +17 -9
- package/dist/connect.mjs +3 -185
- package/dist/controller-DpNVHVsj.d.mts +2295 -0
- package/dist/controller-rMnaxKAH.mjs +46 -0
- package/dist/controller-rMnaxKAH.mjs.map +1 -0
- package/dist/decimal-COJ4g8qy.mjs +38 -0
- package/dist/decimal-COJ4g8qy.mjs.map +1 -0
- package/dist/eligibility-BfM9ybYZ.mjs +48 -0
- package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
- package/dist/engine-Dic_kkEr.d.mts +1829 -0
- package/dist/errors-B8W-hoYW.d.mts +7 -0
- package/dist/errors-horUy5k1.mjs +24 -0
- package/dist/errors-horUy5k1.mjs.map +1 -0
- package/dist/gateway-contract.d.mts +3 -362
- package/dist/gateway-contract.mjs +1531 -81
- package/dist/gateway-contract.mjs.map +1 -1
- package/dist/idb.d.mts +5 -0
- package/dist/idb.mjs +122 -46
- package/dist/idb.mjs.map +1 -1
- package/dist/index-vBgfOFIh.d.mts +2227 -0
- package/dist/index.d.mts +58 -515
- package/dist/index.mjs +22314 -4901
- package/dist/index.mjs.map +1 -1
- package/dist/json-BDwV38cj.mjs +15 -0
- package/dist/json-BDwV38cj.mjs.map +1 -0
- package/dist/link-Ceq8Dggp.mjs +139 -0
- package/dist/link-Ceq8Dggp.mjs.map +1 -0
- package/dist/primitives-DbSHLZKq.mjs +31 -0
- package/dist/primitives-DbSHLZKq.mjs.map +1 -0
- package/dist/push-message-AQuzoNFY.d.mts +84 -0
- package/dist/push-message-kbnH1A5w.mjs +142 -0
- package/dist/push-message-kbnH1A5w.mjs.map +1 -0
- package/dist/push.d.mts +13 -0
- package/dist/push.mjs +70 -0
- package/dist/push.mjs.map +1 -0
- package/dist/qr.d.mts +292 -0
- package/dist/qr.mjs +1725 -0
- package/dist/qr.mjs.map +1 -0
- package/dist/registry-CbtwcxkX.mjs +374 -0
- package/dist/registry-CbtwcxkX.mjs.map +1 -0
- package/dist/risk-DyABgg4W.mjs +757 -0
- package/dist/risk-DyABgg4W.mjs.map +1 -0
- package/dist/session-CNJFLarP.mjs +18 -0
- package/dist/session-CNJFLarP.mjs.map +1 -0
- package/dist/socket-ChG9JRT_.mjs +110 -0
- package/dist/socket-ChG9JRT_.mjs.map +1 -0
- package/dist/spi-BrTw5s98.d.mts +3 -0
- package/dist/timer-Cdk5rGM2.mjs +43 -0
- package/dist/timer-Cdk5rGM2.mjs.map +1 -0
- package/dist/types-BpvioFGo.d.mts +258 -0
- package/dist/types-DbftVZ3I.mjs +90 -0
- package/dist/types-DbftVZ3I.mjs.map +1 -0
- package/dist/walletconnect.d.mts +86 -0
- package/dist/walletconnect.mjs +1507 -0
- package/dist/walletconnect.mjs.map +1 -0
- package/dist/webln-BgrtPXpG.mjs +2593 -0
- package/dist/webln-BgrtPXpG.mjs.map +1 -0
- package/dist/webln-Bllk_xJ2.d.mts +666 -0
- package/package.json +94 -19
- package/dist/connect.mjs.map +0 -1
- package/dist/errors-DpkJneDe.d.mts +0 -1696
- package/dist/registry-Deo5WQe1.d.mts +0 -25
- package/dist/registry-wYrcuFNc.mjs +0 -99
- package/dist/registry-wYrcuFNc.mjs.map +0 -1
- package/dist/webln-DzsI7jVb.mjs +0 -3629
- package/dist/webln-DzsI7jVb.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apps.mjs","names":["eligibilityContract"],"sources":["../src/apps/storage.ts","../src/apps/controller.ts"],"sourcesContent":["/**\n * The `AppStorage` factory: per-app records in the session EngineStore, collection `apps.<id>`,\n * keys `${walletId}/${groupIndex}/${name}` (design.md 不变量 4′/12 — records are group-scoped and\n * their `walletId` prefix is what the wallet-deletion prune matches). Available only while the\n * controller's session store is open — every method throws `EngineStoreError(\"closed\")` after a\n * lock.\n */\nimport { EngineStoreError } from \"../errors.ts\";\nimport type { EngineCollection, EngineStore } from \"../store/port.ts\";\nimport type { AppGroup, AppId, AppStorage } from \"./types.ts\";\n\n/**\n * `store` resolves the currently open session store — `createApps` tracks the facade it hands the\n * controller; tests bind a memory store directly.\n */\nconst key = (group: AppGroup, name: string): string =>\n `${group.walletId}/${group.groupIndex}/${name}`;\n\nexport function createAppStorage(id: AppId, store: () => EngineStore | undefined): AppStorage {\n const collection = (): EngineCollection => {\n const session = store();\n if (session === undefined) {\n throw new EngineStoreError(\"closed\", \"the vault is locked\");\n }\n return session.collection(`apps.${id}`);\n };\n return {\n get: async (group, name) => collection().get(key(group, name)),\n put: async (group, name, bytes) => collection().put(key(group, name), bytes),\n delete: async (group, name) => collection().delete(key(group, name)),\n list: async (group) => {\n const prefix = `${group.walletId}/${group.groupIndex}/`;\n const names: string[] = [];\n for (const stored of await collection().list()) {\n if (stored.startsWith(prefix)) {\n names.push(stored.slice(prefix.length));\n }\n }\n return names;\n },\n groups: async () => {\n const seen = new Map<string, AppGroup>();\n for (const stored of await collection().list()) {\n /* A record key is `<walletId>/<groupIndex>/<name>` — anything shorter is not a\n group record. */\n const first = stored.indexOf(\"/\");\n const second = stored.indexOf(\"/\", first + 1);\n const groupIndex = Number(stored.slice(first + 1, second));\n if (first < 1 || second < first + 2 || !Number.isInteger(groupIndex) || groupIndex < 0) {\n continue;\n }\n const walletId = stored.slice(0, first);\n seen.set(`${walletId}/${groupIndex}`, { walletId, groupIndex });\n }\n return [...seen.values()];\n },\n };\n}\n","/**\n * `createApps` — the app-enablement composition: the host lists the app definitions it wants, each\n * built over one shared `AppContext`; an `AppsController` persists each group's terms flag through\n * lock/unlock; and the serialized lock lifecycle from engine.ts (`transition`/`schedule` on\n * `wallet.subscribe`) drives every app's `unlock`/`lock`/`close` hooks.\n */\nimport type { VerifyFactor, Wallet } from \"@qntx/wallet\";\nimport type { ChainsApi } from \"@qntx/wallet/chains\";\n\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport { APP_ID, eligibility as eligibilityContract } from \"../gateway/contract/eligibility.ts\";\nimport type { AppAvailability, EligibilityResponse } from \"../gateway/contract/eligibility.ts\";\nimport { parseWith } from \"../gateway/contract/endpoint.ts\";\nimport { CLIENT_ID_HEADER } from \"../gateway/contract/primitives.ts\";\nimport { gatewaySession } from \"../gateway/session.ts\";\nimport type { RequestController } from \"../requests/controller.ts\";\nimport { readJson } from \"../store/json.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\nimport type { SetTimer } from \"../timer.ts\";\nimport type { AppSocket } from \"./socket.ts\";\nimport { createAppStorage } from \"./storage.ts\";\nimport type {\n AppApis,\n AppAuthority,\n AppContext,\n AppDefinition,\n AppError,\n AppFlow,\n AppGroup,\n AppGroups,\n AppGroupState,\n AppId,\n AppInstance,\n AppNetworks,\n AppProvider,\n AppsState,\n AppStates,\n} from \"./types.ts\";\n\nconst COLLECTION = \"apps\";\n\n/** One row of `AppsController.authorities`: an app's authority, or its own read failure. */\nexport type AppAuthorityRow = { readonly app: AppId } & (\n | { readonly authority: AppAuthority }\n | { readonly error: AppError }\n);\n\n/* The app's own error type carries `category`; an unexpected throw reads as `unavailable`. */\nconst authorityError = (error: unknown): AppError =>\n error instanceof Error && \"category\" in error && typeof error.category === \"string\"\n ? { category: error.category, message: error.message }\n : {\n category: \"unavailable\",\n message: error instanceof Error ? error.message : String(error),\n };\n\nconst DEFAULT_GROUP: AppGroupState = {\n status: \"disabled\",\n termsAcknowledged: false,\n};\n\n/** What a group's record persists — the terms flag alone; nothing else is stable across sessions. */\ntype StoredGroup = {\n readonly termsAcknowledged: true;\n};\n\nexport type CreateAppsOptions = {\n readonly wallet: Wallet;\n /**\n * The account derivation seam every app shares — the engine's `signers.apis.account` (or the\n * `chains` account api for a host composing apps without the engine).\n */\n readonly account: ChainsApi[\"account\"];\n readonly requests: Pick<RequestController, \"prepare\" | \"outcome\" | \"reject\">;\n /** The chain clients an app's deposit path reads allowance/burn limits through. */\n readonly networks: AppNetworks;\n readonly fetch: typeof globalThis.fetch;\n readonly now: () => number;\n readonly setTimer: SetTimer;\n readonly random: (length: number) => Uint8Array;\n readonly logger: EngineLogger;\n readonly openStore: () => Promise<EngineStore>;\n /**\n * The WebSocket factory live views stream over — `(url) => new WebSocket(url)` on any runtime\n * (browser, RN, Node ≥ 22). One socket serves every subscription.\n */\n readonly socket: (url: string) => AppSocket;\n /** The gateway base URL — eligibility is fetched through the engine's gateway client. */\n readonly gateway: { readonly url: string };\n};\n\nconst recordKey = (group: AppGroup, app: AppId): string =>\n `${group.walletId}/${group.groupIndex}/${app}`;\n\nconst groupKey = (group: AppGroup): string => `${group.walletId}/${group.groupIndex}`;\n\n/** Exact keys only — a record with anything else reads as absent (logged by the caller). */\nconst parseRecord = (raw: Uint8Array): StoredGroup | undefined => {\n const value: unknown = readJson(raw);\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n if (Object.keys(value).some((k) => k !== \"termsAcknowledged\")) {\n return undefined;\n }\n if (!(\"termsAcknowledged\" in value) || value.termsAcknowledged !== true) {\n return undefined;\n }\n return { termsAcknowledged: true };\n};\n\nconst isGroupState = (value: unknown): value is AppGroupState =>\n typeof value === \"object\" &&\n value !== null &&\n \"status\" in value &&\n (value.status === \"disabled\" ||\n value.status === \"enabling\" ||\n value.status === \"enabled\" ||\n value.status === \"needs-reauthorization\" ||\n value.status === \"needs-migration\" ||\n value.status === \"unavailable\");\n\n/**\n * Merge `next` under `app` into the group's row — the `Partial<G>` map is built dynamically from\n * base `AppGroupState` values under registered ids, exactly the shape `G`'s key space declares.\n */\nconst mergeGroup = <G extends AppGroups>(\n apps: Readonly<Partial<G>> | undefined,\n app: AppId,\n next: AppGroupState,\n): Readonly<Partial<G>> => {\n const merged: Record<string, AppGroupState | undefined> = { ...apps, [app]: next };\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `merged` holds only base states under app ids, the same shape `Partial<G>` declares.\n return merged as Readonly<Partial<G>>;\n};\n\n/** One registered app — the provider plus the availability set `enable`/`renew` start under. */\nexport type AppRegistration = {\n readonly provider: AppProvider;\n readonly enableWhen: ReadonlyArray<Exclude<AppAvailability, \"blocked\">>;\n};\n\nexport type AppsControllerDeps = {\n /** The registered apps — the controller names none of them; the map key is the id. */\n readonly registrations: ReadonlyMap<AppId, AppRegistration>;\n readonly wallet: Wallet;\n readonly requests: Pick<RequestController, \"reject\">;\n readonly openStore: () => Promise<EngineStore>;\n /** `GET /v1/eligibility` through the gateway client — throws on transport/malformed answers. */\n readonly fetchEligibility: () => Promise<EligibilityResponse>;\n /**\n * The constructor hands out the private flow runner once — `createApps` closes over it so each\n * definition's `AppContext.flow` binds its own id through the same guards.\n */\n readonly bindFlow: (\n runner: (group: AppGroup, app: AppId, run: (flow: AppFlow) => Promise<void>) => Promise<void>,\n ) => void;\n readonly now: () => number;\n readonly logger: EngineLogger;\n};\n\n/**\n * The controller's own patch — an `AppGroupPatch` that may also carry `termsAcknowledged`\n * (`acknowledgeTerms` writes it; provider patches never do).\n */\ntype ControllerPatch = {\n readonly [K in keyof AppGroupState]?: AppGroupState[K] | undefined;\n};\n\n/**\n * A state view for `group`/`app` — `write` merges unless the captured generations went stale.\n * `acknowledgeTerms` and `reconcile` share it without starting a flow generation.\n */\ntype ControllerFlow = {\n readonly current: () => AppGroupState;\n readonly write: (patch: ControllerPatch) => void;\n readonly stale: () => boolean;\n};\n\n/**\n * Per-group, per-app state machine owner. `init`/`lock` follow the engine's unlock lifecycle; host\n * calls run provider flows under a per-group+app generation so a superseding call or a lock drops\n * stale writes, and one flow per group+app runs at a time (`busy` otherwise).\n */\nexport class AppsController<G extends AppGroups = AppGroups> extends Controller<AppsState<G>> {\n private readonly deps: AppsControllerDeps;\n private engineStore: EngineStore | undefined;\n private generation = 0;\n private readonly flowGen = new Map<string, number>();\n /** Group+app pairs with a flow in flight — a second enable/renew/disable is `busy`. */\n private readonly busy = new Set<string>();\n /** Request ids the flows opened and have not resolved — rejected on lock/cancel. */\n private readonly pendingRequests = new Set<string>();\n\n constructor(deps: AppsControllerDeps) {\n super({\n name: \"apps\",\n defaultState: () => ({ locked: true, groups: {}, eligibility: { status: \"unknown\" } }),\n });\n this.deps = deps;\n deps.bindFlow(async (group, app, run) => {\n await this.flow(group, app, async (_provider, view) => run(view));\n });\n }\n\n async init(): Promise<void> {\n this.engineStore = await this.deps.openStore();\n const collection = this.engineStore.collection(COLLECTION);\n const keys = await collection.list();\n const groups: Record<string, Readonly<Partial<G>>> = {};\n for (const key of keys) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- records load sequentially on unlock.\n const raw = await collection.get(key);\n const stored = raw === undefined ? undefined : parseRecord(raw);\n const slash = key.lastIndexOf(\"/\");\n const group = key.slice(0, slash);\n const suffix = key.slice(slash + 1);\n const app = this.deps.registrations.has(suffix) ? suffix : undefined;\n if (stored === undefined || app === undefined) {\n this.deps.logger.warn(`apps record ${key} skipped: malformed`);\n } else {\n groups[group] = mergeGroup(groups[group], app, {\n ...DEFAULT_GROUP,\n termsAcknowledged: stored.termsAcknowledged,\n });\n }\n }\n this.update((state) => ({ ...state, locked: false, groups }));\n /* Re-derive every group that can carry state: persisted records and every group with a\n kernel agent on this network. */\n const union = new Map<string, AppGroup>();\n for (const key of Object.keys(groups)) {\n const slash = key.lastIndexOf(\"/\");\n union.set(key, {\n walletId: key.slice(0, slash),\n groupIndex: Number(key.slice(slash + 1)),\n });\n }\n for (const [id, { provider }] of this.deps.registrations) {\n /* A lock mid-init turns the kernel enumeration into an error — groups() fails closed and\n the post-init vault check (transition) runs the lock path. */\n // oxlint-disable-next-line eslint/no-await-in-loop -- providers enumerate in order.\n const discovered = await provider.groups().catch((error: unknown): AppGroup[] => {\n this.deps.logger.warn(`apps groups ${id} failed`, error);\n return [];\n });\n for (const group of discovered) {\n union.set(groupKey(group), group);\n }\n }\n /* Eligibility lands before reconcile so the overlay applies during group derivation. */\n await this.refreshEligibility();\n for (const group of union.values()) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- groups reconcile sequentially.\n await this.reconcile(group);\n }\n }\n\n async destroy(): Promise<void> {\n await this.lock();\n }\n\n async lock(): Promise<void> {\n this.generation += 1;\n this.flowGen.clear();\n this.busy.clear();\n for (const id of this.pendingRequests) {\n this.deps.requests.reject(id);\n }\n this.pendingRequests.clear();\n const store = this.engineStore;\n this.engineStore = undefined;\n /* A locked vault holds no account data — eligibility is not account data and stays. */\n this.update((state) => ({ ...state, locked: true, groups: {} }));\n await store?.close();\n }\n\n private registrationFor(app: AppId): AppRegistration {\n const registration = this.deps.registrations.get(app);\n if (registration === undefined) {\n throw new Error(`app ${app} is not implemented`);\n }\n return registration;\n }\n\n private providerFor(app: AppId): AppProvider {\n return this.registrationFor(app).provider;\n }\n\n private requireUnlocked(app: AppId): void {\n if (this.getState().locked) {\n throw this.providerFor(app).error(\"unlock-required\", \"the vault is locked\");\n }\n }\n\n /** The app's availability under the last ready eligibility answer — undefined otherwise. */\n private availability(app: AppId): AppAvailability | undefined {\n const { eligibility } = this.getState();\n return eligibility.status === \"ready\" ? eligibility.apps?.[app] : undefined;\n }\n\n /**\n * `enable`/`renew` gate: unless eligibility is `ready` and the answer is one the app's\n * `enableWhen` declares, the flow must not start — `unknown`/`error`, an app absent from a ready\n * answer and any undeclared availability all refuse (a jurisdiction gate fails closed). This is a\n * UI boundary only: `disable`/`cancel`/trading are not gated, and the platform enforces its own\n * restrictions. The thrown error is the app's own type.\n */\n private requireAvailable(app: AppId): void {\n const availability = this.availability(app);\n const open =\n availability !== undefined &&\n this.registrationFor(app).enableWhen.some((allowed) => allowed === availability);\n if (!open) {\n const { country, region } = this.getState().eligibility;\n const where =\n country === undefined || country === null\n ? \"an unverified\"\n : `your (${[country, region].filter(Boolean).join(\"-\")})`;\n throw this.providerFor(app).error(\n \"unavailable\",\n `this app is not available in ${where} jurisdiction`,\n );\n }\n }\n\n /**\n * Refetch `/v1/eligibility` and apply the overlay: `disabled` groups in a blocked jurisdiction\n * read `unavailable`; groups that were only overlaid revert when the app is no longer blocked.\n * Called on every unlock; hosts should call it on foreground too.\n */\n async refreshEligibility(): Promise<void> {\n if (this.getState().locked) {\n return;\n }\n try {\n const answer = await this.deps.fetchEligibility();\n this.update((state) => ({\n ...state,\n eligibility: {\n status: \"ready\",\n apps: answer.apps,\n country: answer.country,\n region: answer.region,\n checkedAt: this.deps.now(),\n },\n }));\n } catch (error) {\n this.deps.logger.warn(\"apps eligibility fetch failed\", error);\n this.update((state) => ({\n ...state,\n eligibility: { status: \"error\", checkedAt: this.deps.now() },\n }));\n }\n /* Sweep: apply or lift the overlay on groups already written — `disabled` ↔ `unavailable`\n only; other statuses are never rewritten. */\n const { groups, eligibility } = this.getState();\n const patched: Record<string, Readonly<Partial<G>>> = { ...groups };\n let changed = false;\n for (const [gkey, apps] of Object.entries(groups)) {\n /* `Object.entries` on a generic `Partial<G>` widens to `any` — the controller only ever\n holds base group states, so the value type is stated once here. */\n for (const [app, group] of Object.entries<AppGroupState | undefined>(apps)) {\n const blocked =\n this.deps.registrations.has(app) &&\n eligibility.status === \"ready\" &&\n eligibility.apps?.[app] === \"blocked\";\n if (group?.status === \"disabled\" && blocked) {\n patched[gkey] = mergeGroup(patched[gkey], app, { ...group, status: \"unavailable\" });\n changed = true;\n } else if (group?.status === \"unavailable\" && eligibility.status === \"ready\" && !blocked) {\n patched[gkey] = mergeGroup(patched[gkey], app, { ...group, status: \"disabled\" });\n changed = true;\n }\n }\n }\n if (changed) {\n this.update((state) => ({ ...state, groups: patched }));\n }\n }\n\n private view(group: AppGroup, app: AppId): ControllerFlow {\n const key = recordKey(group, app);\n const gkey = groupKey(group);\n const { generation } = this;\n /* The flow generation captured at creation — a `start` bump or a lock makes it stale. */\n const myGen = this.flowGen.get(key) ?? 0;\n const current = (): AppGroupState => {\n const apps: Partial<Record<AppId, AppGroupState>> | undefined = this.getState().groups[gkey];\n return apps?.[app] ?? DEFAULT_GROUP;\n };\n const stale = (): boolean =>\n generation !== this.generation ||\n (this.flowGen.get(key) ?? 0) !== myGen ||\n this.getState().locked;\n return {\n current,\n stale,\n write: (patch) => {\n if (stale()) {\n return;\n }\n /* `undefined` in a patch deletes the field: the spread puts it last, and the rebuild\n drops every undefined value. */\n const merged: Record<string, unknown> = {};\n for (const [field, value] of Object.entries({ ...current(), ...patch })) {\n if (value !== undefined) {\n merged[field] = value;\n }\n }\n if (!isGroupState(merged)) {\n return;\n }\n const next: AppGroupState =\n merged.status === \"disabled\" && this.availability(app) === \"blocked\"\n ? /* The eligibility overlay: `disabled` under a ready-blocked jurisdiction reads\n `unavailable` — `enabled`/`enabling` are never rewritten. */\n { ...merged, status: \"unavailable\" }\n : merged;\n if (patch.requestId !== undefined) {\n this.pendingRequests.add(patch.requestId);\n }\n if (current().requestId !== undefined && patch.requestId !== current().requestId) {\n this.pendingRequests.delete(current().requestId ?? \"\");\n }\n this.update((state) => ({\n ...state,\n groups: { ...state.groups, [gkey]: mergeGroup(state.groups[gkey], app, next) },\n }));\n },\n };\n }\n\n private groupOf(group: AppGroup): AppGroup {\n return { walletId: group.walletId, groupIndex: group.groupIndex };\n }\n\n /** Bump the group+app's flow generation — a running flow's writes go stale — then hand out a view. */\n private start(group: AppGroup, app: AppId): ControllerFlow {\n const key = recordKey(group, app);\n this.flowGen.set(key, (this.flowGen.get(key) ?? 0) + 1);\n return this.view(group, app);\n }\n\n /** Persisted terms acknowledgement — survives lock/unlock; never supersedes a running flow. */\n async acknowledgeTerms(group: AppGroup, app: Extract<keyof G, string>): Promise<void> {\n this.requireUnlocked(app);\n const key = recordKey(this.groupOf(group), app);\n this.view(this.groupOf(group), app).write({ termsAcknowledged: true });\n /* The record is exactly the terms flag, written only here and only while unlocked — a lock\n that landed mid-write dropped the write and the store along with it. */\n const { engineStore } = this;\n try {\n await engineStore\n ?.collection(COLLECTION)\n .put(key, new TextEncoder().encode(JSON.stringify({ termsAcknowledged: true })));\n } catch (error) {\n this.deps.logger.warn(`apps record ${key} write failed`, error);\n }\n }\n\n private async flow(\n group: AppGroup,\n app: AppId,\n run: (provider: AppProvider, flow: AppFlow) => Promise<void>,\n ): Promise<void> {\n this.requireUnlocked(app);\n const key = recordKey(group, app);\n const provider = this.providerFor(app);\n if (this.busy.has(key)) {\n throw provider.error(\"busy\", \"an enablement flow is already running\");\n }\n const view = this.start(this.groupOf(group), app);\n this.busy.add(key);\n try {\n await run(provider, view);\n } finally {\n this.busy.delete(key);\n }\n }\n\n async enable(group: AppGroup, app: Extract<keyof G, string>, input?: unknown): Promise<void> {\n this.requireAvailable(app);\n await this.flow(group, app, async (provider, view) => provider.enable(group, view, input));\n }\n\n async renew(group: AppGroup, app: Extract<keyof G, string>, input?: unknown): Promise<void> {\n this.requireAvailable(app);\n await this.flow(group, app, async (provider, view) => provider.renew(group, view, input));\n }\n\n async disable(\n group: AppGroup,\n app: Extract<keyof G, string>,\n options: { readonly revoke: boolean; readonly verify?: VerifyFactor },\n ): Promise<void> {\n await this.flow(group, app, async (provider, view) => provider.disable(group, options, view));\n }\n\n /** Abort the running flow: supersede it (its writes die), then reject and clean up. */\n async cancel(group: AppGroup, app: Extract<keyof G, string>): Promise<void> {\n this.requireUnlocked(app);\n const provider = this.providerFor(app);\n const view = this.start(this.groupOf(group), app);\n await provider.cancel(this.groupOf(group), view);\n }\n\n /** Re-derive the group's state from the kernel and the apps' own reads — never a flow. */\n async reconcile(group: AppGroup): Promise<void> {\n if (this.getState().locked) {\n return;\n }\n for (const [app, { provider }] of this.deps.registrations) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- providers reconcile in order.\n await provider\n .reconcile(this.groupOf(group), this.view(this.groupOf(group), app))\n .catch((error: unknown) => {\n this.deps.logger.warn(`apps reconcile ${app} failed`, error);\n });\n }\n }\n\n /**\n * The venue-held authorities every app reports for `group` — display-only, unlocked like the\n * other reads. An app without `authorities` contributes nothing and one's failure lands as its\n * own `{ app, error }` row instead of hiding the rest.\n */\n async authorities(group: AppGroup): Promise<ReadonlyArray<AppAuthorityRow>> {\n const rows: AppAuthorityRow[] = [];\n for (const [app, { provider }] of this.deps.registrations) {\n this.requireUnlocked(app);\n if (provider.authorities === undefined) {\n continue;\n }\n try {\n // oxlint-disable-next-line eslint/no-await-in-loop -- providers read in order.\n for (const authority of await provider.authorities(this.groupOf(group))) {\n rows.push({ app, authority });\n }\n } catch (error) {\n rows.push({ app, error: authorityError(error) });\n }\n }\n return rows;\n }\n}\n\n/**\n * The apps composition: runs each listed definition's `create` over one shared `AppContext`,\n * registers its provider under its id (a duplicate id throws), and drives the controller's\n * lifecycle off the wallet's lock state — the same `transition`/`schedule` chain engine.ts\n * serializes on `wallet.subscribe`. The returned surface mirrors the listed definitions: only their\n * apis appear next to `controller`/`destroy`, and the controller's group state is typed by them.\n */\nexport function createApps<const A extends ReadonlyArray<AppDefinition<AppId, unknown>>>(\n options: CreateAppsOptions & { readonly apps: A },\n): {\n readonly controller: AppsController<AppStates<A>>;\n readonly destroy: () => Promise<void>;\n} & AppApis<A> {\n /* The state accessors and `flow` are lazy: definitions capture them at `create`, but the\n controller only exists once every definition ran — `controllerRef`/`runFlow` read it per\n call. `sessionStore` is the store the controller last opened: set on open, cleared\n synchronously when that store's `close` runs (the controller closes it on lock), which is\n what makes `AppStorage` throw `closed` — and a locked vault reads as closed even before the\n queued transition closes the store. */\n const controllerRef: { current: AppsController<AppStates<A>> | undefined } = {\n current: undefined,\n };\n let runFlow:\n | ((group: AppGroup, app: AppId, run: (flow: AppFlow) => Promise<void>) => Promise<void>)\n | undefined;\n let sessionStore: EngineStore | undefined;\n const unlocked = (): boolean => options.wallet.getSnapshot().vault === \"unlocked\";\n const openStore = async (): Promise<EngineStore> => {\n const store = await options.openStore();\n sessionStore = store;\n return {\n collection: (name) => store.collection(name),\n close: async () => {\n if (sessionStore === store) {\n sessionStore = undefined;\n }\n return store.close();\n },\n };\n };\n /* `id` is the definition's own — captured once at registration: a late `id` read (a getter, or\n a `create` that mutated `this.id`) could otherwise stamp another app's origin. */\n const context = (id: AppId): AppContext => ({\n wallet: options.wallet,\n account: options.account,\n /* Requests the app opens are attributed to it — a provider cannot choose its origin. */\n requests: {\n prepare: async (input) => options.requests.prepare(input, { kind: \"app\", id }),\n outcome: async (id) => options.requests.outcome(id),\n reject: (id) => options.requests.reject(id),\n },\n networks: options.networks,\n fetch: options.fetch,\n now: options.now,\n setTimer: options.setTimer,\n random: options.random,\n logger: options.logger,\n socket: options.socket,\n availability: () => {\n /* Eligibility outlives the lock by design — market views keep working without an\n unlocked wallet, so the last ready answer stays readable. */\n const eligibility = controllerRef.current?.getState().eligibility;\n return eligibility?.status === \"ready\" ? eligibility.apps?.[id] : undefined;\n },\n groupState: (group) => {\n const state: AppsState | undefined = controllerRef.current?.getState();\n return state !== undefined && !state.locked ? state.groups[groupKey(group)]?.[id] : undefined;\n },\n flow: async (group, run) => {\n if (runFlow === undefined) {\n /* Cannot happen after `createApps` returned — the controller bound it in its\n constructor, before any definition's `flow` could run. */\n throw new Error(\"apps flow is not bound\");\n }\n await runFlow(group, id, run);\n },\n storage: createAppStorage(id, () => (unlocked() ? sessionStore : undefined)),\n });\n const registrations = new Map<AppId, AppRegistration>();\n const instances: Array<AppInstance<unknown>> = [];\n const apis: Record<string, unknown> = {};\n const registered: AppId[] = [];\n for (const definition of options.apps) {\n const { id } = definition;\n if (!APP_ID.test(id)) {\n throw new Error(`app ${id} must match ^[a-z][a-z0-9-]{1,31}$`);\n }\n if (registrations.has(id)) {\n throw new Error(`app ${id} is defined twice`);\n }\n if (\n definition.enableWhen.length === 0 ||\n definition.enableWhen.some((allowed) => allowed !== \"available\" && allowed !== \"close-only\")\n ) {\n throw new Error(`app ${id} enableWhen must list \"available\" and/or \"close-only\"`);\n }\n const instance = definition.create(context(id));\n registrations.set(id, { provider: instance.provider, enableWhen: definition.enableWhen });\n instances.push(instance);\n apis[id] = instance.api;\n registered.push(id);\n }\n\n /* Generic prune (design.md 不变量 12): on every unlock and every wallet snapshot change the\n app collections drop the records of wallets the snapshot no longer lists — the wallet id\n is the key prefix before the first \"/\". The controller's own `apps` collection is never\n touched. */\n const prune = async (): Promise<void> => {\n const store = sessionStore;\n if (store === undefined) {\n return;\n }\n const live = new Set(options.wallet.getSnapshot().wallets.map((entry) => entry.walletId));\n for (const id of registered) {\n const collection = store.collection(`apps.${id}`);\n // oxlint-disable-next-line eslint/no-await-in-loop -- collections list and delete sequentially.\n for (const key of await collection.list()) {\n const slash = key.indexOf(\"/\");\n if (!live.has(slash === -1 ? key : key.slice(0, slash))) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- records delete sequentially.\n await collection.delete(key);\n }\n }\n }\n };\n\n /* `gatewayScope(\"/v1/eligibility\")` is \"service\" — a fixed client id keeps the whole contract\n table (which `gatewayFetch` needs for per-route scopes) out of this entry. */\n const clientId = gatewaySession(options.gateway.url, options.random).clientIds.service;\n const eligibilityFetch = async (input: URL): Promise<Response> =>\n options.fetch(input, { headers: { [CLIENT_ID_HEADER]: clientId } });\n const controller = new AppsController<AppStates<A>>({\n registrations,\n wallet: options.wallet,\n bindFlow: (runner) => {\n runFlow = runner;\n },\n fetchEligibility: async (): Promise<EligibilityResponse> => {\n const url = new URL(eligibilityContract.path, options.gateway.url);\n const response = await eligibilityFetch(url);\n if (!response.ok) {\n throw new Error(`eligibility answered ${response.status}`);\n }\n const parsed = parseWith(eligibilityContract.response, await response.json());\n if (parsed === undefined) {\n throw new Error(\"malformed eligibility response\");\n }\n return parsed;\n },\n now: options.now,\n requests: options.requests,\n openStore,\n logger: options.logger,\n });\n controllerRef.current = controller;\n\n /* Serialized lifecycle: every wallet status change queues behind the previous one, so a lock\n during an unlock's init cannot interleave. */\n let started = false;\n let chain: Promise<void> = Promise.resolve();\n const transition = async (): Promise<void> => {\n if (unlocked() && !started) {\n started = true;\n try {\n for (const instance of instances) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- apps unlock in list order.\n await instance.unlock?.();\n }\n await controller.init();\n } catch (error) {\n started = false;\n options.logger.warn(\"apps init failed\", error);\n }\n }\n /* Not `else if`: a lock that lands while init is in flight must still close the store —\n init observes the lock only through its own failure, so the vault is re-read here. */\n if (!unlocked() && started) {\n started = false;\n /* Session marks (enabled/rejected) are per-unlock — the next reconcile re-derives. */\n for (const instance of instances) {\n instance.lock?.();\n }\n await controller.lock();\n }\n /* Every event while running prunes — this covers the post-`init` pass and the wallet\n add/remove/rename snapshots; on a lock the store is already gone and prune no-ops. */\n if (unlocked() && started) {\n await prune();\n }\n };\n const schedule = (): void => {\n const previous = chain;\n chain = (async () => {\n try {\n await previous;\n await transition();\n } catch (error) {\n options.logger.warn(\"apps lock transition failed\", error);\n }\n })();\n };\n const unsubscribe = options.wallet.subscribe(schedule);\n schedule();\n const destroy = async (): Promise<void> => {\n unsubscribe();\n for (const instance of instances) {\n instance.close?.();\n }\n await controller.lock();\n await chain;\n };\n /* Each key in `apis` is the `id` of a definition in `A` holding that definition's `Api` — the\n mapped type says exactly that; the runtime object is built dynamically. */\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `apis` is the dynamic build of the static `AppApis<A>` shape.\n return { controller, ...apis, destroy } as {\n readonly controller: AppsController<AppStates<A>>;\n readonly destroy: () => Promise<void>;\n } & AppApis<A>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAeA,MAAM,OAAO,OAAiB,SAC5B,GAAG,MAAM,SAAS,GAAG,MAAM,WAAW,GAAG;AAE3C,SAA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;EACxB;EAGA,IAAI,SAAS,KAAK,SAChB,MAAM,MAAM;CAEhB;CACA,MAAM,iBAAuB;EAC3B,MAAM,WAAW;EACjB,SAAS,YAAY;GACnB,IAAI;IACF,MAAM;IACN,MAAM,WAAW;GACnB,SAAS,OAAO;IACd,QAAQ,OAAO,KAAK,+BAA+B,KAAK;GAC1D;EACF,EAAA,CAAG;CACL;CACA,MAAM,cAAc,QAAQ,OAAO,UAAU,QAAQ;CACrD,SAAS;CACT,MAAM,UAAU,YAA2B;EACzC,YAAY;EACZ,KAAK,MAAM,YAAY,WACrB,SAAS,QAAQ;EAEnB,MAAM,WAAW,KAAK;EACtB,MAAM;CACR;CAIA,OAAO;EAAE;EAAY,GAAG;EAAM;CAAQ;AAIxC"}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { j as ProviderError } from "./webln-BgrtPXpG.mjs";
|
|
2
|
+
import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
|
|
3
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
4
|
+
// src/connect/inject.generated.ts
|
|
5
|
+
const PROVIDER_SCRIPT = "var qntxProvider = (function(exports) {\n Object.defineProperty(exports, Symbol.toStringTag, { value: \"Module\" });\n // node_modules/.bun/@wallet-standard+wallet@1.1.1/node_modules/@wallet-standard/wallet/lib/esm/register.js\n var __classPrivateFieldGet = function(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n };\n var __classPrivateFieldSet = function(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;\n };\n var _RegisterWalletEvent_detail;\n /**\n * Register a {@link \"@wallet-standard/base\".Wallet} as a Standard Wallet with the app.\n *\n * This dispatches a {@link \"@wallet-standard/base\".WindowRegisterWalletEvent} to notify the app that the Wallet is\n * ready to be registered.\n *\n * This also adds a listener for {@link \"@wallet-standard/base\".WindowAppReadyEvent} to listen for a notification from\n * the app that the app is ready to register the Wallet.\n *\n * This combination of event dispatch and listener guarantees that the Wallet will be registered synchronously as soon\n * as the app is ready whether the Wallet loads before or after the app.\n *\n * @param wallet Wallet to register.\n *\n * @group Wallet\n */\n function registerWallet(wallet) {\n const callback = ({ register }) => register(wallet);\n try {\n window.dispatchEvent(new RegisterWalletEvent(callback));\n } catch (error) {\n console.error(\"wallet-standard:register-wallet event could not be dispatched\\n\", error);\n }\n try {\n window.addEventListener(\"wallet-standard:app-ready\", ({ detail: api }) => callback(api));\n } catch (error) {\n console.error(\"wallet-standard:app-ready event listener could not be added\\n\", error);\n }\n }\n var RegisterWalletEvent = class extends Event {\n get detail() {\n return __classPrivateFieldGet(this, _RegisterWalletEvent_detail, \"f\");\n }\n get type() {\n return \"wallet-standard:register-wallet\";\n }\n constructor(callback) {\n super(\"wallet-standard:register-wallet\", {\n bubbles: false,\n cancelable: false,\n composed: false\n });\n _RegisterWalletEvent_detail.set(this, void 0);\n __classPrivateFieldSet(this, _RegisterWalletEvent_detail, callback, \"f\");\n }\n /** @deprecated */\n preventDefault() {\n throw new Error(\"preventDefault cannot be called\");\n }\n /** @deprecated */\n stopImmediatePropagation() {\n throw new Error(\"stopImmediatePropagation cannot be called\");\n }\n /** @deprecated */\n stopPropagation() {\n throw new Error(\"stopPropagation cannot be called\");\n }\n };\n _RegisterWalletEvent_detail = /* @__PURE__ */ new WeakMap();\n // packages/wallet-engine/src/connect/inject/tron.ts\n /** EIP-1193 `ProviderRpcError`. */\n var ProviderRpcError$1 = class extends Error {\n name = \"ProviderRpcError\";\n code;\n constructor(code, message) {\n super(message);\n this.code = code;\n }\n };\n var isRecord$1 = (v) => typeof v === \"object\" && v !== null && !Array.isArray(v);\n var isProviderState = (v) => isRecord$1(v) && (v[\"address\"] === false || isRecord$1(v[\"address\"]) && typeof v[\"address\"][\"base58\"] === \"string\" && typeof v[\"address\"][\"hex\"] === \"string\") && typeof v[\"chainId\"] === \"string\" && typeof v[\"genesis\"] === \"string\";\n var textEncoder = new TextEncoder();\n /**\n * A member the wallet does not implement: any string key resolves to another refusal function, and\n * calling one throws 4200. `then`/`toJSON`/symbols and `is*` flags resolve `undefined` so the stub\n * is never thenable, never serializes, and never pretends to be another wallet.\n */\n var refuse = (path) => new Proxy(() => void 0, {\n get: (_target, prop) => {\n if (prop === \"then\" || prop === \"toJSON\" || typeof prop === \"symbol\" || prop.startsWith(\"is\")) return;\n return refuse(`${path}.${prop}`);\n },\n apply: () => {\n throw new ProviderRpcError$1(4200, `tronWeb.${path} is not supported by this wallet`);\n }\n });\n /** Wraps an implemented object: its own members win, every other string key refuses. */\n var stub = (path, base) => new Proxy(base, { get: (target, prop) => {\n if (prop === \"then\" || prop === \"toJSON\" || typeof prop === \"symbol\") return;\n return prop in target ? target[prop] : prop.startsWith(\"is\") ? void 0 : refuse(`${path}.${prop}`);\n } });\n /** `signMessageV2` accepts a UTF-8 string, Uint8Array bytes, or a plain number array. */\n var messageBytes = (message) => {\n if (typeof message === \"string\") return textEncoder.encode(message);\n if (message instanceof Uint8Array) return message;\n if (Array.isArray(message) && message.every((b) => Number.isInteger(b) && b >= 0 && b <= 255)) return Uint8Array.from(message);\n throw new ProviderRpcError$1(-32602, \"signMessageV2 needs a string or bytes\");\n };\n function installTron(ctx) {\n const { request, on, removeListener, emit, doc, info, global } = ctx;\n let address = false;\n let chainId = \"0x0\";\n let genesis = \"\";\n const connected = () => address !== false;\n const tronWeb = stub(\"tronWeb\", {\n get ready() {\n return connected();\n },\n get defaultAddress() {\n const a = address;\n return a === false ? {\n base58: false,\n hex: false\n } : {\n base58: a.base58,\n hex: a.hex\n };\n },\n request: async (args) => request(\"tron\", args),\n fullNode: { host: \"\" },\n solidityNode: { host: \"\" },\n eventServer: { host: \"\" },\n setFullNode: () => void 0,\n setSolidityNode: () => void 0,\n setEventServer: () => void 0,\n on,\n removeListener,\n trx: stub(\"trx\", {\n sign: async (tx) => {\n if (typeof tx === \"string\") throw new ProviderRpcError$1(4200, \"trx.sign(hex) signs a raw digest — use signMessageV2\");\n if (!isRecord$1(tx)) throw new ProviderRpcError$1(-32602, \"trx.sign needs a transaction object\");\n return request(\"tron\", {\n method: \"tron_signTransaction\",\n params: { transaction: tx }\n });\n },\n signMessage: async () => {\n throw new ProviderRpcError$1(4200, \"trx.signMessage is not supported — use signMessageV2\");\n },\n multiSign: async () => {\n throw new ProviderRpcError$1(4200, \"multi-signature is not supported\");\n },\n signMessageV2: async (message) => request(\"tron\", {\n method: \"tron_signMessageV2\",\n params: { message: messageBytes(message) }\n }),\n _signTypedData: async (domain, types, value) => request(\"tron\", {\n method: \"tron_signTypedData\",\n params: {\n domain,\n types,\n message: value\n }\n }),\n signTypedData: async (domain, types, value) => request(\"tron\", {\n method: \"tron_signTypedData\",\n params: {\n domain,\n types,\n message: value\n }\n }),\n sendRawTransaction: async (tx) => request(\"tron\", {\n method: \"tron_sendRawTransaction\",\n params: { transaction: tx }\n }),\n getBlockByNumber: async (n) => n === 0 || n === \"0\" ? Promise.resolve({ blockID: genesis }) : Promise.reject(new ProviderRpcError$1(4200, \"tronWeb.trx.getBlockByNumber is not supported by this wallet\"))\n }),\n transactionBuilder: refuse(\"transactionBuilder\"),\n address: refuse(\"address\"),\n utils: refuse(\"utils\"),\n event: refuse(\"event\"),\n plugin: refuse(\"plugin\")\n });\n const tronGlobal = Object.freeze({\n request: async (args) => request(\"tron\", args),\n on,\n removeListener,\n get tronWeb() {\n return connected() ? tronWeb : false;\n }\n });\n const tronLink = Object.freeze({\n get ready() {\n return connected();\n },\n request: async (args) => request(\"tron\", args),\n tronWeb\n });\n /**\n * A new host state: the first connected state is a `connect`, then\n * `accountsChanged`/`addressChanged` track the address and `chainChanged` the network.\n */\n const apply = (state) => {\n const nextAddress = isRecord$1(state.address) && typeof state.address.base58 === \"string\" && typeof state.address.hex === \"string\" ? {\n base58: state.address.base58,\n hex: state.address.hex\n } : false;\n const was = address;\n const wasChain = chainId;\n address = nextAddress;\n chainId = typeof state.chainId === \"string\" ? state.chainId : chainId;\n genesis = typeof state.genesis === \"string\" ? state.genesis : genesis;\n if (was === false && nextAddress !== false) emit(\"connect\", { chainId });\n if ((was === false ? false : was.base58) !== (nextAddress === false ? false : nextAddress.base58)) {\n emit(\"accountsChanged\", nextAddress === false ? [] : [nextAddress.base58]);\n emit(\"addressChanged\", nextAddress === false ? {\n base58: false,\n hex: false\n } : { ...nextAddress });\n }\n if (wasChain !== chainId) emit(\"chainChanged\", { chainId });\n };\n (async () => {\n try {\n const state = await request(\"tron\", { method: \"tron_getProviderState\" });\n if (isProviderState(state)) apply(state);\n } catch {}\n })();\n on(\"tron\", (state) => {\n if (isProviderState(state)) apply(state);\n });\n Object.defineProperty(global, \"tron\", {\n value: tronGlobal,\n writable: false,\n configurable: false\n });\n Object.defineProperty(global, \"tronLink\", {\n value: tronLink,\n writable: false,\n configurable: false\n });\n Object.defineProperty(global, \"tronWeb\", {\n value: tronWeb,\n writable: false,\n configurable: false\n });\n const detail = Object.freeze({\n info: Object.freeze({\n ...info,\n uuid: doc\n }),\n provider: tronGlobal\n });\n const announce = () => {\n global.dispatchEvent(new global.CustomEvent(\"TIP6963:announceProvider\", { detail }));\n };\n announce();\n global.addEventListener(\"TIP6963:requestProvider\", announce);\n }\n // packages/wallet-engine/src/connect/inject/provider.ts\n var bytesToHex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n var hexToBytes = (hex) => {\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i += 1) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n return out;\n };\n var bytesReplacer = (_key, value) => value instanceof Uint8Array ? { __bytes: bytesToHex(value) } : value;\n var isBytesEnvelope = (v) => typeof v === \"object\" && v !== null && typeof v.__bytes === \"string\";\n var bytesReviver = (_key, value) => isBytesEnvelope(value) ? hexToBytes(value.__bytes) : value;\n var isWalletIcon = (value) => /^data:image\\/(?:svg\\+xml|webp|png|gif);base64,/.test(value);\n var page = globalThis;\n var EVENT_ANNOUNCE = \"eip6963:announceProvider\";\n var EVENT_REQUEST = \"eip6963:requestProvider\";\n /** EIP-1193 `ProviderRpcError`. */\n var ProviderRpcError = class extends Error {\n name = \"ProviderRpcError\";\n code;\n constructor(code, message) {\n super(message);\n this.code = code;\n }\n };\n var isRecord = (value) => typeof value === \"object\" && value !== null && !Array.isArray(value);\n /** The host's `{ code, message }` as a ProviderRpcError; anything else is an internal error. */\n var errorOf = (value) => isRecord(value) && typeof value[\"code\"] === \"number\" && typeof value[\"message\"] === \"string\" ? new ProviderRpcError(value[\"code\"], value[\"message\"]) : new ProviderRpcError(-32603, \"internal error\");\n /** The wire shape of Bitcoin sign inputs: accounts travel as their addresses. */\n var btcInputs = (inputs) => inputs.map((input) => ({\n psbt: input.psbt,\n chain: input.chain,\n inputsToSign: input.inputsToSign.map((item) => ({\n address: item.account.address,\n signingIndexes: item.signingIndexes,\n sigHash: item.sigHash\n }))\n }));\n var unsupported = async () => {\n await Promise.resolve();\n throw new Error(\"NotSupported\");\n };\n /**\n * Installs `window.ethereum` (EIP-1193) and the EIP-6963 announcer for `info` in the top-level\n * document; subframes get nothing. `id` increments per request; the pending map settles on the\n * host's reply.\n */\n function install(info) {\n if (page.top !== page.self) return;\n const docBytes = /* @__PURE__ */ new Uint8Array(16);\n crypto.getRandomValues(docBytes);\n docBytes[6] = (docBytes[6] ?? 0) & 15 | 64;\n docBytes[8] = (docBytes[8] ?? 0) & 63 | 128;\n const docHex = bytesToHex(docBytes);\n const doc = `${docHex.slice(0, 8)}-${docHex.slice(8, 12)}-${docHex.slice(12, 16)}-${docHex.slice(16, 20)}-${docHex.slice(20)}`;\n let nextId = 1;\n const pending = /* @__PURE__ */ new Map();\n const listeners = /* @__PURE__ */ new Map();\n const emit = (name, payload) => {\n for (const listener of listeners.get(name) ?? []) try {\n listener(payload);\n } catch {}\n };\n const request = async (provider, args) => {\n if (!isRecord(args) || typeof args.method !== \"string\" || args.method.length === 0) throw new ProviderRpcError(-32602, \"request({ method, params? }) requires a method string\");\n const id = nextId;\n nextId += 1;\n const reply = new Promise((resolve, reject) => {\n pending.set(id, {\n resolve,\n reject\n });\n });\n page.ReactNativeWebView?.postMessage(JSON.stringify({\n qntx: 1,\n doc,\n provider,\n id,\n method: args.method,\n params: args.params\n }, bytesReplacer));\n return reply;\n };\n const on = (name, listener) => {\n const set = listeners.get(name) ?? /* @__PURE__ */ new Set();\n set.add(listener);\n listeners.set(name, set);\n };\n const removeListener = (name, listener) => {\n listeners.get(name)?.delete(listener);\n };\n const provider = Object.freeze({\n request: async (args) => {\n return await request(\"eip1193\", args);\n },\n on,\n removeListener\n });\n const nostr = Object.freeze({\n getPublicKey: async () => {\n return await request(\"nostr\", { method: \"getPublicKey\" });\n },\n signEvent: async (event) => {\n return await request(\"nostr\", {\n method: \"signEvent\",\n params: [event]\n });\n },\n nip04: Object.freeze({\n encrypt: async (pubkey, plaintext) => {\n return await request(\"nostr\", {\n method: \"nip04.encrypt\",\n params: [pubkey, plaintext]\n });\n },\n decrypt: async (pubkey, ciphertext) => {\n return await request(\"nostr\", {\n method: \"nip04.decrypt\",\n params: [pubkey, ciphertext]\n });\n }\n }),\n nip44: Object.freeze({\n encrypt: async (pubkey, plaintext) => {\n return await request(\"nostr\", {\n method: \"nip44.encrypt\",\n params: [pubkey, plaintext]\n });\n },\n decrypt: async (pubkey, ciphertext) => {\n return await request(\"nostr\", {\n method: \"nip44.decrypt\",\n params: [pubkey, ciphertext]\n });\n }\n })\n });\n const webln = Object.freeze({\n enable: async () => {\n return await request(\"webln\", { method: \"enable\" });\n },\n getInfo: async () => {\n return await request(\"webln\", { method: \"getInfo\" });\n },\n sendPayment: async (invoice) => {\n return await request(\"webln\", {\n method: \"sendPayment\",\n params: invoice\n });\n },\n makeInvoice: async (args) => {\n return await request(\"webln\", {\n method: \"makeInvoice\",\n params: args\n });\n },\n lnurl: async (lnurl) => {\n return await request(\"webln\", {\n method: \"lnurl\",\n params: lnurl\n });\n },\n getBalance: async () => {\n return await request(\"webln\", { method: \"getBalance\" });\n },\n keysend: unsupported,\n signMessage: unsupported,\n verifyMessage: unsupported,\n request: unsupported\n });\n const receive = (json) => {\n let message;\n try {\n message = JSON.parse(json, bytesReviver);\n } catch {\n return;\n }\n if (!isRecord(message)) return;\n if (message[\"doc\"] !== void 0 && message[\"doc\"] !== doc) return;\n const { id, event } = message;\n if (typeof id === \"number\") {\n const settle = pending.get(id);\n pending.delete(id);\n if (settle !== void 0) {\n if (\"error\" in message) settle.reject(errorOf(message[\"error\"]));\n else settle.resolve(message[\"result\"]);\n }\n return;\n }\n if (typeof event === \"string\") emit(event, message[\"data\"]);\n };\n Object.defineProperty(globalThis, \"__qntxReceive\", {\n value: receive,\n writable: false,\n configurable: false\n });\n Object.defineProperty(globalThis, \"ethereum\", {\n value: provider,\n writable: false,\n configurable: false\n });\n Object.defineProperty(globalThis, \"nostr\", {\n value: nostr,\n writable: false,\n configurable: false\n });\n Object.defineProperty(globalThis, \"webln\", {\n value: webln,\n writable: false,\n configurable: false\n });\n installTron({\n request,\n on,\n removeListener,\n emit,\n doc,\n info,\n global: page\n });\n const wsAccounts = [];\n const setAccounts = (accounts) => {\n wsAccounts.length = 0;\n wsAccounts.push(...accounts);\n };\n const signTransactions = async (method, inputs) => request(\"solana\", {\n method,\n params: {\n transactions: inputs.map((input) => input.transaction),\n accounts: inputs.map((input) => input.account.address),\n chains: inputs.map((input) => input.chain)\n }\n });\n const wsFeatures = {\n \"standard:connect\": {\n version: \"1.0.0\",\n connect: async (input) => {\n const result = await request(\"solana\", {\n method: \"standard:connect\",\n params: input\n });\n setAccounts(result.accounts);\n return { accounts: [...wsAccounts] };\n }\n },\n \"standard:disconnect\": {\n version: \"1.0.0\",\n disconnect: async () => {\n await request(\"solana\", { method: \"standard:disconnect\" });\n setAccounts([]);\n }\n },\n \"standard:events\": {\n version: \"1.0.0\",\n on: (event, cb) => {\n const listener = (data) => {\n const d = data;\n if (d.event === event) {\n setAccounts(d.params?.accounts ?? []);\n cb({ accounts: [...wsAccounts] });\n }\n };\n on(\"standard:events\", listener);\n return () => {\n removeListener(\"standard:events\", listener);\n };\n }\n },\n \"solana:signTransaction\": {\n version: \"1.0.0\",\n supportedTransactionVersions: [\n \"legacy\",\n 0,\n 1\n ],\n signTransaction: async (...inputs) => {\n return (await signTransactions(\"solana:signTransaction\", inputs)).signedTransactions.map((signedTransaction) => ({ signedTransaction }));\n }\n },\n \"solana:signAndSendTransaction\": {\n version: \"1.0.0\",\n supportedTransactionVersions: [\n \"legacy\",\n 0,\n 1\n ],\n signAndSendTransaction: async (...inputs) => {\n return (await signTransactions(\"solana:signAndSendTransaction\", inputs)).signatures.map((signature) => ({ signature }));\n }\n },\n \"solana:signMessage\": {\n version: \"1.0.0\",\n signMessage: async (...inputs) => {\n if (inputs.length !== 1 || inputs[0] === void 0) throw new Error(\"solana:signMessage accepts one input at a time\");\n const [input] = inputs;\n const result = await request(\"solana\", {\n method: \"solana:signMessage\",\n params: {\n message: input.message,\n accounts: [input.account.address]\n }\n });\n return [{\n signedMessage: result.signedMessage,\n signature: result.signature,\n signatureType: \"ed25519\"\n }];\n }\n },\n \"solana:signIn\": {\n version: \"1.0.0\",\n signIn: async (...inputs) => {\n if (inputs.length > 1) throw new Error(\"solana:signIn accepts one input at a time\");\n return await request(\"solana\", {\n method: \"solana:signIn\",\n params: { input: inputs[0] ?? {} }\n });\n }\n }\n };\n if (!isWalletIcon(info.icon)) throw new Error(\"the provider icon is not a data URI image\");\n registerWallet(Object.freeze({\n version: \"1.0.0\",\n name: info.name,\n icon: info.icon,\n chains: Object.freeze([\"solana:mainnet\", \"solana:devnet\"]),\n features: Object.freeze(wsFeatures),\n get accounts() {\n return wsAccounts;\n }\n }));\n const btcAccounts = [];\n const setBtcAccounts = (accounts) => {\n btcAccounts.length = 0;\n btcAccounts.push(...accounts);\n };\n const btcDisconnect = async () => {\n await request(\"bitcoin\", { method: \"standard:disconnect\" });\n setBtcAccounts([]);\n };\n const btcFeatures = {\n \"standard:disconnect\": {\n version: \"1.0.0\",\n disconnect: btcDisconnect\n },\n \"bitcoin:connect\": {\n version: \"1.0.0\",\n connect: async (input) => {\n const result = await request(\"bitcoin\", {\n method: \"bitcoin:connect\",\n params: input\n });\n setBtcAccounts(result.accounts);\n return { accounts: [...btcAccounts] };\n }\n },\n \"bitcoin:disconnect\": {\n version: \"1.0.0\",\n disconnect: btcDisconnect\n },\n \"bitcoin:events\": {\n version: \"1.0.0\",\n on: (event, cb) => {\n const listener = (data) => {\n const d = data;\n if (d.event === event) {\n setBtcAccounts(d.params?.accounts ?? []);\n cb({ accounts: [...btcAccounts] });\n }\n };\n on(\"bitcoin:events\", listener);\n return () => {\n removeListener(\"bitcoin:events\", listener);\n };\n }\n },\n \"bitcoin:signMessage\": {\n version: \"1.0.0\",\n signMessage: async (...inputs) => {\n if (inputs.length !== 1 || inputs[0] === void 0) throw new Error(\"bitcoin:signMessage accepts one input at a time\");\n const [input] = inputs;\n const result = await request(\"bitcoin\", {\n method: \"bitcoin:signMessage\",\n params: {\n account: input.account.address,\n message: input.message\n }\n });\n return [{\n signedMessage: result.signedMessage,\n signature: result.signature\n }];\n }\n },\n \"bitcoin:signTransaction\": {\n version: \"1.0.0\",\n signTransaction: async (...inputs) => {\n return await request(\"bitcoin\", {\n method: \"bitcoin:signTransaction\",\n params: { inputs: btcInputs(inputs) }\n });\n }\n },\n \"bitcoin:signAndSendTransaction\": {\n version: \"1.0.0\",\n signAndSendTransaction: async (...inputs) => {\n return await request(\"bitcoin\", {\n method: \"bitcoin:signAndSendTransaction\",\n params: { inputs: btcInputs(inputs) }\n });\n }\n }\n };\n registerWallet(Object.freeze({\n version: \"1.0.0\",\n name: info.name,\n icon: info.icon,\n chains: Object.freeze([\"bitcoin:mainnet\", \"bitcoin:testnet\"]),\n features: Object.freeze(btcFeatures),\n get accounts() {\n return btcAccounts;\n }\n }));\n const detail = Object.freeze({\n info: Object.freeze({\n ...info,\n uuid: doc\n }),\n provider\n });\n const announce = () => {\n globalThis.dispatchEvent(new CustomEvent(EVENT_ANNOUNCE, { detail }));\n };\n announce();\n globalThis.addEventListener(EVENT_REQUEST, announce);\n }\n exports.install = install;\n return exports;\n})({});\n";
|
|
6
|
+
// src/connect/index.ts
|
|
7
|
+
/**
|
|
8
|
+
* `@qntx/wallet-engine/connect` — the in-app-browser provider injection and message bridge.
|
|
9
|
+
* Platform-neutral: the injected script is a plain string the host runs in the WebView; the bridge
|
|
10
|
+
* lives in the main runtime and speaks `postMessage`/`injectJavaScript` through the host's `inject`
|
|
11
|
+
* hook. No WebView or DOM types cross this boundary.
|
|
12
|
+
*/
|
|
13
|
+
const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
14
|
+
const ICON_PREFIX = /^data:image\/(png|svg\+xml|webp);base64,/;
|
|
15
|
+
const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
16
|
+
const RDNS_LABEL = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
|
|
17
|
+
const MAX_ICON_B64 = 65536;
|
|
18
|
+
const bad = (message) => /* @__PURE__ */ new Error(`ProviderInfo: ${message}`);
|
|
19
|
+
function checkInfo(info) {
|
|
20
|
+
if (typeof info !== "object" || info === null) throw bad("not an object");
|
|
21
|
+
if (typeof info.name !== "string" || info.name.length === 0 || info.name.length > 64) throw bad("name must be 1–64 characters");
|
|
22
|
+
const iconMatch = ICON_PREFIX.exec(info.icon);
|
|
23
|
+
if (iconMatch === null) throw bad("icon is not a png/svg+xml/webp data URL");
|
|
24
|
+
const base64 = info.icon.slice(iconMatch[0].length);
|
|
25
|
+
if (base64.length > MAX_ICON_B64 || !BASE64.test(base64)) throw bad("icon base64 is empty or over 64 KiB");
|
|
26
|
+
if (typeof info.rdns !== "string" || info.rdns.length === 0 || !info.rdns.split(".").every((label) => RDNS_LABEL.test(label)) || info.rdns.split(".").length < 2) throw bad("rdns is not lowercase reverse-DNS labels");
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The script the host injects into the page: the fixed provider body plus one
|
|
30
|
+
* `qntxProvider.install` call carrying `info` — the script itself generates the EIP-6963 uuid per
|
|
31
|
+
* document. `info` is strictly validated — an invalid field throws before the script is produced,
|
|
32
|
+
* so a misconfigured host fails before anything reaches the page.
|
|
33
|
+
*/
|
|
34
|
+
function injectedScript(info) {
|
|
35
|
+
checkInfo(info);
|
|
36
|
+
return `${PROVIDER_SCRIPT}\nqntxProvider.install(${JSON.stringify(info)});`;
|
|
37
|
+
}
|
|
38
|
+
/** SHA-256 (hex) of the fixed provider script — no install call — for the CI freshness check. */
|
|
39
|
+
const PROVIDER_SCRIPT_SHA256 = bytesToHex(sha256(utf8ToBytes(PROVIDER_SCRIPT)));
|
|
40
|
+
/** The largest JSON message a transport accepts — the WalletConnect entry applies the same limit. */
|
|
41
|
+
const MAX_MESSAGE_BYTES = 131072;
|
|
42
|
+
const RATE_LIMIT_PER_MINUTE = 120;
|
|
43
|
+
const RATE_WINDOW_MS = 6e4;
|
|
44
|
+
const DISCONNECT = {
|
|
45
|
+
code: 4900,
|
|
46
|
+
message: "disconnected"
|
|
47
|
+
};
|
|
48
|
+
const isObject = (v) => typeof v === "object" && v !== null;
|
|
49
|
+
/** `Uint8Array` carries over the JSON wire as `{ __bytes: hex }`; the injected reviver restores it. */
|
|
50
|
+
const bytesReplacer = (_key, value) => value instanceof Uint8Array ? { __bytes: bytesToHex(value) } : value;
|
|
51
|
+
/** The EIP-1193 listener payload of an engine event. */
|
|
52
|
+
const eventData = (event) => {
|
|
53
|
+
if (event.name === "connect") return { chainId: event.chainId };
|
|
54
|
+
if (event.name === "accountsChanged") return event.accounts;
|
|
55
|
+
return event.name === "chainChanged" ? event.chainId : DISCONNECT;
|
|
56
|
+
};
|
|
57
|
+
/** A provider error keeps its code and message; anything else is an opaque internal error. */
|
|
58
|
+
const errorData = (error) => error instanceof ProviderError ? {
|
|
59
|
+
code: error.code,
|
|
60
|
+
message: error.message
|
|
61
|
+
} : {
|
|
62
|
+
code: -32603,
|
|
63
|
+
message: "internal error"
|
|
64
|
+
};
|
|
65
|
+
function createBrowserBridge(options) {
|
|
66
|
+
const { eip1193, nip07, webln, solana, bitcoin, tron, connections, inject, now } = options;
|
|
67
|
+
let topOrigin;
|
|
68
|
+
/** The current document's id; a same-origin reload's first message switches it. */
|
|
69
|
+
let topDocument;
|
|
70
|
+
let disposed = false;
|
|
71
|
+
/** Per-origin request timestamps in the current window, for the 120/min cap. */
|
|
72
|
+
const hits = /* @__PURE__ */ new Map();
|
|
73
|
+
const originOf = (topUrl) => {
|
|
74
|
+
try {
|
|
75
|
+
const { origin } = new URL(topUrl);
|
|
76
|
+
connections.checkOrigin(origin);
|
|
77
|
+
return origin;
|
|
78
|
+
} catch {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
const receive = (payload) => {
|
|
83
|
+
inject(`globalThis.__qntxReceive(${JSON.stringify(JSON.stringify(payload, bytesReplacer))})`);
|
|
84
|
+
};
|
|
85
|
+
const rateLimited = (origin) => {
|
|
86
|
+
const window_ = now() - RATE_WINDOW_MS;
|
|
87
|
+
const hitsFor = (hits.get(origin) ?? []).filter((at) => at > window_);
|
|
88
|
+
hits.set(origin, hitsFor);
|
|
89
|
+
if (hitsFor.length >= RATE_LIMIT_PER_MINUTE) return true;
|
|
90
|
+
hitsFor.push(now());
|
|
91
|
+
return false;
|
|
92
|
+
};
|
|
93
|
+
/** Events go to the current document; its id lets a stale page's listener ignore them. */
|
|
94
|
+
const toPage = (payload) => {
|
|
95
|
+
receive(topDocument === void 0 ? payload : {
|
|
96
|
+
doc: topDocument,
|
|
97
|
+
...payload
|
|
98
|
+
});
|
|
99
|
+
};
|
|
100
|
+
const unsubscribe = eip1193.subscribe((event) => {
|
|
101
|
+
if (disposed || topOrigin === void 0 || event.origin !== topOrigin) return;
|
|
102
|
+
toPage({
|
|
103
|
+
event: event.name,
|
|
104
|
+
data: eventData(event)
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
const unsubscribeSolana = solana.subscribe((event) => {
|
|
108
|
+
if (disposed || topOrigin === void 0 || event.origin !== topOrigin) return;
|
|
109
|
+
toPage({
|
|
110
|
+
event: "standard:events",
|
|
111
|
+
data: {
|
|
112
|
+
event: "change",
|
|
113
|
+
params: { accounts: event.accounts }
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
const unsubscribeBitcoin = bitcoin.subscribe((event) => {
|
|
118
|
+
if (disposed || topOrigin === void 0 || event.origin !== topOrigin) return;
|
|
119
|
+
toPage({
|
|
120
|
+
event: "bitcoin:events",
|
|
121
|
+
data: {
|
|
122
|
+
event: "change",
|
|
123
|
+
params: { accounts: event.accounts }
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
const unsubscribeTron = tron.subscribe((event) => {
|
|
128
|
+
if (disposed || topOrigin === void 0 || event.origin !== topOrigin) return;
|
|
129
|
+
toPage({
|
|
130
|
+
event: "tron",
|
|
131
|
+
data: event.state
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
const message = (topUrl, data) => {
|
|
135
|
+
if (disposed || data.length > 131072) return;
|
|
136
|
+
const origin = originOf(topUrl);
|
|
137
|
+
if (origin === void 0 || origin !== topOrigin) return;
|
|
138
|
+
let parsed;
|
|
139
|
+
try {
|
|
140
|
+
parsed = JSON.parse(data);
|
|
141
|
+
} catch {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (!isObject(parsed)) return;
|
|
145
|
+
const { id, method, params, qntx, provider, doc } = parsed;
|
|
146
|
+
if (qntx !== 1 || typeof id !== "number" || !Number.isSafeInteger(id) || id < 0 || typeof method !== "string" || typeof doc !== "string" || !UUID_V4.test(doc)) return;
|
|
147
|
+
if (doc !== topDocument) {
|
|
148
|
+
if (topDocument !== void 0) connections.invalidateOrigin(origin);
|
|
149
|
+
topDocument = doc;
|
|
150
|
+
}
|
|
151
|
+
const handler = provider === "eip1193" ? eip1193 : provider === "nostr" ? nip07 : provider === "webln" ? webln : provider === "solana" ? solana : provider === "bitcoin" ? bitcoin : provider === "tron" ? tron : void 0;
|
|
152
|
+
if (handler === void 0) return;
|
|
153
|
+
if (rateLimited(origin)) {
|
|
154
|
+
receive({
|
|
155
|
+
doc,
|
|
156
|
+
id,
|
|
157
|
+
error: DISCONNECT
|
|
158
|
+
});
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
(async () => {
|
|
162
|
+
try {
|
|
163
|
+
const result = await handler.handle(origin, params === void 0 ? { method } : {
|
|
164
|
+
method,
|
|
165
|
+
params
|
|
166
|
+
});
|
|
167
|
+
if (!disposed && origin === topOrigin && doc === topDocument) receive({
|
|
168
|
+
doc,
|
|
169
|
+
id,
|
|
170
|
+
result
|
|
171
|
+
});
|
|
172
|
+
} catch (error) {
|
|
173
|
+
if (!disposed && origin === topOrigin && doc === topDocument) receive({
|
|
174
|
+
doc,
|
|
175
|
+
id,
|
|
176
|
+
error: errorData(error)
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
})();
|
|
180
|
+
};
|
|
181
|
+
const navigated = (topUrl) => {
|
|
182
|
+
if (disposed) return;
|
|
183
|
+
const next = originOf(topUrl);
|
|
184
|
+
if (next !== topOrigin) {
|
|
185
|
+
if (topOrigin !== void 0) connections.invalidateOrigin(topOrigin);
|
|
186
|
+
topOrigin = next;
|
|
187
|
+
topDocument = void 0;
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
const dispose = () => {
|
|
191
|
+
if (disposed) return;
|
|
192
|
+
disposed = true;
|
|
193
|
+
unsubscribe();
|
|
194
|
+
unsubscribeSolana();
|
|
195
|
+
unsubscribeBitcoin();
|
|
196
|
+
unsubscribeTron();
|
|
197
|
+
if (topOrigin !== void 0) {
|
|
198
|
+
connections.invalidateOrigin(topOrigin);
|
|
199
|
+
topOrigin = void 0;
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
return {
|
|
203
|
+
message,
|
|
204
|
+
navigated,
|
|
205
|
+
dispose
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
export { injectedScript as i, PROVIDER_SCRIPT_SHA256 as n, createBrowserBridge as r, MAX_MESSAGE_BYTES as t };
|
|
209
|
+
|
|
210
|
+
//# sourceMappingURL=connect-BY1C5ZRI.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-BY1C5ZRI.mjs","names":[],"sources":["../src/connect/inject.generated.ts","../src/connect/index.ts"],"sourcesContent":["// GENERATED by scripts/build-provider.ts — do not edit; run `bun run connect:provider`.\nexport const PROVIDER_SCRIPT: string = \"var qntxProvider = (function(exports) {\\n\\tObject.defineProperty(exports, Symbol.toStringTag, { value: \\\"Module\\\" });\\n\\t// node_modules/.bun/@wallet-standard+wallet@1.1.1/node_modules/@wallet-standard/wallet/lib/esm/register.js\\n\\tvar __classPrivateFieldGet = function(receiver, state, kind, f) {\\n\\t\\tif (kind === \\\"a\\\" && !f) throw new TypeError(\\\"Private accessor was defined without a getter\\\");\\n\\t\\tif (typeof state === \\\"function\\\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\\\"Cannot read private member from an object whose class did not declare it\\\");\\n\\t\\treturn kind === \\\"m\\\" ? f : kind === \\\"a\\\" ? f.call(receiver) : f ? f.value : state.get(receiver);\\n\\t};\\n\\tvar __classPrivateFieldSet = function(receiver, state, value, kind, f) {\\n\\t\\tif (kind === \\\"m\\\") throw new TypeError(\\\"Private method is not writable\\\");\\n\\t\\tif (kind === \\\"a\\\" && !f) throw new TypeError(\\\"Private accessor was defined without a setter\\\");\\n\\t\\tif (typeof state === \\\"function\\\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\\\"Cannot write private member to an object whose class did not declare it\\\");\\n\\t\\treturn kind === \\\"a\\\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;\\n\\t};\\n\\tvar _RegisterWalletEvent_detail;\\n\\t/**\\n\\t* Register a {@link \\\"@wallet-standard/base\\\".Wallet} as a Standard Wallet with the app.\\n\\t*\\n\\t* This dispatches a {@link \\\"@wallet-standard/base\\\".WindowRegisterWalletEvent} to notify the app that the Wallet is\\n\\t* ready to be registered.\\n\\t*\\n\\t* This also adds a listener for {@link \\\"@wallet-standard/base\\\".WindowAppReadyEvent} to listen for a notification from\\n\\t* the app that the app is ready to register the Wallet.\\n\\t*\\n\\t* This combination of event dispatch and listener guarantees that the Wallet will be registered synchronously as soon\\n\\t* as the app is ready whether the Wallet loads before or after the app.\\n\\t*\\n\\t* @param wallet Wallet to register.\\n\\t*\\n\\t* @group Wallet\\n\\t*/\\n\\tfunction registerWallet(wallet) {\\n\\t\\tconst callback = ({ register }) => register(wallet);\\n\\t\\ttry {\\n\\t\\t\\twindow.dispatchEvent(new RegisterWalletEvent(callback));\\n\\t\\t} catch (error) {\\n\\t\\t\\tconsole.error(\\\"wallet-standard:register-wallet event could not be dispatched\\\\n\\\", error);\\n\\t\\t}\\n\\t\\ttry {\\n\\t\\t\\twindow.addEventListener(\\\"wallet-standard:app-ready\\\", ({ detail: api }) => callback(api));\\n\\t\\t} catch (error) {\\n\\t\\t\\tconsole.error(\\\"wallet-standard:app-ready event listener could not be added\\\\n\\\", error);\\n\\t\\t}\\n\\t}\\n\\tvar RegisterWalletEvent = class extends Event {\\n\\t\\tget detail() {\\n\\t\\t\\treturn __classPrivateFieldGet(this, _RegisterWalletEvent_detail, \\\"f\\\");\\n\\t\\t}\\n\\t\\tget type() {\\n\\t\\t\\treturn \\\"wallet-standard:register-wallet\\\";\\n\\t\\t}\\n\\t\\tconstructor(callback) {\\n\\t\\t\\tsuper(\\\"wallet-standard:register-wallet\\\", {\\n\\t\\t\\t\\tbubbles: false,\\n\\t\\t\\t\\tcancelable: false,\\n\\t\\t\\t\\tcomposed: false\\n\\t\\t\\t});\\n\\t\\t\\t_RegisterWalletEvent_detail.set(this, void 0);\\n\\t\\t\\t__classPrivateFieldSet(this, _RegisterWalletEvent_detail, callback, \\\"f\\\");\\n\\t\\t}\\n\\t\\t/** @deprecated */\\n\\t\\tpreventDefault() {\\n\\t\\t\\tthrow new Error(\\\"preventDefault cannot be called\\\");\\n\\t\\t}\\n\\t\\t/** @deprecated */\\n\\t\\tstopImmediatePropagation() {\\n\\t\\t\\tthrow new Error(\\\"stopImmediatePropagation cannot be called\\\");\\n\\t\\t}\\n\\t\\t/** @deprecated */\\n\\t\\tstopPropagation() {\\n\\t\\t\\tthrow new Error(\\\"stopPropagation cannot be called\\\");\\n\\t\\t}\\n\\t};\\n\\t_RegisterWalletEvent_detail = /* @__PURE__ */ new WeakMap();\\n\\t// packages/wallet-engine/src/connect/inject/tron.ts\\n\\t/** EIP-1193 `ProviderRpcError`. */\\n\\tvar ProviderRpcError$1 = class extends Error {\\n\\t\\tname = \\\"ProviderRpcError\\\";\\n\\t\\tcode;\\n\\t\\tconstructor(code, message) {\\n\\t\\t\\tsuper(message);\\n\\t\\t\\tthis.code = code;\\n\\t\\t}\\n\\t};\\n\\tvar isRecord$1 = (v) => typeof v === \\\"object\\\" && v !== null && !Array.isArray(v);\\n\\tvar isProviderState = (v) => isRecord$1(v) && (v[\\\"address\\\"] === false || isRecord$1(v[\\\"address\\\"]) && typeof v[\\\"address\\\"][\\\"base58\\\"] === \\\"string\\\" && typeof v[\\\"address\\\"][\\\"hex\\\"] === \\\"string\\\") && typeof v[\\\"chainId\\\"] === \\\"string\\\" && typeof v[\\\"genesis\\\"] === \\\"string\\\";\\n\\tvar textEncoder = new TextEncoder();\\n\\t/**\\n\\t* A member the wallet does not implement: any string key resolves to another refusal function, and\\n\\t* calling one throws 4200. `then`/`toJSON`/symbols and `is*` flags resolve `undefined` so the stub\\n\\t* is never thenable, never serializes, and never pretends to be another wallet.\\n\\t*/\\n\\tvar refuse = (path) => new Proxy(() => void 0, {\\n\\t\\tget: (_target, prop) => {\\n\\t\\t\\tif (prop === \\\"then\\\" || prop === \\\"toJSON\\\" || typeof prop === \\\"symbol\\\" || prop.startsWith(\\\"is\\\")) return;\\n\\t\\t\\treturn refuse(`${path}.${prop}`);\\n\\t\\t},\\n\\t\\tapply: () => {\\n\\t\\t\\tthrow new ProviderRpcError$1(4200, `tronWeb.${path} is not supported by this wallet`);\\n\\t\\t}\\n\\t});\\n\\t/** Wraps an implemented object: its own members win, every other string key refuses. */\\n\\tvar stub = (path, base) => new Proxy(base, { get: (target, prop) => {\\n\\t\\tif (prop === \\\"then\\\" || prop === \\\"toJSON\\\" || typeof prop === \\\"symbol\\\") return;\\n\\t\\treturn prop in target ? target[prop] : prop.startsWith(\\\"is\\\") ? void 0 : refuse(`${path}.${prop}`);\\n\\t} });\\n\\t/** `signMessageV2` accepts a UTF-8 string, Uint8Array bytes, or a plain number array. */\\n\\tvar messageBytes = (message) => {\\n\\t\\tif (typeof message === \\\"string\\\") return textEncoder.encode(message);\\n\\t\\tif (message instanceof Uint8Array) return message;\\n\\t\\tif (Array.isArray(message) && message.every((b) => Number.isInteger(b) && b >= 0 && b <= 255)) return Uint8Array.from(message);\\n\\t\\tthrow new ProviderRpcError$1(-32602, \\\"signMessageV2 needs a string or bytes\\\");\\n\\t};\\n\\tfunction installTron(ctx) {\\n\\t\\tconst { request, on, removeListener, emit, doc, info, global } = ctx;\\n\\t\\tlet address = false;\\n\\t\\tlet chainId = \\\"0x0\\\";\\n\\t\\tlet genesis = \\\"\\\";\\n\\t\\tconst connected = () => address !== false;\\n\\t\\tconst tronWeb = stub(\\\"tronWeb\\\", {\\n\\t\\t\\tget ready() {\\n\\t\\t\\t\\treturn connected();\\n\\t\\t\\t},\\n\\t\\t\\tget defaultAddress() {\\n\\t\\t\\t\\tconst a = address;\\n\\t\\t\\t\\treturn a === false ? {\\n\\t\\t\\t\\t\\tbase58: false,\\n\\t\\t\\t\\t\\thex: false\\n\\t\\t\\t\\t} : {\\n\\t\\t\\t\\t\\tbase58: a.base58,\\n\\t\\t\\t\\t\\thex: a.hex\\n\\t\\t\\t\\t};\\n\\t\\t\\t},\\n\\t\\t\\trequest: async (args) => request(\\\"tron\\\", args),\\n\\t\\t\\tfullNode: { host: \\\"\\\" },\\n\\t\\t\\tsolidityNode: { host: \\\"\\\" },\\n\\t\\t\\teventServer: { host: \\\"\\\" },\\n\\t\\t\\tsetFullNode: () => void 0,\\n\\t\\t\\tsetSolidityNode: () => void 0,\\n\\t\\t\\tsetEventServer: () => void 0,\\n\\t\\t\\ton,\\n\\t\\t\\tremoveListener,\\n\\t\\t\\ttrx: stub(\\\"trx\\\", {\\n\\t\\t\\t\\tsign: async (tx) => {\\n\\t\\t\\t\\t\\tif (typeof tx === \\\"string\\\") throw new ProviderRpcError$1(4200, \\\"trx.sign(hex) signs a raw digest — use signMessageV2\\\");\\n\\t\\t\\t\\t\\tif (!isRecord$1(tx)) throw new ProviderRpcError$1(-32602, \\\"trx.sign needs a transaction object\\\");\\n\\t\\t\\t\\t\\treturn request(\\\"tron\\\", {\\n\\t\\t\\t\\t\\t\\tmethod: \\\"tron_signTransaction\\\",\\n\\t\\t\\t\\t\\t\\tparams: { transaction: tx }\\n\\t\\t\\t\\t\\t});\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tsignMessage: async () => {\\n\\t\\t\\t\\t\\tthrow new ProviderRpcError$1(4200, \\\"trx.signMessage is not supported — use signMessageV2\\\");\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tmultiSign: async () => {\\n\\t\\t\\t\\t\\tthrow new ProviderRpcError$1(4200, \\\"multi-signature is not supported\\\");\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tsignMessageV2: async (message) => request(\\\"tron\\\", {\\n\\t\\t\\t\\t\\tmethod: \\\"tron_signMessageV2\\\",\\n\\t\\t\\t\\t\\tparams: { message: messageBytes(message) }\\n\\t\\t\\t\\t}),\\n\\t\\t\\t\\t_signTypedData: async (domain, types, value) => request(\\\"tron\\\", {\\n\\t\\t\\t\\t\\tmethod: \\\"tron_signTypedData\\\",\\n\\t\\t\\t\\t\\tparams: {\\n\\t\\t\\t\\t\\t\\tdomain,\\n\\t\\t\\t\\t\\t\\ttypes,\\n\\t\\t\\t\\t\\t\\tmessage: value\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}),\\n\\t\\t\\t\\tsignTypedData: async (domain, types, value) => request(\\\"tron\\\", {\\n\\t\\t\\t\\t\\tmethod: \\\"tron_signTypedData\\\",\\n\\t\\t\\t\\t\\tparams: {\\n\\t\\t\\t\\t\\t\\tdomain,\\n\\t\\t\\t\\t\\t\\ttypes,\\n\\t\\t\\t\\t\\t\\tmessage: value\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}),\\n\\t\\t\\t\\tsendRawTransaction: async (tx) => request(\\\"tron\\\", {\\n\\t\\t\\t\\t\\tmethod: \\\"tron_sendRawTransaction\\\",\\n\\t\\t\\t\\t\\tparams: { transaction: tx }\\n\\t\\t\\t\\t}),\\n\\t\\t\\t\\tgetBlockByNumber: async (n) => n === 0 || n === \\\"0\\\" ? Promise.resolve({ blockID: genesis }) : Promise.reject(new ProviderRpcError$1(4200, \\\"tronWeb.trx.getBlockByNumber is not supported by this wallet\\\"))\\n\\t\\t\\t}),\\n\\t\\t\\ttransactionBuilder: refuse(\\\"transactionBuilder\\\"),\\n\\t\\t\\taddress: refuse(\\\"address\\\"),\\n\\t\\t\\tutils: refuse(\\\"utils\\\"),\\n\\t\\t\\tevent: refuse(\\\"event\\\"),\\n\\t\\t\\tplugin: refuse(\\\"plugin\\\")\\n\\t\\t});\\n\\t\\tconst tronGlobal = Object.freeze({\\n\\t\\t\\trequest: async (args) => request(\\\"tron\\\", args),\\n\\t\\t\\ton,\\n\\t\\t\\tremoveListener,\\n\\t\\t\\tget tronWeb() {\\n\\t\\t\\t\\treturn connected() ? tronWeb : false;\\n\\t\\t\\t}\\n\\t\\t});\\n\\t\\tconst tronLink = Object.freeze({\\n\\t\\t\\tget ready() {\\n\\t\\t\\t\\treturn connected();\\n\\t\\t\\t},\\n\\t\\t\\trequest: async (args) => request(\\\"tron\\\", args),\\n\\t\\t\\ttronWeb\\n\\t\\t});\\n\\t\\t/**\\n\\t\\t* A new host state: the first connected state is a `connect`, then\\n\\t\\t* `accountsChanged`/`addressChanged` track the address and `chainChanged` the network.\\n\\t\\t*/\\n\\t\\tconst apply = (state) => {\\n\\t\\t\\tconst nextAddress = isRecord$1(state.address) && typeof state.address.base58 === \\\"string\\\" && typeof state.address.hex === \\\"string\\\" ? {\\n\\t\\t\\t\\tbase58: state.address.base58,\\n\\t\\t\\t\\thex: state.address.hex\\n\\t\\t\\t} : false;\\n\\t\\t\\tconst was = address;\\n\\t\\t\\tconst wasChain = chainId;\\n\\t\\t\\taddress = nextAddress;\\n\\t\\t\\tchainId = typeof state.chainId === \\\"string\\\" ? state.chainId : chainId;\\n\\t\\t\\tgenesis = typeof state.genesis === \\\"string\\\" ? state.genesis : genesis;\\n\\t\\t\\tif (was === false && nextAddress !== false) emit(\\\"connect\\\", { chainId });\\n\\t\\t\\tif ((was === false ? false : was.base58) !== (nextAddress === false ? false : nextAddress.base58)) {\\n\\t\\t\\t\\temit(\\\"accountsChanged\\\", nextAddress === false ? [] : [nextAddress.base58]);\\n\\t\\t\\t\\temit(\\\"addressChanged\\\", nextAddress === false ? {\\n\\t\\t\\t\\t\\tbase58: false,\\n\\t\\t\\t\\t\\thex: false\\n\\t\\t\\t\\t} : { ...nextAddress });\\n\\t\\t\\t}\\n\\t\\t\\tif (wasChain !== chainId) emit(\\\"chainChanged\\\", { chainId });\\n\\t\\t};\\n\\t\\t(async () => {\\n\\t\\t\\ttry {\\n\\t\\t\\t\\tconst state = await request(\\\"tron\\\", { method: \\\"tron_getProviderState\\\" });\\n\\t\\t\\t\\tif (isProviderState(state)) apply(state);\\n\\t\\t\\t} catch {}\\n\\t\\t})();\\n\\t\\ton(\\\"tron\\\", (state) => {\\n\\t\\t\\tif (isProviderState(state)) apply(state);\\n\\t\\t});\\n\\t\\tObject.defineProperty(global, \\\"tron\\\", {\\n\\t\\t\\tvalue: tronGlobal,\\n\\t\\t\\twritable: false,\\n\\t\\t\\tconfigurable: false\\n\\t\\t});\\n\\t\\tObject.defineProperty(global, \\\"tronLink\\\", {\\n\\t\\t\\tvalue: tronLink,\\n\\t\\t\\twritable: false,\\n\\t\\t\\tconfigurable: false\\n\\t\\t});\\n\\t\\tObject.defineProperty(global, \\\"tronWeb\\\", {\\n\\t\\t\\tvalue: tronWeb,\\n\\t\\t\\twritable: false,\\n\\t\\t\\tconfigurable: false\\n\\t\\t});\\n\\t\\tconst detail = Object.freeze({\\n\\t\\t\\tinfo: Object.freeze({\\n\\t\\t\\t\\t...info,\\n\\t\\t\\t\\tuuid: doc\\n\\t\\t\\t}),\\n\\t\\t\\tprovider: tronGlobal\\n\\t\\t});\\n\\t\\tconst announce = () => {\\n\\t\\t\\tglobal.dispatchEvent(new global.CustomEvent(\\\"TIP6963:announceProvider\\\", { detail }));\\n\\t\\t};\\n\\t\\tannounce();\\n\\t\\tglobal.addEventListener(\\\"TIP6963:requestProvider\\\", announce);\\n\\t}\\n\\t// packages/wallet-engine/src/connect/inject/provider.ts\\n\\tvar bytesToHex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, \\\"0\\\")).join(\\\"\\\");\\n\\tvar hexToBytes = (hex) => {\\n\\t\\tconst out = new Uint8Array(hex.length / 2);\\n\\t\\tfor (let i = 0; i < out.length; i += 1) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\\n\\t\\treturn out;\\n\\t};\\n\\tvar bytesReplacer = (_key, value) => value instanceof Uint8Array ? { __bytes: bytesToHex(value) } : value;\\n\\tvar isBytesEnvelope = (v) => typeof v === \\\"object\\\" && v !== null && typeof v.__bytes === \\\"string\\\";\\n\\tvar bytesReviver = (_key, value) => isBytesEnvelope(value) ? hexToBytes(value.__bytes) : value;\\n\\tvar isWalletIcon = (value) => /^data:image\\\\/(?:svg\\\\+xml|webp|png|gif);base64,/.test(value);\\n\\tvar page = globalThis;\\n\\tvar EVENT_ANNOUNCE = \\\"eip6963:announceProvider\\\";\\n\\tvar EVENT_REQUEST = \\\"eip6963:requestProvider\\\";\\n\\t/** EIP-1193 `ProviderRpcError`. */\\n\\tvar ProviderRpcError = class extends Error {\\n\\t\\tname = \\\"ProviderRpcError\\\";\\n\\t\\tcode;\\n\\t\\tconstructor(code, message) {\\n\\t\\t\\tsuper(message);\\n\\t\\t\\tthis.code = code;\\n\\t\\t}\\n\\t};\\n\\tvar isRecord = (value) => typeof value === \\\"object\\\" && value !== null && !Array.isArray(value);\\n\\t/** The host's `{ code, message }` as a ProviderRpcError; anything else is an internal error. */\\n\\tvar errorOf = (value) => isRecord(value) && typeof value[\\\"code\\\"] === \\\"number\\\" && typeof value[\\\"message\\\"] === \\\"string\\\" ? new ProviderRpcError(value[\\\"code\\\"], value[\\\"message\\\"]) : new ProviderRpcError(-32603, \\\"internal error\\\");\\n\\t/** The wire shape of Bitcoin sign inputs: accounts travel as their addresses. */\\n\\tvar btcInputs = (inputs) => inputs.map((input) => ({\\n\\t\\tpsbt: input.psbt,\\n\\t\\tchain: input.chain,\\n\\t\\tinputsToSign: input.inputsToSign.map((item) => ({\\n\\t\\t\\taddress: item.account.address,\\n\\t\\t\\tsigningIndexes: item.signingIndexes,\\n\\t\\t\\tsigHash: item.sigHash\\n\\t\\t}))\\n\\t}));\\n\\tvar unsupported = async () => {\\n\\t\\tawait Promise.resolve();\\n\\t\\tthrow new Error(\\\"NotSupported\\\");\\n\\t};\\n\\t/**\\n\\t* Installs `window.ethereum` (EIP-1193) and the EIP-6963 announcer for `info` in the top-level\\n\\t* document; subframes get nothing. `id` increments per request; the pending map settles on the\\n\\t* host's reply.\\n\\t*/\\n\\tfunction install(info) {\\n\\t\\tif (page.top !== page.self) return;\\n\\t\\tconst docBytes = /* @__PURE__ */ new Uint8Array(16);\\n\\t\\tcrypto.getRandomValues(docBytes);\\n\\t\\tdocBytes[6] = (docBytes[6] ?? 0) & 15 | 64;\\n\\t\\tdocBytes[8] = (docBytes[8] ?? 0) & 63 | 128;\\n\\t\\tconst docHex = bytesToHex(docBytes);\\n\\t\\tconst doc = `${docHex.slice(0, 8)}-${docHex.slice(8, 12)}-${docHex.slice(12, 16)}-${docHex.slice(16, 20)}-${docHex.slice(20)}`;\\n\\t\\tlet nextId = 1;\\n\\t\\tconst pending = /* @__PURE__ */ new Map();\\n\\t\\tconst listeners = /* @__PURE__ */ new Map();\\n\\t\\tconst emit = (name, payload) => {\\n\\t\\t\\tfor (const listener of listeners.get(name) ?? []) try {\\n\\t\\t\\t\\tlistener(payload);\\n\\t\\t\\t} catch {}\\n\\t\\t};\\n\\t\\tconst request = async (provider, args) => {\\n\\t\\t\\tif (!isRecord(args) || typeof args.method !== \\\"string\\\" || args.method.length === 0) throw new ProviderRpcError(-32602, \\\"request({ method, params? }) requires a method string\\\");\\n\\t\\t\\tconst id = nextId;\\n\\t\\t\\tnextId += 1;\\n\\t\\t\\tconst reply = new Promise((resolve, reject) => {\\n\\t\\t\\t\\tpending.set(id, {\\n\\t\\t\\t\\t\\tresolve,\\n\\t\\t\\t\\t\\treject\\n\\t\\t\\t\\t});\\n\\t\\t\\t});\\n\\t\\t\\tpage.ReactNativeWebView?.postMessage(JSON.stringify({\\n\\t\\t\\t\\tqntx: 1,\\n\\t\\t\\t\\tdoc,\\n\\t\\t\\t\\tprovider,\\n\\t\\t\\t\\tid,\\n\\t\\t\\t\\tmethod: args.method,\\n\\t\\t\\t\\tparams: args.params\\n\\t\\t\\t}, bytesReplacer));\\n\\t\\t\\treturn reply;\\n\\t\\t};\\n\\t\\tconst on = (name, listener) => {\\n\\t\\t\\tconst set = listeners.get(name) ?? /* @__PURE__ */ new Set();\\n\\t\\t\\tset.add(listener);\\n\\t\\t\\tlisteners.set(name, set);\\n\\t\\t};\\n\\t\\tconst removeListener = (name, listener) => {\\n\\t\\t\\tlisteners.get(name)?.delete(listener);\\n\\t\\t};\\n\\t\\tconst provider = Object.freeze({\\n\\t\\t\\trequest: async (args) => {\\n\\t\\t\\t\\treturn await request(\\\"eip1193\\\", args);\\n\\t\\t\\t},\\n\\t\\t\\ton,\\n\\t\\t\\tremoveListener\\n\\t\\t});\\n\\t\\tconst nostr = Object.freeze({\\n\\t\\t\\tgetPublicKey: async () => {\\n\\t\\t\\t\\treturn await request(\\\"nostr\\\", { method: \\\"getPublicKey\\\" });\\n\\t\\t\\t},\\n\\t\\t\\tsignEvent: async (event) => {\\n\\t\\t\\t\\treturn await request(\\\"nostr\\\", {\\n\\t\\t\\t\\t\\tmethod: \\\"signEvent\\\",\\n\\t\\t\\t\\t\\tparams: [event]\\n\\t\\t\\t\\t});\\n\\t\\t\\t},\\n\\t\\t\\tnip04: Object.freeze({\\n\\t\\t\\t\\tencrypt: async (pubkey, plaintext) => {\\n\\t\\t\\t\\t\\treturn await request(\\\"nostr\\\", {\\n\\t\\t\\t\\t\\t\\tmethod: \\\"nip04.encrypt\\\",\\n\\t\\t\\t\\t\\t\\tparams: [pubkey, plaintext]\\n\\t\\t\\t\\t\\t});\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tdecrypt: async (pubkey, ciphertext) => {\\n\\t\\t\\t\\t\\treturn await request(\\\"nostr\\\", {\\n\\t\\t\\t\\t\\t\\tmethod: \\\"nip04.decrypt\\\",\\n\\t\\t\\t\\t\\t\\tparams: [pubkey, ciphertext]\\n\\t\\t\\t\\t\\t});\\n\\t\\t\\t\\t}\\n\\t\\t\\t}),\\n\\t\\t\\tnip44: Object.freeze({\\n\\t\\t\\t\\tencrypt: async (pubkey, plaintext) => {\\n\\t\\t\\t\\t\\treturn await request(\\\"nostr\\\", {\\n\\t\\t\\t\\t\\t\\tmethod: \\\"nip44.encrypt\\\",\\n\\t\\t\\t\\t\\t\\tparams: [pubkey, plaintext]\\n\\t\\t\\t\\t\\t});\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tdecrypt: async (pubkey, ciphertext) => {\\n\\t\\t\\t\\t\\treturn await request(\\\"nostr\\\", {\\n\\t\\t\\t\\t\\t\\tmethod: \\\"nip44.decrypt\\\",\\n\\t\\t\\t\\t\\t\\tparams: [pubkey, ciphertext]\\n\\t\\t\\t\\t\\t});\\n\\t\\t\\t\\t}\\n\\t\\t\\t})\\n\\t\\t});\\n\\t\\tconst webln = Object.freeze({\\n\\t\\t\\tenable: async () => {\\n\\t\\t\\t\\treturn await request(\\\"webln\\\", { method: \\\"enable\\\" });\\n\\t\\t\\t},\\n\\t\\t\\tgetInfo: async () => {\\n\\t\\t\\t\\treturn await request(\\\"webln\\\", { method: \\\"getInfo\\\" });\\n\\t\\t\\t},\\n\\t\\t\\tsendPayment: async (invoice) => {\\n\\t\\t\\t\\treturn await request(\\\"webln\\\", {\\n\\t\\t\\t\\t\\tmethod: \\\"sendPayment\\\",\\n\\t\\t\\t\\t\\tparams: invoice\\n\\t\\t\\t\\t});\\n\\t\\t\\t},\\n\\t\\t\\tmakeInvoice: async (args) => {\\n\\t\\t\\t\\treturn await request(\\\"webln\\\", {\\n\\t\\t\\t\\t\\tmethod: \\\"makeInvoice\\\",\\n\\t\\t\\t\\t\\tparams: args\\n\\t\\t\\t\\t});\\n\\t\\t\\t},\\n\\t\\t\\tlnurl: async (lnurl) => {\\n\\t\\t\\t\\treturn await request(\\\"webln\\\", {\\n\\t\\t\\t\\t\\tmethod: \\\"lnurl\\\",\\n\\t\\t\\t\\t\\tparams: lnurl\\n\\t\\t\\t\\t});\\n\\t\\t\\t},\\n\\t\\t\\tgetBalance: async () => {\\n\\t\\t\\t\\treturn await request(\\\"webln\\\", { method: \\\"getBalance\\\" });\\n\\t\\t\\t},\\n\\t\\t\\tkeysend: unsupported,\\n\\t\\t\\tsignMessage: unsupported,\\n\\t\\t\\tverifyMessage: unsupported,\\n\\t\\t\\trequest: unsupported\\n\\t\\t});\\n\\t\\tconst receive = (json) => {\\n\\t\\t\\tlet message;\\n\\t\\t\\ttry {\\n\\t\\t\\t\\tmessage = JSON.parse(json, bytesReviver);\\n\\t\\t\\t} catch {\\n\\t\\t\\t\\treturn;\\n\\t\\t\\t}\\n\\t\\t\\tif (!isRecord(message)) return;\\n\\t\\t\\tif (message[\\\"doc\\\"] !== void 0 && message[\\\"doc\\\"] !== doc) return;\\n\\t\\t\\tconst { id, event } = message;\\n\\t\\t\\tif (typeof id === \\\"number\\\") {\\n\\t\\t\\t\\tconst settle = pending.get(id);\\n\\t\\t\\t\\tpending.delete(id);\\n\\t\\t\\t\\tif (settle !== void 0) {\\n\\t\\t\\t\\t\\tif (\\\"error\\\" in message) settle.reject(errorOf(message[\\\"error\\\"]));\\n\\t\\t\\t\\t\\telse settle.resolve(message[\\\"result\\\"]);\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\treturn;\\n\\t\\t\\t}\\n\\t\\t\\tif (typeof event === \\\"string\\\") emit(event, message[\\\"data\\\"]);\\n\\t\\t};\\n\\t\\tObject.defineProperty(globalThis, \\\"__qntxReceive\\\", {\\n\\t\\t\\tvalue: receive,\\n\\t\\t\\twritable: false,\\n\\t\\t\\tconfigurable: false\\n\\t\\t});\\n\\t\\tObject.defineProperty(globalThis, \\\"ethereum\\\", {\\n\\t\\t\\tvalue: provider,\\n\\t\\t\\twritable: false,\\n\\t\\t\\tconfigurable: false\\n\\t\\t});\\n\\t\\tObject.defineProperty(globalThis, \\\"nostr\\\", {\\n\\t\\t\\tvalue: nostr,\\n\\t\\t\\twritable: false,\\n\\t\\t\\tconfigurable: false\\n\\t\\t});\\n\\t\\tObject.defineProperty(globalThis, \\\"webln\\\", {\\n\\t\\t\\tvalue: webln,\\n\\t\\t\\twritable: false,\\n\\t\\t\\tconfigurable: false\\n\\t\\t});\\n\\t\\tinstallTron({\\n\\t\\t\\trequest,\\n\\t\\t\\ton,\\n\\t\\t\\tremoveListener,\\n\\t\\t\\temit,\\n\\t\\t\\tdoc,\\n\\t\\t\\tinfo,\\n\\t\\t\\tglobal: page\\n\\t\\t});\\n\\t\\tconst wsAccounts = [];\\n\\t\\tconst setAccounts = (accounts) => {\\n\\t\\t\\twsAccounts.length = 0;\\n\\t\\t\\twsAccounts.push(...accounts);\\n\\t\\t};\\n\\t\\tconst signTransactions = async (method, inputs) => request(\\\"solana\\\", {\\n\\t\\t\\tmethod,\\n\\t\\t\\tparams: {\\n\\t\\t\\t\\ttransactions: inputs.map((input) => input.transaction),\\n\\t\\t\\t\\taccounts: inputs.map((input) => input.account.address),\\n\\t\\t\\t\\tchains: inputs.map((input) => input.chain)\\n\\t\\t\\t}\\n\\t\\t});\\n\\t\\tconst wsFeatures = {\\n\\t\\t\\t\\\"standard:connect\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\tconnect: async (input) => {\\n\\t\\t\\t\\t\\tconst result = await request(\\\"solana\\\", {\\n\\t\\t\\t\\t\\t\\tmethod: \\\"standard:connect\\\",\\n\\t\\t\\t\\t\\t\\tparams: input\\n\\t\\t\\t\\t\\t});\\n\\t\\t\\t\\t\\tsetAccounts(result.accounts);\\n\\t\\t\\t\\t\\treturn { accounts: [...wsAccounts] };\\n\\t\\t\\t\\t}\\n\\t\\t\\t},\\n\\t\\t\\t\\\"standard:disconnect\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\tdisconnect: async () => {\\n\\t\\t\\t\\t\\tawait request(\\\"solana\\\", { method: \\\"standard:disconnect\\\" });\\n\\t\\t\\t\\t\\tsetAccounts([]);\\n\\t\\t\\t\\t}\\n\\t\\t\\t},\\n\\t\\t\\t\\\"standard:events\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\ton: (event, cb) => {\\n\\t\\t\\t\\t\\tconst listener = (data) => {\\n\\t\\t\\t\\t\\t\\tconst d = data;\\n\\t\\t\\t\\t\\t\\tif (d.event === event) {\\n\\t\\t\\t\\t\\t\\t\\tsetAccounts(d.params?.accounts ?? []);\\n\\t\\t\\t\\t\\t\\t\\tcb({ accounts: [...wsAccounts] });\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t};\\n\\t\\t\\t\\t\\ton(\\\"standard:events\\\", listener);\\n\\t\\t\\t\\t\\treturn () => {\\n\\t\\t\\t\\t\\t\\tremoveListener(\\\"standard:events\\\", listener);\\n\\t\\t\\t\\t\\t};\\n\\t\\t\\t\\t}\\n\\t\\t\\t},\\n\\t\\t\\t\\\"solana:signTransaction\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\tsupportedTransactionVersions: [\\n\\t\\t\\t\\t\\t\\\"legacy\\\",\\n\\t\\t\\t\\t\\t0,\\n\\t\\t\\t\\t\\t1\\n\\t\\t\\t\\t],\\n\\t\\t\\t\\tsignTransaction: async (...inputs) => {\\n\\t\\t\\t\\t\\treturn (await signTransactions(\\\"solana:signTransaction\\\", inputs)).signedTransactions.map((signedTransaction) => ({ signedTransaction }));\\n\\t\\t\\t\\t}\\n\\t\\t\\t},\\n\\t\\t\\t\\\"solana:signAndSendTransaction\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\tsupportedTransactionVersions: [\\n\\t\\t\\t\\t\\t\\\"legacy\\\",\\n\\t\\t\\t\\t\\t0,\\n\\t\\t\\t\\t\\t1\\n\\t\\t\\t\\t],\\n\\t\\t\\t\\tsignAndSendTransaction: async (...inputs) => {\\n\\t\\t\\t\\t\\treturn (await signTransactions(\\\"solana:signAndSendTransaction\\\", inputs)).signatures.map((signature) => ({ signature }));\\n\\t\\t\\t\\t}\\n\\t\\t\\t},\\n\\t\\t\\t\\\"solana:signMessage\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\tsignMessage: async (...inputs) => {\\n\\t\\t\\t\\t\\tif (inputs.length !== 1 || inputs[0] === void 0) throw new Error(\\\"solana:signMessage accepts one input at a time\\\");\\n\\t\\t\\t\\t\\tconst [input] = inputs;\\n\\t\\t\\t\\t\\tconst result = await request(\\\"solana\\\", {\\n\\t\\t\\t\\t\\t\\tmethod: \\\"solana:signMessage\\\",\\n\\t\\t\\t\\t\\t\\tparams: {\\n\\t\\t\\t\\t\\t\\t\\tmessage: input.message,\\n\\t\\t\\t\\t\\t\\t\\taccounts: [input.account.address]\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t});\\n\\t\\t\\t\\t\\treturn [{\\n\\t\\t\\t\\t\\t\\tsignedMessage: result.signedMessage,\\n\\t\\t\\t\\t\\t\\tsignature: result.signature,\\n\\t\\t\\t\\t\\t\\tsignatureType: \\\"ed25519\\\"\\n\\t\\t\\t\\t\\t}];\\n\\t\\t\\t\\t}\\n\\t\\t\\t},\\n\\t\\t\\t\\\"solana:signIn\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\tsignIn: async (...inputs) => {\\n\\t\\t\\t\\t\\tif (inputs.length > 1) throw new Error(\\\"solana:signIn accepts one input at a time\\\");\\n\\t\\t\\t\\t\\treturn await request(\\\"solana\\\", {\\n\\t\\t\\t\\t\\t\\tmethod: \\\"solana:signIn\\\",\\n\\t\\t\\t\\t\\t\\tparams: { input: inputs[0] ?? {} }\\n\\t\\t\\t\\t\\t});\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t};\\n\\t\\tif (!isWalletIcon(info.icon)) throw new Error(\\\"the provider icon is not a data URI image\\\");\\n\\t\\tregisterWallet(Object.freeze({\\n\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\tname: info.name,\\n\\t\\t\\ticon: info.icon,\\n\\t\\t\\tchains: Object.freeze([\\\"solana:mainnet\\\", \\\"solana:devnet\\\"]),\\n\\t\\t\\tfeatures: Object.freeze(wsFeatures),\\n\\t\\t\\tget accounts() {\\n\\t\\t\\t\\treturn wsAccounts;\\n\\t\\t\\t}\\n\\t\\t}));\\n\\t\\tconst btcAccounts = [];\\n\\t\\tconst setBtcAccounts = (accounts) => {\\n\\t\\t\\tbtcAccounts.length = 0;\\n\\t\\t\\tbtcAccounts.push(...accounts);\\n\\t\\t};\\n\\t\\tconst btcDisconnect = async () => {\\n\\t\\t\\tawait request(\\\"bitcoin\\\", { method: \\\"standard:disconnect\\\" });\\n\\t\\t\\tsetBtcAccounts([]);\\n\\t\\t};\\n\\t\\tconst btcFeatures = {\\n\\t\\t\\t\\\"standard:disconnect\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\tdisconnect: btcDisconnect\\n\\t\\t\\t},\\n\\t\\t\\t\\\"bitcoin:connect\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\tconnect: async (input) => {\\n\\t\\t\\t\\t\\tconst result = await request(\\\"bitcoin\\\", {\\n\\t\\t\\t\\t\\t\\tmethod: \\\"bitcoin:connect\\\",\\n\\t\\t\\t\\t\\t\\tparams: input\\n\\t\\t\\t\\t\\t});\\n\\t\\t\\t\\t\\tsetBtcAccounts(result.accounts);\\n\\t\\t\\t\\t\\treturn { accounts: [...btcAccounts] };\\n\\t\\t\\t\\t}\\n\\t\\t\\t},\\n\\t\\t\\t\\\"bitcoin:disconnect\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\tdisconnect: btcDisconnect\\n\\t\\t\\t},\\n\\t\\t\\t\\\"bitcoin:events\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\ton: (event, cb) => {\\n\\t\\t\\t\\t\\tconst listener = (data) => {\\n\\t\\t\\t\\t\\t\\tconst d = data;\\n\\t\\t\\t\\t\\t\\tif (d.event === event) {\\n\\t\\t\\t\\t\\t\\t\\tsetBtcAccounts(d.params?.accounts ?? []);\\n\\t\\t\\t\\t\\t\\t\\tcb({ accounts: [...btcAccounts] });\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t};\\n\\t\\t\\t\\t\\ton(\\\"bitcoin:events\\\", listener);\\n\\t\\t\\t\\t\\treturn () => {\\n\\t\\t\\t\\t\\t\\tremoveListener(\\\"bitcoin:events\\\", listener);\\n\\t\\t\\t\\t\\t};\\n\\t\\t\\t\\t}\\n\\t\\t\\t},\\n\\t\\t\\t\\\"bitcoin:signMessage\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\tsignMessage: async (...inputs) => {\\n\\t\\t\\t\\t\\tif (inputs.length !== 1 || inputs[0] === void 0) throw new Error(\\\"bitcoin:signMessage accepts one input at a time\\\");\\n\\t\\t\\t\\t\\tconst [input] = inputs;\\n\\t\\t\\t\\t\\tconst result = await request(\\\"bitcoin\\\", {\\n\\t\\t\\t\\t\\t\\tmethod: \\\"bitcoin:signMessage\\\",\\n\\t\\t\\t\\t\\t\\tparams: {\\n\\t\\t\\t\\t\\t\\t\\taccount: input.account.address,\\n\\t\\t\\t\\t\\t\\t\\tmessage: input.message\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t});\\n\\t\\t\\t\\t\\treturn [{\\n\\t\\t\\t\\t\\t\\tsignedMessage: result.signedMessage,\\n\\t\\t\\t\\t\\t\\tsignature: result.signature\\n\\t\\t\\t\\t\\t}];\\n\\t\\t\\t\\t}\\n\\t\\t\\t},\\n\\t\\t\\t\\\"bitcoin:signTransaction\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\tsignTransaction: async (...inputs) => {\\n\\t\\t\\t\\t\\treturn await request(\\\"bitcoin\\\", {\\n\\t\\t\\t\\t\\t\\tmethod: \\\"bitcoin:signTransaction\\\",\\n\\t\\t\\t\\t\\t\\tparams: { inputs: btcInputs(inputs) }\\n\\t\\t\\t\\t\\t});\\n\\t\\t\\t\\t}\\n\\t\\t\\t},\\n\\t\\t\\t\\\"bitcoin:signAndSendTransaction\\\": {\\n\\t\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\t\\tsignAndSendTransaction: async (...inputs) => {\\n\\t\\t\\t\\t\\treturn await request(\\\"bitcoin\\\", {\\n\\t\\t\\t\\t\\t\\tmethod: \\\"bitcoin:signAndSendTransaction\\\",\\n\\t\\t\\t\\t\\t\\tparams: { inputs: btcInputs(inputs) }\\n\\t\\t\\t\\t\\t});\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t};\\n\\t\\tregisterWallet(Object.freeze({\\n\\t\\t\\tversion: \\\"1.0.0\\\",\\n\\t\\t\\tname: info.name,\\n\\t\\t\\ticon: info.icon,\\n\\t\\t\\tchains: Object.freeze([\\\"bitcoin:mainnet\\\", \\\"bitcoin:testnet\\\"]),\\n\\t\\t\\tfeatures: Object.freeze(btcFeatures),\\n\\t\\t\\tget accounts() {\\n\\t\\t\\t\\treturn btcAccounts;\\n\\t\\t\\t}\\n\\t\\t}));\\n\\t\\tconst detail = Object.freeze({\\n\\t\\t\\tinfo: Object.freeze({\\n\\t\\t\\t\\t...info,\\n\\t\\t\\t\\tuuid: doc\\n\\t\\t\\t}),\\n\\t\\t\\tprovider\\n\\t\\t});\\n\\t\\tconst announce = () => {\\n\\t\\t\\tglobalThis.dispatchEvent(new CustomEvent(EVENT_ANNOUNCE, { detail }));\\n\\t\\t};\\n\\t\\tannounce();\\n\\t\\tglobalThis.addEventListener(EVENT_REQUEST, announce);\\n\\t}\\n\\texports.install = install;\\n\\treturn exports;\\n})({});\\n\";\n","/**\n * `@qntx/wallet-engine/connect` — the in-app-browser provider injection and message bridge.\n * Platform-neutral: the injected script is a plain string the host runs in the WebView; the bridge\n * lives in the main runtime and speaks `postMessage`/`injectJavaScript` through the host's `inject`\n * hook. No WebView or DOM types cross this boundary.\n */\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\n\nimport type { BitcoinEvent, BitcoinHandler } from \"./bitcoin.ts\";\nimport type { ConnectionController } from \"./controller.ts\";\nimport type { Eip1193Event, Eip1193Handler } from \"./eip1193.ts\";\nimport { ProviderError } from \"./errors.ts\";\nimport { PROVIDER_SCRIPT } from \"./inject.generated.ts\";\nimport type { Nip07Handler } from \"./nip07.ts\";\nimport type { SolanaEvent, SolanaHandler } from \"./solana.ts\";\nimport type { TronEvent, TronHandler } from \"./tron.ts\";\nimport type { WeblnHandler } from \"./webln.ts\";\n\nexport type { ConnectionController, ConnectionSession } from \"./controller.ts\";\nexport type { Eip1193Handler, Eip1193Request, Eip1193Event } from \"./eip1193.ts\";\nexport type { Nip07Request } from \"./nip07.ts\";\nexport type { WeblnRequest } from \"./webln.ts\";\nexport type { SolanaRequest, SolanaEvent, SolanaWalletAccount } from \"./solana.ts\";\nexport { SolanaWalletHandler, SOLANA_CHAIN_IDS } from \"./solana.ts\";\nexport type { TronRequest, TronEvent, TronProviderState, TronProviderAddress } from \"./tron.ts\";\nexport { TronWalletHandler } from \"./tron.ts\";\nexport type { BitcoinRequest, BitcoinEvent, BitcoinWalletAccount } from \"./bitcoin.ts\";\nexport { BitcoinWalletHandler, BITCOIN_CHAIN_IDS } from \"./bitcoin.ts\";\nexport { WeblnHandler } from \"./webln.ts\";\nexport { Nip07Handler } from \"./nip07.ts\";\nexport type { NostrPolicy } from \"./controller.ts\";\nexport { ProviderError } from \"./errors.ts\";\n\n/** The EIP-6963 provider identity the host stamps into the injected script. */\nexport type ProviderInfo = {\n /** 1–64 characters. */\n readonly name: string;\n /** `data:image/(png|svg+xml|webp);base64,…`, ≤ 64 KiB of base64. */\n readonly icon: string;\n /** Lowercase reverse-DNS, e.g. `xyz.meowl`. */\n readonly rdns: string;\n};\n\nconst UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;\nconst ICON_PREFIX = /^data:image\\/(png|svg\\+xml|webp);base64,/;\nconst BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;\nconst RDNS_LABEL = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;\nconst MAX_ICON_B64 = 64 * 1024;\n\nconst bad = (message: string): Error => new Error(`ProviderInfo: ${message}`);\n\nfunction checkInfo(info: ProviderInfo): void {\n if (typeof info !== \"object\" || info === null) {\n throw bad(\"not an object\");\n }\n if (typeof info.name !== \"string\" || info.name.length === 0 || info.name.length > 64) {\n throw bad(\"name must be 1–64 characters\");\n }\n const iconMatch = ICON_PREFIX.exec(info.icon);\n if (iconMatch === null) {\n throw bad(\"icon is not a png/svg+xml/webp data URL\");\n }\n const base64 = info.icon.slice(iconMatch[0].length);\n if (base64.length > MAX_ICON_B64 || !BASE64.test(base64)) {\n throw bad(\"icon base64 is empty or over 64 KiB\");\n }\n if (\n typeof info.rdns !== \"string\" ||\n info.rdns.length === 0 ||\n !info.rdns.split(\".\").every((label) => RDNS_LABEL.test(label)) ||\n info.rdns.split(\".\").length < 2\n ) {\n throw bad(\"rdns is not lowercase reverse-DNS labels\");\n }\n}\n\n/**\n * The script the host injects into the page: the fixed provider body plus one\n * `qntxProvider.install` call carrying `info` — the script itself generates the EIP-6963 uuid per\n * document. `info` is strictly validated — an invalid field throws before the script is produced,\n * so a misconfigured host fails before anything reaches the page.\n */\nexport function injectedScript(info: ProviderInfo): string {\n checkInfo(info);\n return `${PROVIDER_SCRIPT}\\nqntxProvider.install(${JSON.stringify(info)});`;\n}\n\n/** SHA-256 (hex) of the fixed provider script — no install call — for the CI freshness check. */\nexport const PROVIDER_SCRIPT_SHA256: string = bytesToHex(sha256(utf8ToBytes(PROVIDER_SCRIPT)));\n\n/** The bridge the host's WebView message handler calls. */\nexport type BrowserBridge = {\n /**\n * `onMessage`: `topUrl` is the WebView's `nativeEvent.url` and `data` is `nativeEvent.data`. A\n * message is accepted only when `topUrl`'s origin is the current top-level origin, so `topUrl`\n * must be the URL of the frame that SENT the message, never the top-level URL: otherwise any\n * frame inside a connected dApp could act under the dApp's origin. react-native-webview reports\n * the sending frame from 13.13.5: on iOS the message's `frameInfo`, on Android the\n * `WebMessageListener` source origin. Its Android fallback for a system WebView without\n * `WEB_MESSAGE_LISTENER` (`addJavascriptInterface`) reaches every frame and reports the top-level\n * URL; the in-app browser is not safe on such a WebView.\n */\n readonly message: (topUrl: string, data: string) => void;\n /** Top-level navigation completed: an origin change voids the old origin's pending work. */\n readonly navigated: (topUrl: string) => void;\n readonly dispose: () => void;\n};\n\nexport type BrowserBridgeOptions = {\n readonly eip1193: Pick<Eip1193Handler, \"handle\" | \"subscribe\">;\n readonly nip07: Pick<Nip07Handler, \"handle\">;\n readonly webln: Pick<WeblnHandler, \"handle\">;\n readonly solana: Pick<SolanaHandler, \"handle\" | \"subscribe\">;\n readonly bitcoin: Pick<BitcoinHandler, \"handle\" | \"subscribe\">;\n readonly tron: Pick<TronHandler, \"handle\" | \"subscribe\">;\n readonly connections: Pick<ConnectionController, \"checkOrigin\" | \"invalidateOrigin\">;\n /** The host's `webview.injectJavaScript`. */\n readonly inject: (script: string) => void;\n readonly now: () => number;\n};\n\n/** The largest JSON message a transport accepts — the WalletConnect entry applies the same limit. */\nexport const MAX_MESSAGE_BYTES = 128 * 1024;\nconst RATE_LIMIT_PER_MINUTE = 120;\nconst RATE_WINDOW_MS = 60_000;\nconst DISCONNECT = { code: 4900, message: \"disconnected\" };\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\n/** `Uint8Array` carries over the JSON wire as `{ __bytes: hex }`; the injected reviver restores it. */\nconst bytesReplacer = (_key: string, value: unknown): unknown =>\n value instanceof Uint8Array ? { __bytes: bytesToHex(value) } : value;\n\n/** The EIP-1193 listener payload of an engine event. */\nconst eventData = (event: Eip1193Event): unknown => {\n if (event.name === \"connect\") {\n return { chainId: event.chainId };\n }\n if (event.name === \"accountsChanged\") {\n return event.accounts;\n }\n return event.name === \"chainChanged\" ? event.chainId : DISCONNECT;\n};\n\n/** A provider error keeps its code and message; anything else is an opaque internal error. */\nconst errorData = (error: unknown): { code: number; message: string } =>\n error instanceof ProviderError\n ? { code: error.code, message: error.message }\n : { code: -32603, message: \"internal error\" };\n\nexport function createBrowserBridge(options: BrowserBridgeOptions): BrowserBridge {\n const { eip1193, nip07, webln, solana, bitcoin, tron, connections, inject, now } = options;\n let topOrigin: string | undefined;\n /** The current document's id; a same-origin reload's first message switches it. */\n let topDocument: string | undefined;\n let disposed = false;\n /** Per-origin request timestamps in the current window, for the 120/min cap. */\n const hits = new Map<string, number[]>();\n\n const originOf = (topUrl: string): string | undefined => {\n try {\n const { origin } = new URL(topUrl);\n connections.checkOrigin(origin);\n return origin;\n } catch {\n return undefined;\n }\n };\n\n const receive = (payload: unknown): void => {\n // __qntxReceive takes a JSON *string* (it parses it): embed the payload double-encoded, so the\n // injected script is `globalThis.__qntxReceive(\"<json>\")`, not an object argument. Uint8Array\n // fields (solana signatures/accounts) carry as `{ __bytes: hex }`; the injected reviver\n // restores them.\n inject(`globalThis.__qntxReceive(${JSON.stringify(JSON.stringify(payload, bytesReplacer))})`);\n };\n\n const rateLimited = (origin: string): boolean => {\n const window_ = now() - RATE_WINDOW_MS;\n const hitsFor = (hits.get(origin) ?? []).filter((at) => at > window_);\n hits.set(origin, hitsFor);\n if (hitsFor.length >= RATE_LIMIT_PER_MINUTE) {\n return true;\n }\n hitsFor.push(now());\n return false;\n };\n\n /** Events go to the current document; its id lets a stale page's listener ignore them. */\n const toPage = (payload: Record<string, unknown>): void => {\n receive(topDocument === undefined ? payload : { doc: topDocument, ...payload });\n };\n\n const unsubscribe = eip1193.subscribe((event) => {\n if (disposed || topOrigin === undefined || event.origin !== topOrigin) {\n return;\n }\n toPage({ event: event.name, data: eventData(event) });\n });\n const unsubscribeSolana = solana.subscribe((event: SolanaEvent) => {\n if (disposed || topOrigin === undefined || event.origin !== topOrigin) {\n return;\n }\n toPage({\n event: \"standard:events\",\n data: { event: \"change\", params: { accounts: event.accounts } },\n });\n });\n\n const unsubscribeBitcoin = bitcoin.subscribe((event: BitcoinEvent) => {\n if (disposed || topOrigin === undefined || event.origin !== topOrigin) {\n return;\n }\n toPage({\n event: \"bitcoin:events\",\n data: { event: \"change\", params: { accounts: event.accounts } },\n });\n });\n const unsubscribeTron = tron.subscribe((event: TronEvent) => {\n if (disposed || topOrigin === undefined || event.origin !== topOrigin) {\n return;\n }\n toPage({ event: \"tron\", data: event.state });\n });\n\n const message = (topUrl: string, data: string): void => {\n if (disposed || data.length > MAX_MESSAGE_BYTES) {\n return;\n }\n const origin = originOf(topUrl);\n if (origin === undefined || origin !== topOrigin) {\n return; // the page's top origin is the only source of truth; a foreign frame is dropped.\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch {\n return;\n }\n if (!isObject(parsed)) {\n return;\n }\n const { id, method, params, qntx, provider, doc } = parsed;\n if (\n qntx !== 1 ||\n typeof id !== \"number\" ||\n !Number.isSafeInteger(id) ||\n id < 0 ||\n typeof method !== \"string\" ||\n typeof doc !== \"string\" ||\n !UUID_V4.test(doc)\n ) {\n return;\n }\n // A document id the bridge has not seen is a new document of the same origin (a reload): the\n // previous document is gone, so its pending connection and pipeline requests are void.\n if (doc !== topDocument) {\n if (topDocument !== undefined) {\n connections.invalidateOrigin(origin);\n }\n topDocument = doc;\n }\n // `provider` selects the handler; an unknown or missing value is a malformed message.\n const handler =\n provider === \"eip1193\"\n ? eip1193\n : provider === \"nostr\"\n ? nip07\n : provider === \"webln\"\n ? webln\n : provider === \"solana\"\n ? solana\n : provider === \"bitcoin\"\n ? bitcoin\n : provider === \"tron\"\n ? tron\n : undefined;\n if (handler === undefined) {\n return;\n }\n if (rateLimited(origin)) {\n receive({ doc, id, error: DISCONNECT });\n return;\n }\n void (async (): Promise<void> => {\n try {\n const result = await handler.handle(\n origin,\n params === undefined ? { method } : { method, params },\n );\n if (!disposed && origin === topOrigin && doc === topDocument) {\n receive({ doc, id, result });\n }\n } catch (error: unknown) {\n if (!disposed && origin === topOrigin && doc === topDocument) {\n receive({ doc, id, error: errorData(error) });\n }\n }\n })();\n };\n\n const navigated = (topUrl: string): void => {\n if (disposed) {\n return;\n }\n // An unacceptable origin (http, about:blank, a malformed URL) is no origin: the old page is\n // still gone, its pending work is voided and its late replies are dropped.\n const next = originOf(topUrl);\n if (next !== topOrigin) {\n if (topOrigin !== undefined) {\n connections.invalidateOrigin(topOrigin);\n }\n topOrigin = next;\n topDocument = undefined;\n }\n };\n\n const dispose = (): void => {\n if (disposed) {\n return;\n }\n disposed = true;\n unsubscribe();\n unsubscribeSolana();\n unsubscribeBitcoin();\n unsubscribeTron();\n if (topOrigin !== undefined) {\n connections.invalidateOrigin(topOrigin);\n topOrigin = undefined;\n }\n };\n\n return { message, navigated, dispose };\n}\n"],"mappings":";;;;AACA,MAAa,kBAA0B;;;;;;;;AC2CvC,MAAM,UAAU;AAChB,MAAM,cAAc;AACpB,MAAM,SAAS;AACf,MAAM,aAAa;AACnB,MAAM,eAAe;AAErB,MAAM,OAAO,4BAA2B,IAAI,MAAM,iBAAiB,SAAS;AAE5E,SAAS,UAAU,MAA0B;CAC3C,IAAI,OAAO,SAAS,YAAY,SAAS,MACvC,MAAM,IAAI,eAAe;CAE3B,IAAI,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,WAAW,KAAK,KAAK,KAAK,SAAS,IAChF,MAAM,IAAI,8BAA8B;CAE1C,MAAM,YAAY,YAAY,KAAK,KAAK,IAAI;CAC5C,IAAI,cAAc,MAChB,MAAM,IAAI,yCAAyC;CAErD,MAAM,SAAS,KAAK,KAAK,MAAM,UAAU,EAAE,CAAC,MAAM;CAClD,IAAI,OAAO,SAAS,gBAAgB,CAAC,OAAO,KAAK,MAAM,GACrD,MAAM,IAAI,q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,WAAyB;EAC1C,IAAI,UACF;EAIF,MAAM,OAAO,SAAS,MAAM;EAC5B,IAAI,SAAS,WAAW;GACtB,IAAI,cAAc,KAAA,GAChB,YAAY,iBAAiB,SAAS;GAExC,YAAY;GACZ,cAAc,KAAA;EAChB;CACF;CAEA,MAAM,gBAAsB;EAC1B,IAAI,UACF;EAEF,WAAW;EACX,YAAY;EACZ,kBAAkB;EAClB,mBAAmB;EACnB,gBAAgB;EAChB,IAAI,cAAc,KAAA,GAAW;GAC3B,YAAY,iBAAiB,SAAS;GACtC,YAAY,KAAA;EACd;CACF;CAEA,OAAO;EAAE;EAAS;EAAW;CAAQ;AACvC"}
|
package/dist/connect.d.mts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { D as NostrPolicy, S as
|
|
1
|
+
import { C as BitcoinRequest, D as ConnectionController, P as NostrPolicy, S as BitcoinHandler, T as BitcoinWalletHandler, _ as Eip1193Event, a as TronProviderAddress, b as BITCOIN_CHAIN_IDS, c as TronWalletHandler, d as SolanaHandler, f as SolanaRequest, g as Nip07Request, h as Nip07Handler, i as TronHandler, j as ConnectionSession, l as SOLANA_CHAIN_IDS, m as SolanaWalletHandler, n as WeblnRequest, o as TronProviderState, p as SolanaWalletAccount, r as TronEvent, s as TronRequest, t as WeblnHandler, u as SolanaEvent, v as Eip1193Handler, w as BitcoinWalletAccount, x as BitcoinEvent, y as Eip1193Request } from "./webln-Bllk_xJ2.mjs";
|
|
2
|
+
import { t as ProviderError } from "./errors-B8W-hoYW.mjs";
|
|
2
3
|
/** The EIP-6963 provider identity the host stamps into the injected script. */
|
|
3
4
|
export type ProviderInfo = {
|
|
4
|
-
/** UUIDv4 — the host generates or fixes one per install. */
|
|
5
|
-
readonly uuid: string;
|
|
6
5
|
/** 1–64 characters. */
|
|
7
6
|
readonly name: string;
|
|
8
7
|
/** `data:image/(png|svg+xml|webp);base64,…`, ≤ 64 KiB of base64. */
|
|
@@ -12,9 +11,9 @@ export type ProviderInfo = {
|
|
|
12
11
|
};
|
|
13
12
|
/**
|
|
14
13
|
* The script the host injects into the page: the fixed provider body plus one
|
|
15
|
-
* `qntxProvider.install` call carrying `info
|
|
16
|
-
*
|
|
17
|
-
* page.
|
|
14
|
+
* `qntxProvider.install` call carrying `info` — the script itself generates the EIP-6963 uuid per
|
|
15
|
+
* document. `info` is strictly validated — an invalid field throws before the script is produced,
|
|
16
|
+
* so a misconfigured host fails before anything reaches the page.
|
|
18
17
|
*/
|
|
19
18
|
export declare function injectedScript(info: ProviderInfo): string;
|
|
20
19
|
/** SHA-256 (hex) of the fixed provider script — no install call — for the CI freshness check. */
|
|
@@ -22,8 +21,14 @@ export declare const PROVIDER_SCRIPT_SHA256: string;
|
|
|
22
21
|
/** The bridge the host's WebView message handler calls. */
|
|
23
22
|
export type BrowserBridge = {
|
|
24
23
|
/**
|
|
25
|
-
* `onMessage`: `topUrl` is the WebView's `nativeEvent.url`
|
|
26
|
-
*
|
|
24
|
+
* `onMessage`: `topUrl` is the WebView's `nativeEvent.url` and `data` is `nativeEvent.data`. A
|
|
25
|
+
* message is accepted only when `topUrl`'s origin is the current top-level origin, so `topUrl`
|
|
26
|
+
* must be the URL of the frame that SENT the message, never the top-level URL: otherwise any
|
|
27
|
+
* frame inside a connected dApp could act under the dApp's origin. react-native-webview reports
|
|
28
|
+
* the sending frame from 13.13.5: on iOS the message's `frameInfo`, on Android the
|
|
29
|
+
* `WebMessageListener` source origin. Its Android fallback for a system WebView without
|
|
30
|
+
* `WEB_MESSAGE_LISTENER` (`addJavascriptInterface`) reaches every frame and reports the top-level
|
|
31
|
+
* URL; the in-app browser is not safe on such a WebView.
|
|
27
32
|
*/
|
|
28
33
|
readonly message: (topUrl: string, data: string) => void;
|
|
29
34
|
/** Top-level navigation completed: an origin change voids the old origin's pending work. */
|
|
@@ -36,11 +41,14 @@ export type BrowserBridgeOptions = {
|
|
|
36
41
|
readonly webln: Pick<WeblnHandler, "handle">;
|
|
37
42
|
readonly solana: Pick<SolanaHandler, "handle" | "subscribe">;
|
|
38
43
|
readonly bitcoin: Pick<BitcoinHandler, "handle" | "subscribe">;
|
|
44
|
+
readonly tron: Pick<TronHandler, "handle" | "subscribe">;
|
|
39
45
|
readonly connections: Pick<ConnectionController, "checkOrigin" | "invalidateOrigin">;
|
|
40
46
|
/** The host's `webview.injectJavaScript`. */
|
|
41
47
|
readonly inject: (script: string) => void;
|
|
42
48
|
readonly now: () => number;
|
|
43
49
|
};
|
|
50
|
+
/** The largest JSON message a transport accepts — the WalletConnect entry applies the same limit. */
|
|
51
|
+
export declare const MAX_MESSAGE_BYTES: number;
|
|
44
52
|
export declare function createBrowserBridge(options: BrowserBridgeOptions): BrowserBridge;
|
|
45
|
-
export { BITCOIN_CHAIN_IDS, type BitcoinEvent, type BitcoinRequest, type BitcoinWalletAccount, BitcoinWalletHandler, type ConnectionController, type ConnectionSession, type Eip1193Event, type Eip1193Handler, type Eip1193Request, Nip07Handler, type Nip07Request, type NostrPolicy, ProviderError, SOLANA_CHAIN_IDS, type SolanaEvent, type SolanaRequest, type SolanaWalletAccount, SolanaWalletHandler, WeblnHandler, type WeblnRequest };
|
|
53
|
+
export { BITCOIN_CHAIN_IDS, type BitcoinEvent, type BitcoinRequest, type BitcoinWalletAccount, BitcoinWalletHandler, type ConnectionController, type ConnectionSession, type Eip1193Event, type Eip1193Handler, type Eip1193Request, Nip07Handler, type Nip07Request, type NostrPolicy, ProviderError, SOLANA_CHAIN_IDS, type SolanaEvent, type SolanaRequest, type SolanaWalletAccount, SolanaWalletHandler, type TronEvent, type TronProviderAddress, type TronProviderState, type TronRequest, TronWalletHandler, WeblnHandler, type WeblnRequest };
|
|
46
54
|
//# sourceMappingURL=connect.d.mts.map
|