update extension to be compatible with PAPI

Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
This commit is contained in:
Uncle Stretch 2026-11-05 21:56:26 +03:00
parent d3274222f9
commit d79bbfe668
Signed by: str3tch
GPG Key ID: 84F3190747EE79AA
13 changed files with 237 additions and 94 deletions

View File

@ -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 <f4ts0@ghostchain.io>",

24
src/background/chains.ts Normal file
View File

@ -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<String> => {
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<void> => {
await storage.set(CHAIN_KEY_PREIFX, activeChainId)
}
return {
getActiveChainId,
setActiveChainId,
}
}

View File

@ -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<string, number>()
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<BackgroundRpcSpec, Context> = {
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",
]

View File

@ -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<typeof createBackgroundRpc>
const connectedRpcs: BackgroundRpc[] = []
const notifyOnAccountsChanged = (accounts: Account[]) =>
const notifyOnAccountsChanged = (accounts: PjsAccount[]) =>
connectedRpcs.forEach((rpc) => rpc.notify("onAccountsChanged", [accounts]))
const subscribeOnAccountsChanged = (rpc: BackgroundRpc) => {

View File

@ -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<string, CreateDeriveFn> = {
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<KeystoreMeta[]> => {
const getRootAccounts = async (chainId: string): Promise<KeystoreMeta[]> => {
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,

View File

@ -27,6 +27,7 @@ export type KeystoreMetaWithAddress = KeystoreMeta & {
export type ExposedAccount = {
publicKey: string,
address: string,
genesisHash: string,
}
export type AccountTree = KeystoreMetaWithAddress & {

View File

@ -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<UserSignedExtensions>
@ -16,5 +16,5 @@ export type Context = {
lightClientPageHelper: LightClientPageHelper
signRequests: Record<string, InternalSignRequest>
port: chrome.runtime.Port
notifyOnAccountsChanged: (accounts: Account[]) => void
notifyOnAccountsChanged: (accounts: PjsAccount[]) => void
}

View File

@ -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<ExposedAccount[]>
getAccount(chainId: string): Promise<ExposedAccount | undefined>
pjsSignPayload(payload: Pjs.SignerPayloadJSON): Promise<string>
pjsSignRaw(payload: Pjs.SignerPayloadRaw): Promise<string>
createTx(chainId: string, from: string, callData: string): Promise<string>
// private methods
getSignRequests(): Promise<Record<string, SignRequest>>
@ -143,7 +152,7 @@ export type BackgroundRpcSpec = {
changePassword(args: ChangePasswordArgs): Promise<void>
revealSecretSeed(args: RevealSecretSeedArgs): Promise<string>
getAccounts(chainId: string): Promise<KeystoreMetaWithAddress[]>
getRootAccounts(chainId: string): Promise<KeystoreMetaWithAddress[]>
renameAccount(args: RenameAccountArgs): Promise<void>
setActiveAccount(args: ActiveAccountArgs): Promise<void>
getChainSpecs(): Promise<ChainSpec[]>
@ -157,4 +166,8 @@ export type BackgroundRpcSpec = {
deriveAccount(args: DeriveAccountArgs): Promise<void>
removeAccount(args: RemoveAccountArgs): Promise<void>
extendKeystore(args: ExtendKeystoreArgs): Promise<void>
// chain specific
getActiveChainId(): Promise<String>
setActiveChainId(chainId: String | undefined): Promise<void>
}

View File

@ -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,
},

View File

@ -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<boolean>(true)
const [currentChainId, setCurrentChainIdState] = useState<string>("")
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 = {

View File

@ -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)

View File

@ -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<Unstable.Provider>
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}`,
}
},
},

View File

@ -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
}