From 8f7d040fe6d653e70a10b2cecdbe01df995c5379 Mon Sep 17 00:00:00 2001 From: Uncle Fatso Date: Fri, 20 Nov 2026 16:08:21 +0300 Subject: [PATCH] fix signing process based on the PAPI library Signed-off-by: Uncle Fatso --- package.json | 2 +- src/background/createBackgroundRpc.ts | 26 ++++- src/constants.ts | 2 + .../WalletPopup/api/decodeCallData.ts | 3 + .../WalletPopup/api/feeEstimation.ts | 100 ++++++++++++++++++ src/containers/WalletPopup/api/index.ts | 1 + .../components/UserSignedExtensions.tsx | 28 +++-- src/containers/WalletPopup/hooks/useChain.tsx | 4 +- .../WalletPopup/pages/SignRequest.tsx | 100 +++++++++++++----- 9 files changed, 214 insertions(+), 52 deletions(-) create mode 100644 src/containers/WalletPopup/api/feeEstimation.ts diff --git a/package.json b/package.json index 824cd06..f3b495d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ghost-wallet", - "version": "0.4.1", + "version": "0.4.2", "description": "Browser extension to manage ghost blockchain light clients.", "main": "dist/src/index.js", "author": "Uncle f4ts0 ", diff --git a/src/background/createBackgroundRpc.ts b/src/background/createBackgroundRpc.ts index 814db3f..3bf4953 100644 --- a/src/background/createBackgroundRpc.ts +++ b/src/background/createBackgroundRpc.ts @@ -217,7 +217,7 @@ export const createBackgroundRpc = ( const createdWindow = await chrome.windows.create({ focused: true, - height: 680, + height: 640, width: 460, type: "popup", url: chrome.runtime.getURL(`ui/assets/wallet-popup.html#/sign-request/${id}`), @@ -341,7 +341,7 @@ export const createBackgroundRpc = ( const createdWindow = await chrome.windows.create({ focused: true, - height: 680, + height: 640, width: 460, type: "popup", url: chrome.runtime.getURL(`ui/assets/wallet-popup.html#/sign-request/${id}`), @@ -445,7 +445,7 @@ export const createBackgroundRpc = ( const createdWindow = await chrome.windows.create({ focused: true, - height: 680, + height: 640, width: 460, type: "popup", url: chrome.runtime.getURL(`ui/assets/wallet-popup.html#/sign-raw-request/${id}`), @@ -513,7 +513,25 @@ export const createBackgroundRpc = ( } }, async getSignRequests(_, { signRequests }) { - return signRequests + const sanitized: Record = {}; + + const serializeBigInts = (obj) => { + if (typeof obj === "bigint") return `${obj.toString()}n`; + if (Array.isArray(obj)) return obj.map(serializeBigInts); + if (obj !== null && typeof obj === "object") { + return Object.fromEntries( + Object.entries(obj).map(([k, v]) => [k, serializeBigInts(v)]) + ); + } + return obj; + } + + for (const [id, req] of Object.entries(signRequests)) { + const { resolve, reject, ...serializableData } = req as any; + sanitized[id] = serializeBigInts(serializableData); + } + + return sanitized; }, async approveSignRequest([id, userSignedExtensions, password], { signRequests }) { signRequests[id]?.resolve({ diff --git a/src/constants.ts b/src/constants.ts index 482d72f..a7b0eff 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -4,6 +4,7 @@ export type NetworkType = { value: string prefix: number decimals: number + symbol: string } export const networks: NetworkType[] = [ @@ -11,6 +12,7 @@ export const networks: NetworkType[] = [ chainId: "0xcaf9c5ddccc7ba6f96149a6b8a81c26a3641742795cd5e7e0aee79bf3f4e77b7", value: "casper_staging_testnet", label: "CASPER Testnet", + symbol: "CSPR", prefix: 1996, decimals: 18, } diff --git a/src/containers/WalletPopup/api/decodeCallData.ts b/src/containers/WalletPopup/api/decodeCallData.ts index dbb217b..c6d31f3 100644 --- a/src/containers/WalletPopup/api/decodeCallData.ts +++ b/src/containers/WalletPopup/api/decodeCallData.ts @@ -11,6 +11,7 @@ export const decodeCallData = async (chainId: string, callData: string) => { const chain = chains.find(({ genesisHash }) => genesisHash === chainId) if (!chain) throw new Error("unknown chain") const client = createClient(chain.provider) + try { const metadata = await new Promise((resolve, reject) => client._request("state_getMetadata", [], { @@ -26,5 +27,7 @@ export const decodeCallData = async (chainId: string, callData: string) => { return getViewBuilder(getLookupFn(convertedMetadata)).callDecoder(callData) } catch { return undefined + } finally { + client.destroy() } } diff --git a/src/containers/WalletPopup/api/feeEstimation.ts b/src/containers/WalletPopup/api/feeEstimation.ts new file mode 100644 index 0000000..94a422b --- /dev/null +++ b/src/containers/WalletPopup/api/feeEstimation.ts @@ -0,0 +1,100 @@ +import { helper } from "@substrate/light-client-extension-helpers/extension-page" +import { createClient } from "@polkadot-api/substrate-client" + +function hexToBytes(hex: string): Uint8Array { + const clean = hex.startsWith("0x") ? hex.slice(2) : hex; + const bytes = new Uint8Array(clean.length / 2); + for (let i = 0; i < bytes.length; i++) { + bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16); + } + return bytes; +} + +function bytesToHex(bytes: Uint8Array): string { + return "0x" + Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); +} + +function encodeCompactLength(len: number): Uint8Array { + if (len < 64) return new Uint8Array([len << 2]); + if (len < 16384) { + const val = (len << 2) | 0x01; + return new Uint8Array([val & 0xff, (val >> 8) & 0xff]); + } + const val = (len << 2) | 0x02; + return new Uint8Array([ + val & 0xff, + (val >> 8) & 0xff, + (val >> 16) & 0xff, + (val >> 24) & 0xff, + ]); +} + +function wrapCallDataInDummyExtrinsic(callDataHex: string): Uint8Array { + const callBytes = hexToBytes(callDataHex); + + const version = new Uint8Array([0x84]); + const address = new Uint8Array(33); + const signature = new Uint8Array(65); + signature[0] = 0x01; + + const extra = new Uint8Array([0x00, 0x00, 0x00]); + + const bodyLen = version.length + address.length + signature.length + extra.length + callBytes.length; + const prefix = encodeCompactLength(bodyLen); + + const extrinsic = new Uint8Array(prefix.length + bodyLen); + let offset = 0; + for (const part of [prefix, version, address, signature, extra, callBytes]) { + extrinsic.set(part, offset); + offset += part.length; + } + return extrinsic; +} + +function decodePartialFee(resultHex: string): bigint { + const bytes = hexToBytes(resultHex); + const feeBytes = bytes.slice(bytes.length - 16); + let fee = 0n; + for (let i = 15; i >= 0; i--) { + fee = (fee << 8n) | BigInt(feeBytes[i]); + } + return fee; +} + +export const feeEstimation = async ( + chainId: string, + callData: string, +): Promise => { + const chains = await helper.getChains(); + const chain = chains.find(({ genesisHash }) => genesisHash === chainId); + if (!chain) throw new Error("unknown chain"); + + const client = createClient(chain.provider); + + try { + const extrinsic = wrapCallDataInDummyExtrinsic(callData); + const params = new Uint8Array(extrinsic.length + 4); + params.set(extrinsic, 0); + new DataView(params.buffer).setUint32(extrinsic.length, extrinsic.length, true); + + const rawHex = await new Promise((resolve, reject) => + client._request( + "state_call", + ["TransactionPaymentApi_query_info", bytesToHex(params)], + { + onSuccess: (result) => resolve(result as string), + onError: reject, + }, + ), + ).catch(() => undefined); + + if (!rawHex) return undefined; + + return decodePartialFee(rawHex); + } catch (err) { + console.error(err); + return undefined; + } finally { + client.destroy(); + } +}; diff --git a/src/containers/WalletPopup/api/index.ts b/src/containers/WalletPopup/api/index.ts index 3b5fd71..25537d8 100644 --- a/src/containers/WalletPopup/api/index.ts +++ b/src/containers/WalletPopup/api/index.ts @@ -1,2 +1,3 @@ export * from "./rpc" export * from "./decodeCallData" +export * from "./feeEstimation" diff --git a/src/containers/WalletPopup/components/UserSignedExtensions.tsx b/src/containers/WalletPopup/components/UserSignedExtensions.tsx index 90ced5b..f5e41df 100644 --- a/src/containers/WalletPopup/components/UserSignedExtensions.tsx +++ b/src/containers/WalletPopup/components/UserSignedExtensions.tsx @@ -11,26 +11,24 @@ export const UserSignedExtensions = ({ userSignedExtensions }: Props) => ( case "CheckMortality": { const mortality = userSignedExtensions[type]! return ( - +
+ Transaction Mortality + + {mortality.mortal ? `${mortality.period} blocks` : "Immortal"} + +
) } case "ChargeTransactionPayment": { const payment = userSignedExtensions[type]! - return
tip: {payment.toString()}
+ const formattedTip = String(payment).replace(/n$/, "") return ( - +
+ Tip Amount + + {formattedTip} + +
) } default: { diff --git a/src/containers/WalletPopup/hooks/useChain.tsx b/src/containers/WalletPopup/hooks/useChain.tsx index 6660826..f4bf16e 100644 --- a/src/containers/WalletPopup/hooks/useChain.tsx +++ b/src/containers/WalletPopup/hooks/useChain.tsx @@ -13,9 +13,7 @@ type ChainContextType = { const ChainContext = createContext({} as ChainContextType) export const ChainProvider = ({ children }: { children?: ReactNode }) => { - const [isLoadingChain, setIsLoadingChain] = useState(true) - - const { data: currentChainId, mutate: currentChainIdMutate } = useSWR( + const { data: currentChainId, isLoading: isLoadingChain, mutate: currentChainIdMutate } = useSWR( "rpc.getActiveChainId", () => rpc.client.getActiveChainId(), { diff --git a/src/containers/WalletPopup/pages/SignRequest.tsx b/src/containers/WalletPopup/pages/SignRequest.tsx index 62d6a9b..de42b64 100644 --- a/src/containers/WalletPopup/pages/SignRequest.tsx +++ b/src/containers/WalletPopup/pages/SignRequest.tsx @@ -17,8 +17,27 @@ import { UserSignedExtensions, } from "../components" +import { feeEstimation } from "../api" import { useAccounts, useChain } from "../hooks" +const formatNetworkFee = ( + plancks: bigint | string, + decimals = 18, + symbol?: string, +): string => { + const value = BigInt(plancks); + const divisor = 10n ** BigInt(decimals); + const whole = value / divisor; + const fraction = (value % divisor) + .toString() + .padStart(decimals, "0") + .slice(0, 6) + .replace(/0+$/, ""); + + const formatted = fraction ? `${whole}.${fraction}` : whole.toString(); + return symbol ? `${formatted} ${symbol}` : formatted; +} + export const SignRequest = () => { const { currentChain, isLoadingChain } = useChain() const { @@ -59,6 +78,31 @@ export const SignRequest = () => { return targetAddress }, [activeAccount, accountTree]) + const request = signRequests?.[signRequestId] + const isRequestNotFound = !request || error + + const isAddressMismatched = !!(request && activeAddress && request.address !== activeAddress) + const isChainMismatched = !!(request && chainId && request.chainId !== chainId) + const isExecutionBlocked = isRequestNotFound || isAddressMismatched || isChainMismatched + + const { data: fee, isLoading: isFeeLoading, error: feeError } = useSWR( + chainId && request?.callData ? ["feeEstimation", chainId, request.callData] : null, + ([, id, callData]) => feeEstimation(id, callData), + { + revalidateOnFocus: false, + shouldRetryOnError: false, + }, + ); + + const feeDisplayValue = useMemo(() => { + if (isFeeLoading) return "Estimating fee..."; + if (feeError || fee === undefined) return "Unable to estimate fee"; + + const decimals = currentChain?.decimals ?? 18; + const symbol = currentChain?.symbol ?? ""; + return formatNetworkFee(fee, decimals, symbol); + }, [isFeeLoading, feeError, fee, currentChain]); + if (isLoading || isLoadingChain || isFetchingActiveAccounts || isFetchingAccountTree) { return ( @@ -72,13 +116,6 @@ export const SignRequest = () => { return null } - const request = signRequests?.[signRequestId] - const isRequestNotFound = !request || error - - const isAddressMismatched = !!(request && activeAddress && request.address !== activeAddress) - const isChainMismatched = !!(request && chainId && request.chainId !== chainId) - const isExecutionBlocked = isRequestNotFound || isAddressMismatched || isChainMismatched - const handleSigning = async () => { setInAction(true) @@ -100,11 +137,9 @@ export const SignRequest = () => { } } - console.log(isExecutionBlocked, inAction) - return ( -
+
{activeAddress && ( @@ -144,17 +179,14 @@ export const SignRequest = () => {
-
-
- Transaction Details -
- -
- -
+
+ Network Fee + + {feeDisplayValue} +
-
+
{request.userSignedExtensions.type === "names" ? ( { /> )}
+ +
+
+ Transaction Details +
+ +
+ +
+
)}
-
- - +
+ +