Skip to content

Commit

Permalink
fix typing and warnings
Browse files Browse the repository at this point in the history
Signed-off-by: Ruben <rubdeivis@gmail.com>
  • Loading branch information
rubenguc committed Apr 4, 2023
1 parent 82d671a commit 2190b45
Show file tree
Hide file tree
Showing 11 changed files with 170 additions and 107 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"devDependencies": {
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
"@esbuild-plugins/node-modules-polyfill": "^0.2.2",
"@polkadot/types-codec": "^10.2.2",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.0.0",
"@types/chrome": "^0.0.220",
Expand Down
34 changes: 17 additions & 17 deletions src/entries/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { getProvider } from "@src/providers/networkProvider";
import { Keyring } from "@polkadot/keyring";
import { TxToProcess } from "@src/types";

const openPopUp = (params: any) => {
const openPopUp = (params: unknown) => {
const querys = makeQuerys(params);

return chrome.windows.create({
Expand Down Expand Up @@ -116,7 +116,7 @@ const getSelectedAccount = () => {
return Extension.getSelectedAccount();
};

const processTx = (tx: any) => {
const processTx = (tx: TxToProcess) => {
if (tx?.tx.type === AccountType.WASM) {
processWasmTx(tx);
} else {
Expand All @@ -129,22 +129,22 @@ const processWasmTx = async ({
asset,
originAddress,
destinationAddress,
originNetwork,
// originNetwork,
destinationNetwork,
networkInfo,
tx,
rpc,
}: TxToProcess) => {
const { txHash, type, aditional } = tx;

const api = await getProvider(rpc, AccountType.WASM);
const { block } = await (api as ApiPromise).rpc.chain.getBlock();
const api = (await getProvider(rpc, AccountType.WASM)) as ApiPromise;
const { block } = await api.rpc.chain.getBlock();

const seed = await Extension.showSeed();
const keyring = new Keyring({ type: "sr25519" });
const sender = keyring.addFromMnemonic(seed as string);

const unsub = await (api as ApiPromise)
const unsub = await api
?.tx(txHash)
?.signAndSend(
sender as AddressOrPair,
Expand All @@ -153,7 +153,8 @@ const processWasmTx = async ({
if (String(status.type) === "Ready") {
const hash = txHash.toString();
const date = Date.now();
const activity = {

const activity: Partial<Record> = {
fromBlock: block.header.number.toString(),
address: originAddress,
type: RecordType.TRANSFER,
Expand All @@ -178,11 +179,8 @@ const processWasmTx = async ({
},
} as TransferData,
};
await Extension.addActivity(hash, activity as any);
chrome.runtime.sendMessage({
origin: "kuma",
method: "update_activity",
});
await Extension.addActivity(hash, activity as Record);
sendUpdateActivityMessage();
}
if (status.isFinalized) {
const failedEvents = events.filter(({ event }) =>
Expand All @@ -194,9 +192,9 @@ const processWasmTx = async ({
failedEvents.forEach(
({
event: {
data: [_error, info],
data: [_error],
},
}) => {
}: any) => {
if (_error.isModule) {
const decoded = api?.registry.findMetaError(_error.asModule);
const { docs, method, section } = decoded;
Expand Down Expand Up @@ -226,7 +224,7 @@ const processEVMTx = async ({
asset,
originAddress,
destinationAddress,
originNetwork,
// originNetwork,
destinationNetwork,
networkInfo,
tx,
Expand All @@ -242,11 +240,11 @@ const processEVMTx = async ({

const txReceipt = await api.getTransaction(txHash);
const date = Date.now();
const activity = {
const activity: Partial<Record> = {
address: originAddress,
type: RecordType.TRANSFER,
reference: AccountType.EVM,
hash: tx,
hash: txHash,
status: RecordStatus.PENDING,
createdAt: date,
lastUpdated: date,
Expand Down Expand Up @@ -277,6 +275,8 @@ const processEVMTx = async ({
sendNotification(`tx ${status}`, txHash);
sendUpdateActivityMessage();
} catch (error) {
sendNotification(`tx failed`, txHash);
await Extension.updateActivity(txHash, RecordStatus.FAIL, String(error));
console.error(error);
}
};
Expand Down
2 changes: 1 addition & 1 deletion src/entries/scripts/contentScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ interface KumaProps {
(window as any).kuma = {
call: ({ method, params }: KumaProps) => {
const origin = window.location.origin;
return new Promise((res, rej) => {
return new Promise((res) => {
window.postMessage({
origin: "kuma",
method,
Expand Down
148 changes: 65 additions & 83 deletions src/providers/txProvider/TxProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,41 +5,24 @@ import {
useContext,
useEffect,
useReducer,
// useState,
} from "react";
import { RecordStatus } from "@src/storage/entities/activity/types";
import { useAccountContext } from "../accountProvider";
import Extension from "@src/Extension";
import { ApiPromise } from "@polkadot/api";
import { ethers } from "ethers";
import { Tx } from "@src/pages";
import { useNetworkContext } from "..";

interface InitialState {
activity: any[];
}
import { Action, InitialState, TxContext } from "./types";
import Record from "@src/storage/entities/activity/Record";

const initialState: InitialState = {
activity: [],
};

interface TxContext {
state: InitialState;
addTxToQueue: (newTx: newTx) => void;
}

const TxContext = createContext({} as TxContext);

const reducer = (state: InitialState, action: any): InitialState => {
const reducer = (state: InitialState, action: Action): InitialState => {
switch (action.type) {
case "add-activity": {
const { tx } = action.payload;

return {
...state,
activity: [tx, ...state.activity],
};
}
case "init-activity": {
const { activity } = action.payload;

Expand All @@ -50,25 +33,24 @@ const reducer = (state: InitialState, action: any): InitialState => {
}
case "update-activity-status": {
const { hash, status, error } = action.payload;
const activity = state.activity.map((act) =>
act.hash === hash ? { ...act, status, error } : act
);

const _activity = [...state.activity];
const index = _activity.findIndex((a) => a.hash === hash);
if (index !== -1) {
_activity[index].status = status;
_activity[index].error = error;
}

return {
...state,
activity,
activity: _activity,
};
}
default:
return state;
}
};

interface newTx {
tx: Tx;
destinationAccount: string;
amount: number;
}

export const TxProvider: FC<PropsWithChildren> = ({ children }) => {
const {
state: { api, selectedChain },
Expand All @@ -79,7 +61,6 @@ export const TxProvider: FC<PropsWithChildren> = ({ children }) => {
} = useAccountContext();

const [state, dispatch] = useReducer(reducer, initialState);
// const [isSearching, setisSearching] = useState(false);

const loadActivity = async () => {
const records = await Extension.getActivity();
Expand All @@ -92,61 +73,59 @@ export const TxProvider: FC<PropsWithChildren> = ({ children }) => {
return records;
};

const searchTx = async (blockNumber: any, extHash: any) => {
const searchWasmTx = async (blockNumber: number, extHash: string) => {
let number = blockNumber;
let finish = false;
while (!finish) {
const hash = await (api as ApiPromise).rpc.chain.getBlockHash(number);
const { block } = await (api as ApiPromise).rpc.chain.getBlock(hash);
const _api = api as ApiPromise;
const hash = await _api.rpc.chain.getBlockHash(number);
const { block } = await _api.rpc.chain.getBlock(hash);

const apiAt = await api.at(block.header.hash);
const apiAt = await _api.at(block.header.hash);
const allRecords = await apiAt.query.system.events();

for (const [
index,
{
method: { method, section },
hash,
},
] of block.extrinsics.entries()) {
for (const [index, { hash }] of block.extrinsics.entries()) {
if (hash.toString() === extHash) {
allRecords

.filter(
({ phase }) =>
phase.isApplyExtrinsic && phase.asApplyExtrinsic.eq(index)
)
.forEach(async ({ event }) => {
let status = RecordStatus.PENDING;
let error = undefined;
if (api.events.system.ExtrinsicSuccess.is(event)) {
status = RecordStatus.SUCCESS;
} else if (api.events.system.ExtrinsicFailed.is(event)) {
const [dispatchError] = event.data;

if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(
dispatchError.asModule
);

error = `${decoded.section}.${decoded.name}`;
} else {
error = dispatchError.toString();
Array.isArray(allRecords) &&
allRecords
.filter(
({ phase }) =>
phase.isApplyExtrinsic && phase.asApplyExtrinsic.eq(index)
)
.forEach(async ({ event }) => {
let status = RecordStatus.PENDING;
let error = undefined;

if (api.events.system.ExtrinsicSuccess.is(event)) {
status = RecordStatus.SUCCESS;
} else if (api.events.system.ExtrinsicFailed.is(event)) {
const [dispatchError] = event.data;

if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(
dispatchError.asModule
);

error = `${decoded.section}.${decoded.name}`;
} else {
error = dispatchError.toString();
}
status = RecordStatus.FAIL;
}
status = RecordStatus.FAIL;
}

await Extension.updateActivity(hash.toString(), status, error);

dispatch({
type: "update-activity-status",
payload: {
hash,
status,
error,
},

const _hash = hash.toString();

await Extension.updateActivity(_hash, status, error);

dispatch({
type: "update-activity-status",
payload: {
hash: _hash,
status,
error,
},
});
});
});
finish = true;
break;
}
Expand Down Expand Up @@ -180,19 +159,25 @@ export const TxProvider: FC<PropsWithChildren> = ({ children }) => {
await Extension.updateActivity(hash, status, error);
};

const processPendingTxs = async (activityArray: any[]) => {
const processPendingTxs = async (activityArray: Record[]) => {
for (const activity of activityArray) {
if (activity.status === RecordStatus.PENDING) {
if (activity.reference === "WASM") {
searchTx(Number(activity?.fromBlock), activity.hash);
searchWasmTx(Number(activity?.fromBlock), activity.hash);
} else {
searchEvmTx(activity.hash);
}
}
}
};

const activityListener = ({ origin, method }: any) => {
const activityListener = ({
origin,
method,
}: {
origin: string;
method: string;
}) => {
if (origin === "kuma" && method === "update_activity") {
loadActivity();
}
Expand Down Expand Up @@ -225,9 +210,6 @@ export const TxProvider: FC<PropsWithChildren> = ({ children }) => {
<TxContext.Provider
value={{
state,
addTxToQueue: () => {
//
},
}}
>
{children}
Expand Down
25 changes: 25 additions & 0 deletions src/providers/txProvider/types.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import Record from "@src/storage/entities/activity/Record";

export interface InitialState {
activity: Record[];
}

export interface TxContext {
state: InitialState;
}

export type Action =
| {
type: "init-activity";
payload: {
activity: Record[];
};
}
| {
type: "update-activity-status";
payload: {
hash: string;
status: RecordStatus;
error: string;
};
};
2 changes: 1 addition & 1 deletion src/storage/entities/CacheAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default class CacheAuth extends BaseEntity {
await CacheAuth.get<CacheAuth>();
}

static fromData<CacheAuth>(data: { [key: string]: any }): CacheAuth {
static fromData<CacheAuth>(data: { [key: string]: unknown }): CacheAuth {
const entity = CacheAuth.getInstance();
Object.keys(data).forEach((key) => {
(entity as any)[key] = data[key];
Expand Down
Loading

0 comments on commit 2190b45

Please sign in to comment.