Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: shield nam #1165

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 2 additions & 38 deletions apps/extension/src/extension/ExtensionRequester.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import BigNumber from "bignumber.js";
import browser from "webextension-polyfill";

import { deserializeBigNumbers } from "@namada/utils";
import { Message } from "../router";
import { Messenger } from "./ExtensionMessenger";

Expand Down Expand Up @@ -40,7 +40,7 @@ export class ExtensionRequester {
throw error;
}

return fixBigNumbers(result.return);
return deserializeBigNumbers(result.return);
}

async sendMessageToTab<M extends Message<unknown>>(
Expand Down Expand Up @@ -94,39 +94,3 @@ export class ExtensionRequester {
return tabs.map((tab) => tab.id || browser.tabs.TAB_ID_NONE);
}
}

/**
* Searches through an object and creates BigNumbers from any object with
* the _isBigNumber property. This is needed because BigNumbers lose their
* prototype when sent between extension scripts in Firefox.
*
* Returns the object with the BigNumbers reconstructed.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const fixBigNumbers = (result: any): any => {
if (typeof result !== "object" || result === null) {
return result;
}

if (result["_isBigNumber"]) {
return BigNumber(result as BigNumber.Value);
}

const unseenValues = [result];

while (unseenValues.length !== 0) {
const obj = unseenValues.pop();
Object.entries(obj).forEach(([key, value]) => {
if (typeof value === "object" && value !== null) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((value as any)["_isBigNumber"]) {
obj[key] = BigNumber(value as BigNumber.Value);
} else {
unseenValues.push(value);
}
}
});
}

return result;
};
29 changes: 2 additions & 27 deletions apps/extension/src/extension/ExtensionRouter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import BigNumber from "bignumber.js";
import { serializeBigNumbers } from "@namada/utils/helpers";
import {
EnvProducer,
MessageSender,
Expand Down Expand Up @@ -61,7 +61,7 @@ export class ExtensionRouter extends Router {
): Promise<Result> {
try {
const result = await this.handleMessage(message, sender);
fixBigNumbers(result);
serializeBigNumbers(result);
return {
return: result,
};
Expand All @@ -77,28 +77,3 @@ export class ExtensionRouter extends Router {
}
}
}

/**
* Searches through an object and adds the _isBigNumber key to any BigNumber
* values. This key is used by the BigNumber constructor to reconstruct a
* BigNumber from a plain object, and is needed because BigNumbers lose their
* prototype when sent between extension scripts in Firefox.
*
* Fixes object in place and returns void.
*/
const fixBigNumbers = (result: unknown): void => {
const unseenValues = [result];

while (unseenValues.length !== 0) {
const value = unseenValues.pop();

if (typeof value === "object" && value !== null) {
if (BigNumber.isBigNumber(value)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(value as any)["_isBigNumber"] = true;
} else {
unseenValues.push(...Object.values(value));
}
}
}
};
1 change: 1 addition & 0 deletions apps/namadillo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"@tanstack/react-query-persist-client": "^5.40.0",
"bignumber.js": "^9.1.1",
"clsx": "^2.1.1",
"comlink": "^4.4.1",
"crypto-browserify": "^3.12.0",
"fp-ts": "^2.16.1",
"framer-motion": "^11.3.28",
Expand Down
2 changes: 2 additions & 0 deletions apps/namadillo/src/App/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { useOnNamadaExtensionAttached } from "hooks/useOnNamadaExtensionAttached
import { useTransactionCallback } from "hooks/useTransactionCallbacks";
import { useTransactionNotifications } from "hooks/useTransactionNotifications";
import { Outlet } from "react-router-dom";

import { ChainLoader } from "./Setup/ChainLoader";

export const history = createBrowserHistory({ window });
Expand All @@ -15,6 +16,7 @@ export function App(): JSX.Element {
useOnNamadaExtensionAttached();
useTransactionNotifications();
useTransactionCallback();

return (
<>
<Toasts />
Expand Down
2 changes: 1 addition & 1 deletion apps/namadillo/src/App/Ibc/IbcWithdraw.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Key as KeplrKey, Window as KeplrWindow } from "@keplr-wallet/types";
import { Panel } from "@namada/components";
import { WindowWithNamada } from "@namada/types";
import BigNumber from "bignumber.js";
import { getSdkInstance } from "hooks";
import { useAtomValue } from "jotai";
import { useEffect, useState } from "react";

Expand All @@ -11,6 +10,7 @@ import { NamInput } from "App/Common/NamInput";
import { accountBalanceAtom, defaultAccountAtom } from "atoms/accounts";
import { chainAtom, chainParametersAtom } from "atoms/chain";
import { getFirstError } from "atoms/utils";
import { getSdkInstance } from "utils/sdk";

const keplr = (window as KeplrWindow).keplr!;
const namada = (window as WindowWithNamada).namada!;
Expand Down
107 changes: 107 additions & 0 deletions apps/namadillo/src/App/WorkerTest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import * as Comlink from "comlink";

import { ShieldingTransferMsgValue } from "@namada/types";
import { defaultAccountAtom } from "atoms/accounts";
import { chainAtom, nativeTokenAddressAtom } from "atoms/chain";
import { indexerUrlAtom, rpcUrlAtom } from "atoms/settings";
import BigNumber from "bignumber.js";
import { useAtomValue } from "jotai";
import { signTx } from "lib/query";
import { Shield } from "workers/ShieldMessages";
import {
registerTransferHandlers,
Worker as ShieldWorkerApi,
} from "workers/ShieldWorker";
import ShieldWorker from "workers/ShieldWorker?worker";
import { Worker as ShieldedSyncWorkerApi } from "workers/ShieldedSyncWorker";
import ShieldedSyncWorker from "workers/ShieldedSyncWorker?worker";

export function WorkerTest(): JSX.Element {
const rpcUrl = useAtomValue(rpcUrlAtom);

const { data: account } = useAtomValue(defaultAccountAtom);
const { data: chain } = useAtomValue(chainAtom);
const { data: token } = useAtomValue(nativeTokenAddressAtom);
const indexerUrl = useAtomValue(indexerUrlAtom);

// eslint-disable-next-line @typescript-eslint/no-explicit-any
(window as any).shieldedSync = async (vk: string) => {
const worker = new ShieldedSyncWorker();
const shieldedSyncWorker = Comlink.wrap<ShieldedSyncWorkerApi>(worker);
await shieldedSyncWorker.init({
type: "init",
payload: {
rpcUrl,
token: token!,
},
});

await shieldedSyncWorker.sync({
type: "sync",
payload: {
vks: [vk],
},
});

worker.terminate();
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
(window as any).buildShieldlingTx = async (
target: string,
amount: number
) => {
registerTransferHandlers();
const worker = new ShieldWorker();
const shieldWorker = Comlink.wrap<ShieldWorkerApi>(worker);

await shieldWorker.init({
type: "init",
payload: {
rpcUrl,
token: token!,
},
});

const shieldingMsgValue = new ShieldingTransferMsgValue({
target,
data: [
{
source: account?.address || "",
token: token!,
amount: BigNumber(amount),
},
],
});

const msg: Shield = {
type: "shield",
payload: {
account: account!,
gasConfig: {
gasLimit: BigNumber(250000),
gasPrice: BigNumber(0.000001),
},
shieldingProps: [shieldingMsgValue],
indexerUrl,
chain: chain!,
},
};

const { payload: encodedTx } = await shieldWorker.shield(msg);

const signedTxs = await signTx("namada", encodedTx, account?.address || "");

await shieldWorker.broadcast({
type: "broadcast",
payload: {
encodedTx,
signedTxs,
},
});

worker.terminate();
};

return <div></div>;
}
2 changes: 1 addition & 1 deletion apps/namadillo/src/atoms/proposals/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ import { TransactionPair, buildTxPair } from "lib/query";
import { GasConfig } from "types";

import { fromHex } from "@cosmjs/encoding";
import { getSdkInstance } from "hooks";
import { ChainSettings } from "types";
import { getSdkInstance } from "utils/sdk";

// TODO: this function is way too big
const decodeProposalType = (
Expand Down
2 changes: 1 addition & 1 deletion apps/namadillo/src/atoms/staking/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ import {
WrapperTxProps,
} from "@namada/types";
import { queryClient } from "App/Common/QueryProvider";
import { getSdkInstance } from "hooks";
import { TransactionPair, buildTxPair } from "lib/query";
import { Address, AddressBalance, ChainSettings, GasConfig } from "types";
import { getSdkInstance } from "utils/sdk";

export const fetchClaimableRewards = async (
api: DefaultApi,
Expand Down
39 changes: 3 additions & 36 deletions apps/namadillo/src/hooks/useSdk.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import initSdk from "@heliax/namada-sdk/inline-init";
import { getSdk, Sdk } from "@heliax/namada-sdk/web";
import { Sdk } from "@heliax/namada-sdk/web";
import { QueryStatus, useQuery } from "@tanstack/react-query";
import { nativeTokenAddressAtom } from "atoms/chain";
import { maspIndexerUrlAtom, rpcUrlAtom } from "atoms/settings";
import { getDefaultStore, useAtomValue } from "jotai";
import { useAtomValue } from "jotai";
import {
createContext,
FunctionComponent,
Expand All @@ -12,6 +10,7 @@ import {
useEffect,
useState,
} from "react";
import { getSdkInstance } from "utils/sdk";

type SdkContext = {
sdk?: Sdk;
Expand All @@ -25,38 +24,6 @@ export const SdkContext = createContext<SdkContext>({

const paramsUrl = "/params/";

const initializeSdk = async (): Promise<Sdk> => {
const { cryptoMemory } = await initSdk();
const store = getDefaultStore();
const rpcUrl = store.get(rpcUrlAtom);
const maspIndexerUrl = store.get(maspIndexerUrlAtom);
const nativeToken = store.get(nativeTokenAddressAtom);

if (!nativeToken.isSuccess) {
throw "Native token not loaded";
}

const sdk = getSdk(
cryptoMemory,
rpcUrl,
maspIndexerUrl,
"",
nativeToken.data
);
return sdk;
};

// Global instance of initialized SDK
let sdkInstance: Promise<Sdk>;

// Helper to access SDK instance
export const getSdkInstance = async (): Promise<Sdk> => {
if (!sdkInstance) {
sdkInstance = initializeSdk();
}
return sdkInstance;
};

export const SdkProvider: FunctionComponent<PropsWithChildren> = ({
children,
}) => {
Expand Down
19 changes: 12 additions & 7 deletions apps/namadillo/src/lib/query.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getIntegration } from "@namada/integrations";
import { Sdk } from "@heliax/namada-sdk/web";
import { getIntegration } from "@namada/integrations/utils";
import {
Account,
AccountType,
Expand All @@ -10,11 +11,11 @@ import {
} from "@namada/types";
import { getIndexerApi } from "atoms/api";
import { chainParametersAtom } from "atoms/chain";
import { getSdkInstance } from "hooks";
import invariant from "invariant";
import { getDefaultStore } from "jotai";
import { Address, ChainSettings, GasConfig } from "types";
import { TransactionEventsClasses } from "types/events";
import { getSdkInstance } from "utils/sdk";

export type TransactionPair<T> = {
encodedTxData: EncodedTxData<T>;
Expand Down Expand Up @@ -85,19 +86,20 @@ export const isPublicKeyRevealed = async (
* @param {(WrapperTxProps, T) => Promise<TxMsgValue>} txFn - Function to build each transaction.
*/
export const buildTx = async <T>(
sdk: Sdk,
account: Account,
gasConfig: GasConfig,
chain: ChainSettings,
queryProps: T[],
txFn: (wrapperTxProps: WrapperTxProps, props: T) => Promise<TxMsgValue>
txFn: (wrapperTxProps: WrapperTxProps, props: T) => Promise<TxMsgValue>,
publicKeyRevealed: boolean
): Promise<EncodedTxData<T>> => {
const { tx } = await getSdkInstance();
const { tx } = sdk;
const wrapperTxProps = getTxProps(account, gasConfig, chain);
const txs: TxMsgValue[] = [];
const txProps: TxProps[] = [];

// Determine if RevealPK is needed:
const publicKeyRevealed = await isPublicKeyRevealed(account.address);
if (!publicKeyRevealed) {
const revealPkTx = await tx.buildRevealPk(wrapperTxProps);
txs.push(revealPkTx);
Expand All @@ -115,7 +117,6 @@ export const buildTx = async <T>(
txProps.push(tx.buildBatch(txs));
}

const sdk = await getSdkInstance();
return {
txs: txProps.map(({ args, hash, bytes, signingData }) => {
const innerTxHashes = sdk.tx.getInnerTxHashes(bytes);
Expand Down Expand Up @@ -184,12 +185,16 @@ export const buildTxPair = async <T>(
txFn: (wrapperTxProps: WrapperTxProps, props: T) => Promise<TxMsgValue>,
owner: string
): Promise<TransactionPair<T>> => {
const sdk = await getSdkInstance();
const publicKeyRevealed = await isPublicKeyRevealed(account.address);
const encodedTxData = await buildTx<T>(
sdk,
account,
gasConfig,
chain,
queryProps,
txFn
txFn,
publicKeyRevealed
);
const signedTxs = await signTx<T>(chain.extensionId, encodedTxData, owner);
return {
Expand Down
Loading
Loading