Skip to content

Commit

Permalink
fix: wallet slice logic
Browse files Browse the repository at this point in the history
  • Loading branch information
Argeare5 committed Oct 22, 2023
1 parent 85596e9 commit 55c9b60
Show file tree
Hide file tree
Showing 12 changed files with 230 additions and 188 deletions.
13 changes: 8 additions & 5 deletions src/hooks/useLastTxLocalStatus.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ export const useLastTxLocalStatus = <T extends BaseTx>({
}: LastTxStatusesParams<T>) => {
const tx = selectLastTxByTypeAndPayload(state, activeAddress, type, payload);

const [fullTxErrorMessage, setFullTxErrorMessage] = useState('');
const [fullTxErrorMessage, setFullTxErrorMessage] = useState<string | Error>(
'',
);
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const [isTxStart, setIsTxStart] = useState(false);
Expand Down Expand Up @@ -67,10 +69,11 @@ export const useLastTxLocalStatus = <T extends BaseTx>({
try {
await callbackFunction();
} catch (e) {
const error = e as any;
console.error('TX error: ', error);
setFullTxErrorMessage(!!error?.message ? error.message : error);
setError(errorMessage);
if (e instanceof Error) {
console.error('TX error: ', e);
setFullTxErrorMessage(!!e?.message ? e.message : e);
setError(errorMessage);
}
}
setLoading(false);
}
Expand Down
26 changes: 21 additions & 5 deletions src/utils/chainInfoHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,26 @@
import { Chain, createPublicClient, http, PublicClient } from 'viem';
import { mainnet } from 'viem/chains';
import {
avalanche,
avalancheFuji,
goerli,
mainnet,
polygon,
polygonMumbai,
sepolia,
} from 'viem/chains';

export const initChainInformationConfig = (chains?: {
[chainId: number]: Chain;
}) => {
const CHAINS = chains || {};
export const initialChains: Record<number, Chain> = {
[mainnet.id]: mainnet,
[polygon.id]: polygon,
[polygonMumbai.id]: polygonMumbai,
[avalanche.id]: avalanche,
[avalancheFuji.id]: avalancheFuji,
[goerli.id]: goerli,
[sepolia.id]: sepolia,
};

export const initChainInformationConfig = (chains?: Record<number, Chain>) => {
const CHAINS = { ...initialChains, ...chains } || {};

// init clients instances from chain config
const initalizedClients: Record<number, PublicClient> = {};
Expand Down
21 changes: 15 additions & 6 deletions src/utils/constants.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import {
arbitrum,
avalanche,
goerli,
mainnet,
optimism,
polygon,
} from 'viem/chains';

export const SafeTransactionServiceUrls: { [key in number]: string } = {
1: 'https://safe-transaction-mainnet.safe.global/api/v1',
5: 'https://safe-transaction-goerli.safe.global/api/v1',
10: 'https://safe-transaction-optimism.safe.global/api/v1',
137: 'https://safe-transaction-polygon.safe.global/api/v1',
42161: 'https://safe-transaction-arbitrum.safe.global/api/v1',
43114: 'https://safe-transaction-avalanche.safe.global/api/v1',
[mainnet.id]: 'https://safe-transaction-mainnet.safe.global/api/v1',
[goerli.id]: 'https://safe-transaction-goerli.safe.global/api/v1',
[optimism.id]: 'https://safe-transaction-optimism.safe.global/api/v1',
[polygon.id]: 'https://safe-transaction-polygon.safe.global/api/v1',
[arbitrum.id]: 'https://safe-transaction-arbitrum.safe.global/api/v1',
[avalanche.id]: 'https://safe-transaction-avalanche.safe.global/api/v1',
};
14 changes: 13 additions & 1 deletion src/utils/localStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ export const setLocalStorageWallet = (walletType: WalletType) => {

export const deleteLocalStorageWallet = () => {
localStorage.removeItem(LocalStorageKeys.LastConnectedWallet);
localStorage.removeItem('wagmi.wallet');
};

export const clearWalletConnectLocalStorage = () => {
export const clearWalletLinkLocalStorage = () => {
localStorage.removeItem('walletconnect');
localStorage.removeItem('-walletlink:https://www.walletlink.org:version');
localStorage.removeItem('-walletlink:https://www.walletlink.org:session:id');
Expand All @@ -41,3 +42,14 @@ export const clearWalletConnectLocalStorage = () => {
'-walletlink:https://www.walletlink.org:walletUsername',
);
};

export const clearWalletConnectV2LocalStorage = () => {
localStorage.removeItem('wc@2:core:0.3//messages');
localStorage.removeItem('wc@2:client:0.3//proposal');
localStorage.removeItem('wc@2:universal_provider:/namespaces');
localStorage.removeItem('wc@2:core:0.3//subscription');
localStorage.removeItem('wc@2:core:0.3//history');
localStorage.removeItem('wc@2:core:0.3//expirer');
localStorage.removeItem('wc@2:core:0.3//pairing');
localStorage.removeItem('wc@2:universal_provider:/optionalNamespaces');
};
10 changes: 4 additions & 6 deletions src/web3/adapters/EthereumAdapter.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
// TODO: need fix execute tx

import { produce } from 'immer';
import { GetTransactionReturnType, Hex, PublicClient } from 'viem';

import { setLocalStorageTxPool } from '../../utils/localStorage';
import { BaseTx, ITransactionsSlice } from '../store/transactionsSlice';
import { BaseTx, ITransactionsSlice, NewTx } from '../store/transactionsSlice';
import { Wallet } from '../store/walletSlice';
import { GelatoTx } from './GelatoAdapter';
import { AdapterInterface } from './interface';

export class EthereumAdapter<T extends BaseTx> implements AdapterInterface<T> {
Expand All @@ -23,7 +20,7 @@ export class EthereumAdapter<T extends BaseTx> implements AdapterInterface<T> {
}

executeTx = async (params: {
tx: GetTransactionReturnType | GelatoTx;
tx: NewTx;
activeWallet: Wallet;
payload: object | undefined;
chainId: number;
Expand Down Expand Up @@ -78,6 +75,7 @@ export class EthereumAdapter<T extends BaseTx> implements AdapterInterface<T> {
const client = this.get().clients[chainId] as PublicClient;

try {
// TODO: need added onReplaced logic
const txn = await client.waitForTransactionReceipt({ hash: tx.hash });
this.updateTXStatus(txHash, txn.status);

Expand All @@ -89,7 +87,7 @@ export class EthereumAdapter<T extends BaseTx> implements AdapterInterface<T> {
timestamp,
});
} catch (e) {
console.log(e);
console.error(e);
}
};

Expand Down
17 changes: 6 additions & 11 deletions src/web3/adapters/GelatoAdapter.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
// TODO: need fix execute tx

import { produce } from 'immer';
import { GetTransactionReturnType, Hex } from 'viem';
import { Hex } from 'viem';

import { setLocalStorageTxPool } from '../../utils/localStorage';
import { selectIsGelatoTXPending } from '../store/transactionsSelectors';
import {
BaseTx,
GelatoBaseTx,
InitialTx,
ITransactionsSlice,
NewTx,
} from '../store/transactionsSlice';
import { Wallet } from '../store/walletSlice';
import { AdapterInterface } from './interface';
Expand Down Expand Up @@ -38,9 +38,7 @@ export type GelatoTx = {
taskId: string;
};

export function isGelatoTx(
tx: GetTransactionReturnType | GelatoTx,
): tx is GelatoTx {
export function isGelatoTx(tx: InitialTx): tx is GelatoTx {
return (tx as GelatoTx).taskId !== undefined;
}

Expand Down Expand Up @@ -68,15 +66,15 @@ export class GelatoAdapter<T extends BaseTx> implements AdapterInterface<T> {
}

executeTx = async (params: {
tx: GelatoTx | GetTransactionReturnType;
tx: NewTx;
activeWallet: Wallet;
payload: object | undefined;
chainId: number;
type: T['type'];
}): Promise<T & { status?: number; pending: boolean }> => {
const { activeWallet, chainId, type } = params;
const tx = params.tx as GelatoTx;
const from = activeWallet.account;
const from = activeWallet.address;
const gelatoTX = {
from: from as Hex,
chainId,
Expand All @@ -92,9 +90,6 @@ export class GelatoAdapter<T extends BaseTx> implements AdapterInterface<T> {
};

startTxTracking = async (taskId: string) => {
// TODO: need fix typing for transactions pool
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const tx = this.get().transactionsPool[taskId] as GelatoBaseTx;

const isPending = selectIsGelatoTXPending(tx.gelatoStatus);
Expand Down
6 changes: 2 additions & 4 deletions src/web3/adapters/GnosisAdapter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// TODO: need fix execute tx

import dayjs from 'dayjs';
import { produce } from 'immer';
import { GetTransactionReturnType, Hex } from 'viem';
Expand All @@ -10,9 +8,9 @@ import {
BaseTx,
EthBaseTx,
ITransactionsSlice,
NewTx,
} from '../store/transactionsSlice';
import { Wallet } from '../store/walletSlice';
import { GelatoTx } from './GelatoAdapter';
import { AdapterInterface } from './interface';

export type GnosisTxStatusResponse = {
Expand Down Expand Up @@ -40,7 +38,7 @@ export class GnosisAdapter<T extends BaseTx> implements AdapterInterface<T> {
}

executeTx = async (params: {
tx: GetTransactionReturnType | GelatoTx;
tx: NewTx;
activeWallet: Wallet;
payload: object | undefined;
chainId: number;
Expand Down
7 changes: 2 additions & 5 deletions src/web3/adapters/interface.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import { GetTransactionReturnType } from 'viem';

import { BaseTx, ITransactionsSlice } from '../store/transactionsSlice';
import { BaseTx, ITransactionsSlice, NewTx } from '../store/transactionsSlice';
import { Wallet } from '../store/walletSlice';
import { GelatoTx } from './GelatoAdapter';

export interface AdapterInterface<T extends BaseTx> {
get: () => ITransactionsSlice<T>;
set: (fn: (state: ITransactionsSlice<T>) => ITransactionsSlice<T>) => void;
executeTx: (params: {
tx: GetTransactionReturnType | GelatoTx;
tx: NewTx;
activeWallet: Wallet;
payload: object | undefined;
chainId: number;
Expand Down
47 changes: 16 additions & 31 deletions src/web3/providers/WagmiProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,25 @@ import {
createConfig,
GetAccountResult,
watchAccount,
watchNetwork,
} from '@wagmi/core';
import React, { useEffect, useState } from 'react';
import { Chain } from 'viem';
import { publicProvider } from 'wagmi/providers/public';
import { StoreApi, UseBoundStore } from 'zustand';

import {
AllConnectorsInitProps,
ConnectorType,
getConnectorName,
initAllConnectors,
} from '../connectors';
import { Wallet } from '../store/walletSlice';

interface WagmiProviderProps {
useStore: UseBoundStore<
StoreApi<{
setActiveWallet: (wallet: Wallet) => void;
changeActiveWalletChainId: (chainID: number) => void;
changeActiveWalletAccount: (account?: GetAccountResult) => Promise<void>;
changeActiveWalletChain: (chain?: Chain) => Promise<void>;
setConnectors: (connectors: ConnectorType[]) => void;
disconnectActiveWallet: () => void;
}>
>;
connectorsInitProps: AllConnectorsInitProps;
Expand All @@ -34,40 +33,26 @@ function Child({
}: Omit<WagmiProviderProps, 'connectorsInitProps'> & {
connectors: ConnectorType[];
}) {
const [account, setAccount] = useState<GetAccountResult | undefined>(
undefined,
);
watchAccount((data) => {
setAccount(data);
});

const setConnectors = useStore((state) => state.setConnectors);
const disconnectActiveWallet = useStore(
(state) => state.disconnectActiveWallet,
);
const { setConnectors, changeActiveWalletAccount, changeActiveWalletChain } =
useStore();

const [currentWalletType, setCurrentWalletType] = useState<string>('');
watchAccount(async (data) => {
if (data.address) {
await changeActiveWalletAccount(data);
}
});
watchNetwork(async (data) => {
if (data.chain?.id) {
await changeActiveWalletChain(data.chain);
}
});

useEffect(() => {
if (connectors) {
setConnectors(connectors);
}
}, [connectors]);

useEffect(() => {
if (account && account.address && account.isConnected) {
const walletType =
account.connector &&
getConnectorName(account.connector as ConnectorType);

if (walletType) {
setCurrentWalletType(walletType);
} else if (currentWalletType !== walletType) {
disconnectActiveWallet();
}
}
}, [account]);

return null;
}

Expand Down
12 changes: 7 additions & 5 deletions src/web3/store/transactionsSelectors.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import isEqual from 'lodash/isEqual';
import { Chain } from 'viem';
import { goerli, mainnet } from 'viem/chains';

import { isGelatoBaseTx } from '../adapters/GelatoAdapter';
import { BaseTx, GelatoBaseTx, ITransactionsState } from './transactionsSlice';
Expand Down Expand Up @@ -33,21 +34,21 @@ export const selectTXByHash = <T extends BaseTx>(
if (txByKey) {
return txByKey;
}
return selectAllTransactions(state).find((tx) => tx.hash == hash);
return selectAllTransactions(state).find((tx) => tx.hash === hash);
};

export const selectAllTransactionsByWallet = <T extends BaseTx>(
state: ITransactionsState<T>,
from: string,
) => {
return selectAllTransactions(state).filter((tx) => tx.from == from);
return selectAllTransactions(state).filter((tx) => tx.from === from);
};

export const selectPendingTransactionByWallet = <T extends BaseTx>(
state: ITransactionsState<T>,
from: string,
) => {
return selectPendingTransactions(state).filter((tx) => tx.from == from);
return selectPendingTransactions(state).filter((tx) => tx.from === from);
};

export const selectLastTxByTypeAndPayload = <T extends BaseTx>(
Expand Down Expand Up @@ -88,9 +89,10 @@ export const selectTxExplorerLink = <T extends BaseTx>(
return '';
}

// TODO: need check
const gnosisSafeLinksHelper: Record<number, string> = {
1: 'https://app.safe.global/eth:',
5: 'https://app.safe.global/gor:',
[mainnet.id]: 'https://app.safe.global/eth:',
[goerli.id]: 'https://app.safe.global/gor:',
};

if (tx.walletType !== 'GnosisSafe') {
Expand Down
Loading

0 comments on commit 55c9b60

Please sign in to comment.