From d79bbfe6686492c4bc800b2499267e622843379a Mon Sep 17 00:00:00 2001 From: Uncle Stretch Date: Thu, 5 Nov 2026 21:56:26 +0300 Subject: [PATCH] update extension to be compatible with PAPI Signed-off-by: Uncle Stretch --- package.json | 2 +- src/background/chains.ts | 24 +++ src/background/createBackgroundRpc.ts | 149 ++++++++++++++++-- src/background/index.ts | 4 +- src/background/keyring.ts | 12 +- src/background/keystore/types.ts | 1 + src/background/rpc/types.ts | 4 +- src/background/types.ts | 15 +- .../WalletPopup/hooks/useAccounts.tsx | 4 +- src/containers/WalletPopup/hooks/useChain.tsx | 42 ++--- src/inpage/index.ts | 9 +- src/inpage/pjsInject.ts | 61 ++++--- src/inpage/types.ts | 4 +- 13 files changed, 237 insertions(+), 94 deletions(-) create mode 100644 src/background/chains.ts diff --git a/package.json b/package.json index 7314ae8..824cd06 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ghost-wallet", - "version": "0.4.0", + "version": "0.4.1", "description": "Browser extension to manage ghost blockchain light clients.", "main": "dist/src/index.js", "author": "Uncle f4ts0 ", diff --git a/src/background/chains.ts b/src/background/chains.ts new file mode 100644 index 0000000..02d6dae --- /dev/null +++ b/src/background/chains.ts @@ -0,0 +1,24 @@ +import { networks } from "../constants" +import * as storage from "./storage" + +const CHAIN_KEY_PREIFX = "selected_chain_id" + +export const createChainStorage = () => { + const getActiveChainId = async (): Promise => { + let activeChainId = await storage.get(CHAIN_KEY_PREIFX) + if (!activeChainId) { + activeChainId = networks.at(0)?.chainId; + await setActiveChainId(activeChainId) + } + return activeChainId + } + + const setActiveChainId = async (activeChainId: String | undefined): Promise => { + await storage.set(CHAIN_KEY_PREIFX, activeChainId) + } + + return { + getActiveChainId, + setActiveChainId, + } +} diff --git a/src/background/createBackgroundRpc.ts b/src/background/createBackgroundRpc.ts index f8d12f7..814db3f 100644 --- a/src/background/createBackgroundRpc.ts +++ b/src/background/createBackgroundRpc.ts @@ -12,6 +12,7 @@ import { getPolkadotSigner } from "@polkadot-api/signer" import type { BackgroundRpcSpec } from "./types" import { createKeyring } from "./keyring" +import { createChainStorage } from "./chains" import { UserSignedExtensionName } from "../types/UserSignedExtension" import { createClient } from "@polkadot-api/substrate-client" import { getObservableClient } from "@polkadot-api/observable-client" @@ -37,6 +38,8 @@ const isUserSignedExtensionName = (s: string): s is UserSignedExtensionName => { } const keyring = createKeyring() +const chainStorage = createChainStorage() + const requestCooldowns = new Map() const COOLDOWN_MS = 3000 let nextSignRequestId = 0 @@ -44,15 +47,15 @@ let nextSignRequestId = 0 export const createBackgroundRpc = ( sendMessage: (message: RpcMessage) => void ) => { - const getAccounts: RpcMethodHandlers< + const getRootAccounts: RpcMethodHandlers< BackgroundRpcSpec, Context - >["getAccounts"] = async ([chainId], { lightClientPageHelper }) => { + >["getRootAccounts"] = async ([chainId], { lightClientPageHelper }) => { const chains = await lightClientPageHelper.getChains() const chain = chains.find(({ genesisHash }) => genesisHash === chainId) if (!chain) return [] - const accounts = await keyring.getAccounts(chainId) + const accounts = await keyring.getRootAccounts(chainId) const prefix = wellKnownPrefixByGenesisHash[chain.genesisHash] return accounts.map(acc => ({ @@ -113,6 +116,7 @@ export const createBackgroundRpc = ( const publicKey = derivation ? derivation.publicKey : activeAccount.publicKey return { + genesisHash: chainId, publicKey: publicKey, address: ss58Address( publicKey, @@ -121,21 +125,27 @@ export const createBackgroundRpc = ( } } - const notifyOnAccountsChanged = async (context: Context) => - context.notifyOnAccountsChanged( - ( - await Promise.all( - (await context.lightClientPageHelper.getChains()).map( - ({ genesisHash }) => getAccounts([genesisHash], context) - ), - ) - ).flatMap((accounts) => accounts), - ) + const getAccounts: RpcMethodHandlers< + BackgroundRpcSpec, + Context + >["getAccounts"] = async (_, context) => { + const activeChainId = await chainStorage.getActiveChainId() + const account = await getAccount([activeChainId as string], context) + return account ? [account] : [] + } + + const notifyOnAccountsChanged = async (context: Context) => { + const activeChainId = await chainStorage.getActiveChainId() + const accounts = await getRootAccounts([activeChainId as string], context) + const notifyAccounts = accounts.map(a => ({ ...a, type: "sr25519", genesisHash: a.chainId })) + context.notifyOnAccountsChanged(notifyAccounts) + } const handlers: RpcMethodHandlers = { getAccountDerivations, - getAccounts, + getRootAccounts, getAccount, + getAccounts, getActiveAccount, async createTx( [chainId, from, callData], @@ -149,7 +159,6 @@ export const createBackgroundRpc = ( if (now - lastApprovedRequestTime < COOLDOWN_MS) { throw new Error("wallet interaction is rate-limited") - } requestCooldowns.set(url, now) @@ -402,6 +411,107 @@ export const createBackgroundRpc = ( } } }, + async pjsSignRaw( + [payload], + { port, signRequests } + ) { + const url = port.sender?.url + if (!url) throw new Error("unknown url") + + const now = Date.now() + const lastApprovedRequestTime = requestCooldowns.get(url) || 0 + + if (now - lastApprovedRequestTime < COOLDOWN_MS) { + throw new Error("wallet interaction is rate-limited. Please wait 3 seconds.") + } + + requestCooldowns.set(url, now) + + const id = nextSignRequestId++ + const currentRequestId = id + + const signRequest = new Promise<{ password?: string }>((resolve, reject) => + (signRequests[id] = { + resolve, + reject, + url, + address: payload.address, + rawData: payload.data, + type: payload.type || "bytes" + } as any) + ) + + let windowId: number | undefined = undefined + + const createdWindow = await chrome.windows.create({ + focused: true, + height: 680, + width: 460, + type: "popup", + url: chrome.runtime.getURL(`ui/assets/wallet-popup.html#/sign-raw-request/${id}`), + }) + + windowId = createdWindow.id + const targetWindowId = createdWindow.id + + const removeWindow = () => { + if (windowId && windowId === targetWindowId) { + chrome.windows.remove(windowId).catch(() => {}) + windowId = undefined + } + } + + const onWindowsRemoved = (closedWindowId: number) => { + if (closedWindowId === windowId) { + if (signRequests[currentRequestId]) { + signRequests[currentRequestId].reject(new Error("user closed connection window")) + } + cleanUpWindowListeners(port) + windowId = undefined + } + } + + const cleanUpWindowListeners = (port: any) => { + port.onDisconnect.removeListener(removeWindow) + chrome.windows.onRemoved.removeListener(onWindowsRemoved) + } + + port.onDisconnect.addListener(removeWindow) + chrome.windows.onRemoved.addListener(onWindowsRemoved) + + try { + const { password } = await signRequest + cleanUpWindowListeners(port) + + if (!password) { + throw new Error("password verification is strictly required for this action") + } + + const activeChainId = await chainStorage.getActiveChainId() + let [keypair, scheme] = await keyring.getKeypairWithPassword(activeChainId as string, password) + + let messageBytes: Uint8Array + if (typeof payload.data === "string" && payload.data.startsWith("0x")) { + messageBytes = fromHex(payload.data) + } else { + messageBytes = new TextEncoder().encode(payload.data) + } + + const signature = keypair.sign(messageBytes); + + ;(keypair as any) = null; + + return toHex(signature) + } catch (err) { + cleanUpWindowListeners(port) + throw err + } finally { + delete signRequests[id] + if (windowId) { + chrome.windows.remove(windowId).catch(() => {}) + } + } + }, async getSignRequests(_, { signRequests }) { return signRequests }, @@ -444,6 +554,13 @@ export const createBackgroundRpc = ( await keyring.setActiveAccount(args) await notifyOnAccountsChanged(context) }, + async getActiveChainId(context) { + return await chainStorage.getActiveChainId() + }, + async setActiveChainId([chainId], context) { + await chainStorage.setActiveChainId(chainId) + await notifyOnAccountsChanged(context) + }, getChainSpecs: listChainSpecsHandler, } @@ -452,6 +569,8 @@ export const createBackgroundRpc = ( const ALLOWED_WEB_METHODS: Method[] = [ "createTx", "getAccount", + "getAccounts", + "pjsSignRaw", "pjsSignPayload", ] diff --git a/src/background/index.ts b/src/background/index.ts index d8e4da8..b7fc466 100644 --- a/src/background/index.ts +++ b/src/background/index.ts @@ -5,7 +5,7 @@ import { import { start } from "@substrate/light-client-extension-helpers/smoldot" import { createBackgroundRpc } from "./createBackgroundRpc" import * as storage from "./storage" -import type { Account } from "./types" +import type { PjsAccount } from "./types" import { startHeartbeat } from "./heartbeat" import { CHANNEL_ID } from "../constants" @@ -31,7 +31,7 @@ const signRequests = {} type BackgroundRpc = ReturnType const connectedRpcs: BackgroundRpc[] = [] -const notifyOnAccountsChanged = (accounts: Account[]) => +const notifyOnAccountsChanged = (accounts: PjsAccount[]) => connectedRpcs.forEach((rpc) => rpc.notify("onAccountsChanged", [accounts])) const subscribeOnAccountsChanged = (rpc: BackgroundRpc) => { diff --git a/src/background/keyring.ts b/src/background/keyring.ts index 6bfdbd8..c888231 100644 --- a/src/background/keyring.ts +++ b/src/background/keyring.ts @@ -35,7 +35,6 @@ import { import { assert } from "./utils" import * as storage from "./storage" import { toHex, fromHex } from "@polkadot-api/utils" -import { wellKnownChainIdByGenesisHash } from "../constants" const createDeriveFnMap: Record = { Sr25519: sr25519CreateDerive, @@ -99,7 +98,7 @@ export const createKeyring = () => { await storage.set(`${ACTIVE_ACCOUNT_PREFIX}_${args.chainId}`, args.activeAccount) } - const getAccounts = async (chainId: string): Promise => { + const getRootAccounts = async (chainId: string): Promise => { const keystoreStorage = await getKeystoreStorage() const accounts = keystoreStorage.keystores @@ -134,12 +133,7 @@ export const createKeyring = () => { const newVault = keystoreV4.create(args.password, encodeSecret(args.miniSecret)) const newKeystoreItem: KeystoreV4WithMeta = { - metadata: { - name: args.name, - scheme: args.scheme, - chainId: args.chainId, - publicKey: publicKeyHex, - }, + metadata: { ...args, publicKey: publicKeyHex }, vault: newVault, } @@ -387,7 +381,7 @@ export const createKeyring = () => { }, setActiveAccount, getActiveAccount, - getAccounts, + getRootAccounts, getAccountDerivations, insertAccount, diff --git a/src/background/keystore/types.ts b/src/background/keystore/types.ts index a6d7d4a..22f3b37 100644 --- a/src/background/keystore/types.ts +++ b/src/background/keystore/types.ts @@ -27,6 +27,7 @@ export type KeystoreMetaWithAddress = KeystoreMeta & { export type ExposedAccount = { publicKey: string, address: string, + genesisHash: string, } export type AccountTree = KeystoreMetaWithAddress & { diff --git a/src/background/rpc/types.ts b/src/background/rpc/types.ts index cf5c956..f7838ba 100644 --- a/src/background/rpc/types.ts +++ b/src/background/rpc/types.ts @@ -1,6 +1,6 @@ import type { LightClientPageHelper } from "@substrate/light-client-extension-helpers/background" import { UserSignedExtensions } from "../../types/UserSignedExtension" -import { Account, SignRequest } from "../types" +import { PjsAccount, SignRequest } from "../types" export type SignResponse = { userSignedExtensions: Partial @@ -16,5 +16,5 @@ export type Context = { lightClientPageHelper: LightClientPageHelper signRequests: Record port: chrome.runtime.Port - notifyOnAccountsChanged: (accounts: Account[]) => void + notifyOnAccountsChanged: (accounts: PjsAccount[]) => void } diff --git a/src/background/types.ts b/src/background/types.ts index 9d0662d..1b6cbe2 100644 --- a/src/background/types.ts +++ b/src/background/types.ts @@ -31,6 +31,13 @@ export type Account = { address: string } +export type PjsAccount = { + name?: string + genesisHash: string + address: string + type: string +} + export type KeystoreAccount = { publicKey: string, name: string, @@ -129,8 +136,10 @@ export namespace Pjs { } export type BackgroundRpcSpec = { + getAccounts(): Promise getAccount(chainId: string): Promise pjsSignPayload(payload: Pjs.SignerPayloadJSON): Promise + pjsSignRaw(payload: Pjs.SignerPayloadRaw): Promise createTx(chainId: string, from: string, callData: string): Promise // private methods getSignRequests(): Promise> @@ -143,7 +152,7 @@ export type BackgroundRpcSpec = { changePassword(args: ChangePasswordArgs): Promise revealSecretSeed(args: RevealSecretSeedArgs): Promise - getAccounts(chainId: string): Promise + getRootAccounts(chainId: string): Promise renameAccount(args: RenameAccountArgs): Promise setActiveAccount(args: ActiveAccountArgs): Promise getChainSpecs(): Promise @@ -157,4 +166,8 @@ export type BackgroundRpcSpec = { deriveAccount(args: DeriveAccountArgs): Promise removeAccount(args: RemoveAccountArgs): Promise extendKeystore(args: ExtendKeystoreArgs): Promise + + // chain specific + getActiveChainId(): Promise + setActiveChainId(chainId: String | undefined): Promise } diff --git a/src/containers/WalletPopup/hooks/useAccounts.tsx b/src/containers/WalletPopup/hooks/useAccounts.tsx index aa09b75..90cf621 100644 --- a/src/containers/WalletPopup/hooks/useAccounts.tsx +++ b/src/containers/WalletPopup/hooks/useAccounts.tsx @@ -85,8 +85,8 @@ export const AccountsProvider = ({ children }: { children?: ReactNode }) => { } const { data: accounts, mutate: accountsMutate, isLoading: isFetchingAccounts } = useSWR( - currentChain?.chainId ? ["rpc.getAccounts", currentChain.chainId] : null, - ([_, id]) => rpc.client.getAccounts(id), + currentChain?.chainId ? ["rpc.getRootAccounts", currentChain.chainId] : null, + ([_, id]) => rpc.client.getRootAccounts(id), { revalidateOnFocus: true, }, diff --git a/src/containers/WalletPopup/hooks/useChain.tsx b/src/containers/WalletPopup/hooks/useChain.tsx index 4d94330..6660826 100644 --- a/src/containers/WalletPopup/hooks/useChain.tsx +++ b/src/containers/WalletPopup/hooks/useChain.tsx @@ -1,9 +1,7 @@ import { ReactNode, createContext, useContext, useState, useEffect, useMemo } from "react" import useSWR from "swr" import { rpc } from "../api" - import { networks, NetworkType } from "@/constants" -import * as storage from "@/background/storage" type ChainContextType = { currentChain: NetworkType | undefined @@ -14,46 +12,24 @@ type ChainContextType = { const ChainContext = createContext({} as ChainContextType) -const STORAGE_CHAIN_KEY = "current_selected_chain_id" - export const ChainProvider = ({ children }: { children?: ReactNode }) => { const [isLoadingChain, setIsLoadingChain] = useState(true) - const [currentChainId, setCurrentChainIdState] = useState("") - useEffect(() => { - const loadSavedChain = async () => { - const stored = await storage.get(STORAGE_CHAIN_KEY) - const savedId = stored?.[STORAGE_CHAIN_KEY] - - if (savedId && networks.some(n => n.chainId === savedId)) { - setCurrentChainIdState(savedId) - } else { - const defaultChainId = networks[0].chainId - setCurrentChainIdState(defaultChainId) - await storage.set(STORAGE_CHAIN_KEY, defaultChainId) - } - - setIsLoadingChain(false) - } - - loadSavedChain() - }, []) + const { data: currentChainId, mutate: currentChainIdMutate } = useSWR( + "rpc.getActiveChainId", + () => rpc.client.getActiveChainId(), + { + revalidateOnFocus: true, + }, + ) const currentChain = useMemo(() => { return networks.find(n => n.chainId === currentChainId) }, [currentChainId]) const setCurrentChainId = async (id: string) => { - const chainExists = networks.some(n => n.chainId === id) - if (!chainExists) return - - setCurrentChainIdState(id) - - try { - await storage.set(STORAGE_CHAIN_KEY, id) - } catch (error) { - console.error("Failed to save chain change:", error) - } + await rpc.client.setActiveChainId(id) + await currentChainIdMutate() } const value: ChainContextType = { diff --git a/src/inpage/index.ts b/src/inpage/index.ts index 3ca6f16..c480803 100644 --- a/src/inpage/index.ts +++ b/src/inpage/index.ts @@ -9,7 +9,7 @@ import { SmoldotExtensionProviderDetail, } from "@substrate/smoldot-discovery-connector" -import type { Account, BackgroundRpcSpec } from "../background/types" +import type { PjsAccount, BackgroundRpcSpec } from "../background/types" import { CHANNEL_ID } from "../constants" import { pjsInject } from "./pjsInject" import type { InPageRpcSpec } from "./types" @@ -21,7 +21,7 @@ const PROVIDER_INFO = { rdns: "io.ghostchain.GhostWalletExtension", } -type OnAccountsChangedCallback = (accounts: Account[]) => void +type OnAccountsChangedCallback = (accounts: PjsAccount[]) => void const onAccountsChangedCallbacks: OnAccountsChangedCallback[] = [] const subscribeOnAccountsChanged = (cb: OnAccountsChangedCallback) => { onAccountsChangedCallbacks.push(cb) @@ -76,9 +76,8 @@ const lightClientProvider = getLightClientProvider(CHANNEL_ID) async getAccount(chainId: string) { return rpc.client.getAccount(chainId) }, - async getAccounts(chainId: string) { - const account = await rpc.client.getAccount(chainId) - return account ? [account] : [] + async getAccounts() { + return rpc.client.getAccounts() }, async createTx(chainId: string, from: string, callData: string) { return rpc.client.createTx(chainId, from, callData) diff --git a/src/inpage/pjsInject.ts b/src/inpage/pjsInject.ts index f96f002..cd91066 100644 --- a/src/inpage/pjsInject.ts +++ b/src/inpage/pjsInject.ts @@ -2,7 +2,7 @@ import type { Injected, InjectedAccount, } from "@polkadot/extension-inject/types" -import type { Account, BackgroundRpcSpec } from "../background/types" +import type { PjsAccount, BackgroundRpcSpec } from "../background/types" import type { Unstable } from "@substrate/connect-discovery" type PjsInjectOpts = { @@ -10,7 +10,7 @@ type PjsInjectOpts = { version: string rpc: BackgroundRpcSpec providerPromise: Promise - subscribeOnAccountsChanged: (cb: (accounts: Account[]) => void) => () => void + subscribeOnAccountsChanged: (cb: (accounts: PjsAccount[]) => void) => () => void } export const pjsInject = ({ name, @@ -27,31 +27,48 @@ injectExtension( accounts: { // TODO: use anyType async get(_anyType) { - const provider = await providerPromise - return ( - await Promise.all( - Object.values(provider.getChains()).map( - async ({ genesisHash }) => - [genesisHash, await rpc.getAccounts(genesisHash)] as const, - ), - ) - ).flatMap(([genesisHash, accounts]) => - accounts.map( - ({ address }) => - ({ - address, - genesisHash, - }) as InjectedAccount, - ), - ) - }, - subscribe: subscribeOnAccountsChanged, + const accounts = await rpc.getAccounts() + return accounts.map(a => ({ + genesisHash: a.genesisHash, + address: a.address, + type: "sr25519", + })) + }, + subscribe: (cb) => { + rpc.getAccounts() + .then((currentAccounts) => { + cb(currentAccounts.map(a => ({ + genesisHash: a.genesisHash, + address: a.address, + type: "sr25519", + }))) + }) + .catch(console.error) + + return subscribeOnAccountsChanged((_) => + rpc.getAccounts() + .then((currentAccounts) => { + cb(currentAccounts.map(a => ({ + genesisHash: a.genesisHash, + address: a.address, + type: "sr25519", + }))) + }) + .catch(console.error) + ) + } }, signer: { async signPayload(payload) { return { id: requestId++, - signature: (await rpc.pjsSignPayload(payload)) as `0x{string}`, + signature: (await rpc.pjsSignPayload(payload)) as `0x${string}`, + } + }, + async signRaw(payload) { + return { + id: requestId++, + signature: (await rpc.pjsSignRaw(payload)) as `0x${string}`, } }, }, diff --git a/src/inpage/types.ts b/src/inpage/types.ts index 09e81f4..093ad26 100644 --- a/src/inpage/types.ts +++ b/src/inpage/types.ts @@ -1,5 +1,5 @@ -import { Account } from "../background/types" +import { PjsAccount } from "../background/types" export type InPageRpcSpec = { - onAccountsChanged(accounts: Account[]): void + onAccountsChanged(accounts: PjsAccount[]): void }