Skip to content

Commit

Permalink
fix: code style
Browse files Browse the repository at this point in the history
  • Loading branch information
Argeare5 committed Nov 19, 2023
1 parent 7182993 commit 323f603
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 101 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@bgd-labs/frontend-web3-utils",
"description": "Frontend utilities common to multiple Web3 projects",
"version": "0.4.87",
"version": "0.4.88",
"author": "BGD labs",
"license": "MIT",
"private": false,
Expand Down
30 changes: 15 additions & 15 deletions src/web3/adapters/GelatoAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,21 @@ export class GelatoAdapter<T extends BaseTx> implements AdapterInterface<T> {
this.set = set;
}

checkIsGelatoAvailable = async (chainId: number) => {
try {
const response = await fetch(`https://relay.gelato.digital/relays/v2`);
if (!response.ok) {
return false;
} else {
const listOfRelays = (await response.json()) as { relays: string[] };
return !!listOfRelays.relays.find((id) => +id === chainId);
}
} catch (e) {
console.error('Check gelato available error', e);
return false;
}
};

startTxTracking = async (tx: PoolTx<T>) => {
if (isGelatoBaseTx(tx)) {
const isPending = isGelatoTXPending(tx.gelatoStatus);
Expand Down Expand Up @@ -89,21 +104,6 @@ export class GelatoAdapter<T extends BaseTx> implements AdapterInterface<T> {
}
};

checkIsGelatoAvailable = async (chainId: number) => {
try {
const response = await fetch(`https://relay.gelato.digital/relays/v2`);
if (!response.ok) {
return false;
} else {
const listOfRelays = (await response.json()) as { relays: string[] };
return !!listOfRelays.relays.find((id) => +id === chainId);
}
} catch (e) {
console.error('Check gelato available error', e);
return false;
}
};

private fetchGelatoTXStatus = async (taskId: string) => {
const response = await fetch(
`https://api.gelato.digital/tasks/status/${taskId}/`,
Expand Down
51 changes: 18 additions & 33 deletions src/web3/store/transactionsSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,38 +25,38 @@ import { WalletType } from '../connectors';
import { IWalletSlice } from './walletSlice';

export type PoolTxParams = {
status?: TransactionStatus;
pending: boolean;
walletType: WalletType;
status?: TransactionStatus;
replacedTxHash?: Hex;
};

export type PoolTx<T extends BaseTx> = T & PoolTxParams;
export type EthPoolTx = EthBaseTx & PoolTxParams;
export type GelatoPoolTx = GelatoBaseTx & PoolTxParams;

export type PoolTx<T extends BaseTx> = T & PoolTxParams;
export type TransactionPool<T extends BaseTx> = Record<string, T>;

export type TransactionsSliceBaseType = {
clients: ClientsRecord;
setClient: (chainId: number, client: PublicClient) => void;
initTxPool: () => void;
};

export type TransactionPool<T extends BaseTx> = Record<string, T>;

export interface ITransactionsState<T extends BaseTx> {
transactionsPool: TransactionPool<PoolTx<T>>;
transactionsIntervalsMap: Record<string, number | undefined>;
}

export interface ITransactionsActions<T extends BaseTx> {
adapters: {
[TxAdapter.Ethereum]: EthereumAdapter<T>;
[TxAdapter.Safe]?: SafeAdapter<T>;
[TxAdapter.Gelato]?: GelatoAdapter<T>;
};
setAdapter: (adapter: TxAdapter) => void;

transactionsPool: TransactionPool<PoolTx<T>>;
transactionsIntervalsMap: Record<string, number | undefined>;

isGelatoAvailable: boolean;
checkIsGelatoAvailable: (chainId: number) => Promise<void>;
}

export interface ITransactionsActions<T extends BaseTx> {
txStatusChangedCallback: (
data: T & {
status?: TransactionStatus;
Expand All @@ -73,9 +73,6 @@ export interface ITransactionsActions<T extends BaseTx> {
}) => Promise<TransactionPool<T & PoolTxParams>[string] | undefined>;
addTXToPool: (tx: InitialTxParams<T>) => TransactionPool<PoolTx<T>>;
removeTXFromPool: (txKey: string) => void;

isGelatoAvailable: boolean;
checkIsGelatoAvailable: (chainId: number) => Promise<void>;
}

export type ITransactionsSlice<T extends BaseTx> = ITransactionsActions<T> &
Expand All @@ -97,6 +94,7 @@ export function createTransactionsSlice<T extends BaseTx>({
Pick<IWalletSlice, 'checkAndSwitchNetwork' | 'activeWallet'>
> {
return (set, get) => ({
txStatusChangedCallback,
clients: defaultClients,
setClient: (chainId, client) => {
set((state) =>
Expand All @@ -106,7 +104,8 @@ export function createTransactionsSlice<T extends BaseTx>({
);
},

txStatusChangedCallback,
transactionsPool: {},
transactionsIntervalsMap: {},

adapters: {
[TxAdapter.Ethereum]: new EthereumAdapter(get, set),
Expand All @@ -126,9 +125,6 @@ export function createTransactionsSlice<T extends BaseTx>({
}
},

transactionsPool: {},
transactionsIntervalsMap: {},

initTxPool: () => {
const localStorageTXPool = getLocalStorageTxPool();

Expand Down Expand Up @@ -168,7 +164,6 @@ export function createTransactionsSlice<T extends BaseTx>({
}

const chainId = Number(desiredChainID);

let adapterType = TxAdapter.Ethereum;
let newTxKey: Hex | string | undefined = isHex(txKey) ? txKey : undefined;

Expand Down Expand Up @@ -257,26 +252,16 @@ export function createTransactionsSlice<T extends BaseTx>({
delete draft.transactionsPool[txKey];
}),
);

const txPool = get().transactionsPool;
setLocalStorageTxPool(txPool);
setLocalStorageTxPool(get().transactionsPool);
},

// need for gelato only
isGelatoAvailable: true,
checkIsGelatoAvailable: async (chainId) => {
get().setAdapter(TxAdapter.Gelato);
const adapter = get().adapters[TxAdapter.Gelato];
if (adapter) {
const isAvailable = await adapter.checkIsGelatoAvailable(chainId);
set({ isGelatoAvailable: isAvailable });
} else {
get().setAdapter(TxAdapter.Gelato);
const isAvailable =
await get().adapters[TxAdapter.Gelato]?.checkIsGelatoAvailable(
chainId,
);
set({ isGelatoAvailable: isAvailable });
}
const isAvailable = await adapter?.checkIsGelatoAvailable(chainId);
set({ isGelatoAvailable: isAvailable });
},
});
}
111 changes: 59 additions & 52 deletions src/web3/store/walletSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,42 +35,48 @@ export interface Wallet {
walletClient: WalletClient;
// isActive is added, because Wallet can be connected but not active, i.e. wrong network
isActive: boolean;
// isContractAddress is added, to check if wallet address is contract
// isContractAddress is added, to check if wallet address is contract (mostly fo safe)
isContractAddress: boolean;
}

export type IWalletSlice = {
isContractWalletRecord: Record<string, boolean>;
connectors: ConnectorType[];
setConnectors: (connectors: ConnectorType[]) => void;

defaultChainId: number;
setDefaultChainId: (chainId: number) => void;

initDefaultWallet: () => Promise<void>;

isActiveWalletSetting: boolean;
activeWallet?: Wallet;
setActiveWallet: (
wallet: Omit<Wallet, 'walletClient' | 'client'>,
) => Promise<void>;
isActiveWalletSetting: boolean;
connectWallet: (walletType: WalletType, chainId?: number) => Promise<void>;
disconnectActiveWallet: () => Promise<void>;

walletActivating: boolean;
walletConnectionError: string;
connectWallet: (walletType: WalletType, chainId?: number) => Promise<void>;
disconnectActiveWallet: () => Promise<void>;
resetWalletConnectionError: () => void;
initDefaultWallet: () => Promise<void>;
changeActiveWalletAccount: (account?: GetAccountResult) => Promise<void>;
checkAndSwitchNetwork: (chainId?: number) => Promise<void>;

isActiveWalletAccountChanging: boolean;
changeActiveWalletChain: (chain?: Chain) => Promise<void>;
changeActiveWalletAccount: (account?: GetAccountResult) => Promise<void>;
isActiveWalletChainChanging: boolean;
checkAndSwitchNetwork: (chainId?: number) => Promise<void>;
connectors: ConnectorType[];
setConnectors: (connectors: ConnectorType[]) => void;
changeActiveWalletChain: (chain?: Chain) => Promise<void>;

impersonated?: {
account?: Account;
address?: Hex;
isViewOnly?: boolean;
};
setImpersonated: (privateKeyOrAddress: string) => void;

isContractWalletRecord: Record<string, boolean>;
checkIsContractWallet: (
wallet: Omit<Wallet, 'walletClient'>,
) => Promise<boolean>;

defaultChainId: number;
setDefaultChainId: (chainId: number) => void;
};

export function createWalletSlice({
Expand All @@ -79,9 +85,6 @@ export function createWalletSlice({
walletConnected: (wallet: Wallet) => void;
}): StoreSlice<IWalletSlice, TransactionsSliceBaseType> {
return (set, get) => ({
isContractWalletRecord: {},
walletActivating: false,
walletConnectionError: '',
connectors: [],
setConnectors: async (connectors) => {
if (get().connectors.length !== connectors.length) {
Expand All @@ -90,6 +93,12 @@ export function createWalletSlice({
get().initTxPool();
}
},

defaultChainId: mainnet.id,
setDefaultChainId: (chainId) => {
set({ defaultChainId: chainId });
},

initDefaultWallet: async () => {
const lastConnectedWallet = localStorage.getItem(
LocalStorageKeys.LastConnectedWallet,
Expand All @@ -100,6 +109,7 @@ export function createWalletSlice({
}
},

isActiveWalletSetting: false,
setActiveWallet: async (wallet) => {
if (wallet.isActive) {
if (wallet.chain) {
Expand Down Expand Up @@ -128,8 +138,9 @@ export function createWalletSlice({
}
}
},
isActiveWalletSetting: false,

walletActivating: false,
walletConnectionError: '',
connectWallet: async (walletType, chainId) => {
clearWalletLinkLocalStorage();
clearWalletConnectV2LocalStorage();
Expand Down Expand Up @@ -178,7 +189,7 @@ export function createWalletSlice({
}
} catch (e) {
if (e instanceof Error) {
const errorMessage = e.message ? e.message.toString() : e.toString();
const errorMessage = e.message ? String(e.message) : String(e);
set({
walletConnectionError: errorMessage,
});
Expand All @@ -187,6 +198,16 @@ export function createWalletSlice({
}
set({ walletActivating: false });
},
disconnectActiveWallet: async () => {
await disconnect();
set({ activeWallet: undefined });
deleteLocalStorageWallet();
clearWalletLinkLocalStorage();
clearWalletConnectV2LocalStorage();
},
resetWalletConnectionError: () => {
set({ walletConnectionError: '' });
},
checkAndSwitchNetwork: async (chainId) => {
const activeWallet = get().activeWallet;
if (chainId && activeWallet && activeWallet?.chain?.id !== chainId) {
Expand All @@ -207,32 +228,8 @@ export function createWalletSlice({
});
}
},
disconnectActiveWallet: async () => {
await disconnect();
set({ activeWallet: undefined });
deleteLocalStorageWallet();
clearWalletLinkLocalStorage();
clearWalletConnectV2LocalStorage();
},

checkIsContractWallet: async (wallet) => {
const address = wallet.address;
const walletRecord = get().isContractWalletRecord[address];
if (walletRecord !== undefined) {
return walletRecord;
}
const codeOfWalletAddress = await wallet.client.getBytecode({
address: wallet.address,
});
const isContractWallet = !!codeOfWalletAddress;
set((state) =>
produce(state, (draft) => {
draft.isContractWalletRecord[address] = isContractWallet;
}),
);
return isContractWallet;
},

isActiveWalletAccountChanging: false,
changeActiveWalletAccount: async (account) => {
const activeWallet = get().activeWallet;
if (
Expand All @@ -252,7 +249,7 @@ export function createWalletSlice({
set({ isActiveWalletAccountChanging: false });
}
},
isActiveWalletAccountChanging: false,
isActiveWalletChainChanging: false,
changeActiveWalletChain: async (chain) => {
const activeWallet = get().activeWallet;
if (
Expand All @@ -273,7 +270,6 @@ export function createWalletSlice({
set({ isActiveWalletChainChanging: false });
}
},
isActiveWalletChainChanging: false,

setImpersonated: (privateKeyOrAddress) => {
if (isAddress(privateKeyOrAddress)) {
Expand All @@ -292,13 +288,24 @@ export function createWalletSlice({
});
}
},
resetWalletConnectionError: () => {
set({ walletConnectionError: '' });
},

defaultChainId: mainnet.id,
setDefaultChainId: (chainId) => {
set({ defaultChainId: chainId });
isContractWalletRecord: {},
checkIsContractWallet: async (wallet) => {
const address = wallet.address;
const walletRecord = get().isContractWalletRecord[address];
if (walletRecord !== undefined) {
return walletRecord;
}
const codeOfWalletAddress = await wallet.client.getBytecode({
address: wallet.address,
});
const isContractWallet = !!codeOfWalletAddress;
set((state) =>
produce(state, (draft) => {
draft.isContractWalletRecord[address] = isContractWallet;
}),
);
return isContractWallet;
},
});
}

0 comments on commit 323f603

Please sign in to comment.