Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8f7d040fe6 |
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "ghost-wallet",
|
"name": "ghost-wallet",
|
||||||
"version": "0.4.1",
|
"version": "0.4.2",
|
||||||
"description": "Browser extension to manage ghost blockchain light clients.",
|
"description": "Browser extension to manage ghost blockchain light clients.",
|
||||||
"main": "dist/src/index.js",
|
"main": "dist/src/index.js",
|
||||||
"author": "Uncle f4ts0 <f4ts0@ghostchain.io>",
|
"author": "Uncle f4ts0 <f4ts0@ghostchain.io>",
|
||||||
|
|||||||
@ -217,7 +217,7 @@ export const createBackgroundRpc = (
|
|||||||
|
|
||||||
const createdWindow = await chrome.windows.create({
|
const createdWindow = await chrome.windows.create({
|
||||||
focused: true,
|
focused: true,
|
||||||
height: 680,
|
height: 640,
|
||||||
width: 460,
|
width: 460,
|
||||||
type: "popup",
|
type: "popup",
|
||||||
url: chrome.runtime.getURL(`ui/assets/wallet-popup.html#/sign-request/${id}`),
|
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({
|
const createdWindow = await chrome.windows.create({
|
||||||
focused: true,
|
focused: true,
|
||||||
height: 680,
|
height: 640,
|
||||||
width: 460,
|
width: 460,
|
||||||
type: "popup",
|
type: "popup",
|
||||||
url: chrome.runtime.getURL(`ui/assets/wallet-popup.html#/sign-request/${id}`),
|
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({
|
const createdWindow = await chrome.windows.create({
|
||||||
focused: true,
|
focused: true,
|
||||||
height: 680,
|
height: 640,
|
||||||
width: 460,
|
width: 460,
|
||||||
type: "popup",
|
type: "popup",
|
||||||
url: chrome.runtime.getURL(`ui/assets/wallet-popup.html#/sign-raw-request/${id}`),
|
url: chrome.runtime.getURL(`ui/assets/wallet-popup.html#/sign-raw-request/${id}`),
|
||||||
@ -513,7 +513,25 @@ export const createBackgroundRpc = (
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
async getSignRequests(_, { signRequests }) {
|
async getSignRequests(_, { signRequests }) {
|
||||||
return 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;
|
||||||
},
|
},
|
||||||
async approveSignRequest([id, userSignedExtensions, password], { signRequests }) {
|
async approveSignRequest([id, userSignedExtensions, password], { signRequests }) {
|
||||||
signRequests[id]?.resolve({
|
signRequests[id]?.resolve({
|
||||||
|
|||||||
@ -4,6 +4,7 @@ export type NetworkType = {
|
|||||||
value: string
|
value: string
|
||||||
prefix: number
|
prefix: number
|
||||||
decimals: number
|
decimals: number
|
||||||
|
symbol: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export const networks: NetworkType[] = [
|
export const networks: NetworkType[] = [
|
||||||
@ -11,6 +12,7 @@ export const networks: NetworkType[] = [
|
|||||||
chainId: "0xcaf9c5ddccc7ba6f96149a6b8a81c26a3641742795cd5e7e0aee79bf3f4e77b7",
|
chainId: "0xcaf9c5ddccc7ba6f96149a6b8a81c26a3641742795cd5e7e0aee79bf3f4e77b7",
|
||||||
value: "casper_staging_testnet",
|
value: "casper_staging_testnet",
|
||||||
label: "CASPER Testnet",
|
label: "CASPER Testnet",
|
||||||
|
symbol: "CSPR",
|
||||||
prefix: 1996,
|
prefix: 1996,
|
||||||
decimals: 18,
|
decimals: 18,
|
||||||
}
|
}
|
||||||
|
|||||||
@ -11,6 +11,7 @@ export const decodeCallData = async (chainId: string, callData: string) => {
|
|||||||
const chain = chains.find(({ genesisHash }) => genesisHash === chainId)
|
const chain = chains.find(({ genesisHash }) => genesisHash === chainId)
|
||||||
if (!chain) throw new Error("unknown chain")
|
if (!chain) throw new Error("unknown chain")
|
||||||
const client = createClient(chain.provider)
|
const client = createClient(chain.provider)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const metadata = await new Promise<string>((resolve, reject) =>
|
const metadata = await new Promise<string>((resolve, reject) =>
|
||||||
client._request("state_getMetadata", [], {
|
client._request("state_getMetadata", [], {
|
||||||
@ -26,5 +27,7 @@ export const decodeCallData = async (chainId: string, callData: string) => {
|
|||||||
return getViewBuilder(getLookupFn(convertedMetadata)).callDecoder(callData)
|
return getViewBuilder(getLookupFn(convertedMetadata)).callDecoder(callData)
|
||||||
} catch {
|
} catch {
|
||||||
return undefined
|
return undefined
|
||||||
|
} finally {
|
||||||
|
client.destroy()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
100
src/containers/WalletPopup/api/feeEstimation.ts
Normal file
100
src/containers/WalletPopup/api/feeEstimation.ts
Normal file
@ -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<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();
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -1,2 +1,3 @@
|
|||||||
export * from "./rpc"
|
export * from "./rpc"
|
||||||
export * from "./decodeCallData"
|
export * from "./decodeCallData"
|
||||||
|
export * from "./feeEstimation"
|
||||||
|
|||||||
@ -11,26 +11,24 @@ export const UserSignedExtensions = ({ userSignedExtensions }: Props) => (
|
|||||||
case "CheckMortality": {
|
case "CheckMortality": {
|
||||||
const mortality = userSignedExtensions[type]!
|
const mortality = userSignedExtensions[type]!
|
||||||
return (
|
return (
|
||||||
<Input
|
<div key={type} className="w-full flex flex-row justify-between items-center">
|
||||||
readOnly
|
<span className="text-xs font-semibold text-white">Transaction Mortality</span>
|
||||||
aria-label="Check Mortality"
|
<span className="text-xs font-medium text-primary font-mono">
|
||||||
type="number"
|
{mortality.mortal ? `${mortality.period} blocks` : "Immortal"}
|
||||||
className="pr-10 mt-4"
|
</span>
|
||||||
placeholder={`Mortality: ${mortality.mortal ? `${mortality.period} blocks` : "inmortal"}`}
|
</div>
|
||||||
/>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
case "ChargeTransactionPayment": {
|
case "ChargeTransactionPayment": {
|
||||||
const payment = userSignedExtensions[type]!
|
const payment = userSignedExtensions[type]!
|
||||||
return <div className="my-1">tip: {payment.toString()}</div>
|
const formattedTip = String(payment).replace(/n$/, "")
|
||||||
return (
|
return (
|
||||||
<Input
|
<div key={type} className="w-full flex flex-row justify-between items-center">
|
||||||
readOnly
|
<span className="text-xs font-semibold text-white">Tip Amount</span>
|
||||||
aria-label="Charge Transaction Payment"
|
<span className="text-xs font-medium text-primary font-mono">
|
||||||
type="number"
|
{formattedTip}
|
||||||
className="pr-10 mt-4"
|
</span>
|
||||||
placeholder={`Tip: ${payment.toString()}`}
|
</div>
|
||||||
/>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
default: {
|
default: {
|
||||||
|
|||||||
@ -13,9 +13,7 @@ type ChainContextType = {
|
|||||||
const ChainContext = createContext({} as ChainContextType)
|
const ChainContext = createContext({} as ChainContextType)
|
||||||
|
|
||||||
export const ChainProvider = ({ children }: { children?: ReactNode }) => {
|
export const ChainProvider = ({ children }: { children?: ReactNode }) => {
|
||||||
const [isLoadingChain, setIsLoadingChain] = useState<boolean>(true)
|
const { data: currentChainId, isLoading: isLoadingChain, mutate: currentChainIdMutate } = useSWR(
|
||||||
|
|
||||||
const { data: currentChainId, mutate: currentChainIdMutate } = useSWR(
|
|
||||||
"rpc.getActiveChainId",
|
"rpc.getActiveChainId",
|
||||||
() => rpc.client.getActiveChainId(),
|
() => rpc.client.getActiveChainId(),
|
||||||
{
|
{
|
||||||
|
|||||||
@ -17,8 +17,27 @@ import {
|
|||||||
UserSignedExtensions,
|
UserSignedExtensions,
|
||||||
} from "../components"
|
} from "../components"
|
||||||
|
|
||||||
|
import { feeEstimation } from "../api"
|
||||||
import { useAccounts, useChain } from "../hooks"
|
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 = () => {
|
export const SignRequest = () => {
|
||||||
const { currentChain, isLoadingChain } = useChain()
|
const { currentChain, isLoadingChain } = useChain()
|
||||||
const {
|
const {
|
||||||
@ -59,6 +78,31 @@ export const SignRequest = () => {
|
|||||||
return targetAddress
|
return targetAddress
|
||||||
}, [activeAccount, accountTree])
|
}, [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) {
|
if (isLoading || isLoadingChain || isFetchingActiveAccounts || isFetchingAccountTree) {
|
||||||
return (
|
return (
|
||||||
<Layout2>
|
<Layout2>
|
||||||
@ -72,13 +116,6 @@ export const SignRequest = () => {
|
|||||||
return null
|
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 () => {
|
const handleSigning = async () => {
|
||||||
setInAction(true)
|
setInAction(true)
|
||||||
|
|
||||||
@ -100,11 +137,9 @@ export const SignRequest = () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(isExecutionBlocked, inAction)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Layout2>
|
<Layout2>
|
||||||
<div className="flex flex-col justify-between">
|
<div className="flex flex-col justify-between h-full">
|
||||||
<div className="">
|
<div className="">
|
||||||
<div className="py-2 px-6">
|
<div className="py-2 px-6">
|
||||||
{activeAddress && (
|
{activeAddress && (
|
||||||
@ -144,17 +179,14 @@ export const SignRequest = () => {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="w-full flex flex-col min-w-0 mt-6">
|
<div className="w-full flex flex-row justify-between items-center">
|
||||||
<div className="text-xs font-semibold mb-2 text-white uppercase tracking-wider">
|
<span className="text-xs font-semibold text-white">Network Fee</span>
|
||||||
Transaction Details
|
<span className={`text-xs font-medium font-mono ${feeError ? "text-red-400" : "text-primary"}`}>
|
||||||
</div>
|
{feeDisplayValue}
|
||||||
|
</span>
|
||||||
<div className="w-full min-w-0">
|
|
||||||
<DecodedCallData chainId={request.chainId} callData={request.callData} />
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="my-2">
|
<div className="mt-6">
|
||||||
{request.userSignedExtensions.type === "names" ? (
|
{request.userSignedExtensions.type === "names" ? (
|
||||||
<UserSignedExtensionInputs
|
<UserSignedExtensionInputs
|
||||||
userSignedExtensionNames={request.userSignedExtensions.names}
|
userSignedExtensionNames={request.userSignedExtensions.names}
|
||||||
@ -166,20 +198,21 @@ export const SignRequest = () => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</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>
|
</div>
|
||||||
|
|
||||||
<div className="w-full flex gap-4 justify-center space-x-4 pt-6 px-6">
|
<div className="w-full flex flex-col items-center gap-4 px-6 py-4 mt-auto">
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
disabled={inAction}
|
|
||||||
size="full"
|
|
||||||
onClick={() => rpc.client.cancelSignRequest(signRequestId)}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
size="full"
|
size="full"
|
||||||
@ -188,6 +221,15 @@ export const SignRequest = () => {
|
|||||||
>
|
>
|
||||||
Approve
|
Approve
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
disabled={inAction}
|
||||||
|
size="full"
|
||||||
|
onClick={() => rpc.client.cancelSignRequest(signRequestId)}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Layout2>
|
</Layout2>
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user