Compare commits

..

No commits in common. "main" and "development" have entirely different histories.

9 changed files with 52 additions and 214 deletions

View File

@ -1,6 +1,6 @@
{
"name": "ghost-wallet",
"version": "0.4.2",
"version": "0.4.1",
"description": "Browser extension to manage ghost blockchain light clients.",
"main": "dist/src/index.js",
"author": "Uncle f4ts0 <f4ts0@ghostchain.io>",

View File

@ -217,7 +217,7 @@ export const createBackgroundRpc = (
const createdWindow = await chrome.windows.create({
focused: true,
height: 640,
height: 680,
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: 640,
height: 680,
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: 640,
height: 680,
width: 460,
type: "popup",
url: chrome.runtime.getURL(`ui/assets/wallet-popup.html#/sign-raw-request/${id}`),
@ -513,25 +513,7 @@ export const createBackgroundRpc = (
}
},
async getSignRequests(_, { signRequests }) {
const sanitized: Record<string, any> = {};
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;
return signRequests
},
async approveSignRequest([id, userSignedExtensions, password], { signRequests }) {
signRequests[id]?.resolve({

View File

@ -4,7 +4,6 @@ export type NetworkType = {
value: string
prefix: number
decimals: number
symbol: string
}
export const networks: NetworkType[] = [
@ -12,7 +11,6 @@ export const networks: NetworkType[] = [
chainId: "0xcaf9c5ddccc7ba6f96149a6b8a81c26a3641742795cd5e7e0aee79bf3f4e77b7",
value: "casper_staging_testnet",
label: "CASPER Testnet",
symbol: "CSPR",
prefix: 1996,
decimals: 18,
}

View File

@ -11,7 +11,6 @@ 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<string>((resolve, reject) =>
client._request("state_getMetadata", [], {
@ -27,7 +26,5 @@ export const decodeCallData = async (chainId: string, callData: string) => {
return getViewBuilder(getLookupFn(convertedMetadata)).callDecoder(callData)
} catch {
return undefined
} finally {
client.destroy()
}
}

View File

@ -1,100 +0,0 @@
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<bigint | undefined> => {
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<string>((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();
}
};

View File

@ -1,3 +1,2 @@
export * from "./rpc"
export * from "./decodeCallData"
export * from "./feeEstimation"

View File

@ -11,24 +11,26 @@ export const UserSignedExtensions = ({ userSignedExtensions }: Props) => (
case "CheckMortality": {
const mortality = userSignedExtensions[type]!
return (
<div key={type} className="w-full flex flex-row justify-between items-center">
<span className="text-xs font-semibold text-white">Transaction Mortality</span>
<span className="text-xs font-medium text-primary font-mono">
{mortality.mortal ? `${mortality.period} blocks` : "Immortal"}
</span>
</div>
<Input
readOnly
aria-label="Check Mortality"
type="number"
className="pr-10 mt-4"
placeholder={`Mortality: ${mortality.mortal ? `${mortality.period} blocks` : "inmortal"}`}
/>
)
}
case "ChargeTransactionPayment": {
const payment = userSignedExtensions[type]!
const formattedTip = String(payment).replace(/n$/, "")
return <div className="my-1">tip: {payment.toString()}</div>
return (
<div key={type} className="w-full flex flex-row justify-between items-center">
<span className="text-xs font-semibold text-white">Tip Amount</span>
<span className="text-xs font-medium text-primary font-mono">
{formattedTip}
</span>
</div>
<Input
readOnly
aria-label="Charge Transaction Payment"
type="number"
className="pr-10 mt-4"
placeholder={`Tip: ${payment.toString()}`}
/>
)
}
default: {

View File

@ -13,7 +13,9 @@ type ChainContextType = {
const ChainContext = createContext({} as ChainContextType)
export const ChainProvider = ({ children }: { children?: ReactNode }) => {
const { data: currentChainId, isLoading: isLoadingChain, mutate: currentChainIdMutate } = useSWR(
const [isLoadingChain, setIsLoadingChain] = useState<boolean>(true)
const { data: currentChainId, mutate: currentChainIdMutate } = useSWR(
"rpc.getActiveChainId",
() => rpc.client.getActiveChainId(),
{

View File

@ -17,27 +17,8 @@ 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 {
@ -78,31 +59,6 @@ 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 (
<Layout2>
@ -116,6 +72,13 @@ 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)
@ -137,9 +100,11 @@ export const SignRequest = () => {
}
}
console.log(isExecutionBlocked, inAction)
return (
<Layout2>
<div className="flex flex-col justify-between h-full">
<div className="flex flex-col justify-between">
<div className="">
<div className="py-2 px-6">
{activeAddress && (
@ -179,14 +144,17 @@ export const SignRequest = () => {
</span>
</div>
<div className="w-full flex flex-row justify-between items-center">
<span className="text-xs font-semibold text-white">Network Fee</span>
<span className={`text-xs font-medium font-mono ${feeError ? "text-red-400" : "text-primary"}`}>
{feeDisplayValue}
</span>
<div className="w-full flex flex-col min-w-0 mt-6">
<div className="text-xs font-semibold mb-2 text-white uppercase tracking-wider">
Transaction Details
</div>
<div className="w-full min-w-0">
<DecodedCallData chainId={request.chainId} callData={request.callData} />
</div>
</div>
<div className="mt-6">
<div className="my-2">
{request.userSignedExtensions.type === "names" ? (
<UserSignedExtensionInputs
userSignedExtensionNames={request.userSignedExtensions.names}
@ -198,30 +166,11 @@ export const SignRequest = () => {
/>
)}
</div>
<div className="w-full flex flex-col min-w-0 mt-6">
<div className="text-xs font-semibold mb-2 text-white uppercase tracking-wider">
Transaction Details
</div>
<div className="w-full min-w-0">
<DecodedCallData chainId={request.chainId} callData={request.callData} />
</div>
</div>
</div>
)}
</div>
<div className="w-full flex flex-col items-center gap-4 px-6 py-4 mt-auto">
<Button
variant="primary"
size="full"
disabled={isExecutionBlocked || inAction}
onClick={() => handleSigning()}
>
Approve
</Button>
<div className="w-full flex gap-4 justify-center space-x-4 pt-6 px-6">
<Button
variant="secondary"
disabled={inAction}
@ -230,6 +179,15 @@ export const SignRequest = () => {
>
Cancel
</Button>
<Button
variant="primary"
size="full"
disabled={isExecutionBlocked || inAction}
onClick={() => handleSigning()}
>
Approve
</Button>
</div>
</div>
</Layout2>