From 9256d91498d9e302fb8c97a3792b224fd9e90e12 Mon Sep 17 00:00:00 2001 From: Corban Brook Date: Wed, 10 Apr 2024 10:45:37 -0400 Subject: [PATCH] Prettier format (#14) * Prettier format * Updating format command to work on tsx files as well --- package.json | 2 +- packages/checkout/src/api/data.tsx | 105 ++++--- packages/checkout/src/api/index.tsx | 2 +- .../checkout/src/contexts/CheckoutModal.tsx | 20 +- packages/checkout/src/contexts/Navigation.tsx | 21 +- packages/checkout/src/contexts/index.ts | 2 +- packages/checkout/src/hooks/data.ts | 6 +- packages/checkout/src/hooks/index.ts | 2 +- .../checkout/src/hooks/useCheckoutModal.tsx | 2 +- packages/checkout/src/hooks/useModalTheme.tsx | 2 +- packages/checkout/src/hooks/useNavigation.tsx | 13 +- packages/checkout/src/shared/styles.css.ts | 7 +- packages/checkout/src/utils/helpers.ts | 12 +- packages/checkout/src/utils/index.ts | 2 +- packages/checkout/src/utils/networks.ts | 2 +- .../src/views/PaperTransactionForm.tsx | 11 +- .../checkout/src/views/PendingTransaction.tsx | 48 ++-- .../checkout/src/views/TransactionError.tsx | 4 +- .../checkout/src/views/TransactionSuccess.tsx | 6 +- packages/checkout/src/views/index.ts | 2 +- packages/kit/src/components/index.tsx | 2 +- packages/kit/src/components/styles.css.ts | 15 +- .../kit/src/constants/defaultSignInOptions.ts | 2 +- packages/kit/src/constants/index.ts | 2 +- packages/kit/src/contexts/Analytics.tsx | 8 +- packages/kit/src/contexts/ConnectModal.tsx | 2 +- packages/kit/src/contexts/Theme.tsx | 6 +- packages/kit/src/contexts/WalletSettings.tsx | 2 +- packages/kit/src/contexts/index.ts | 2 +- packages/kit/src/hooks/index.ts | 2 +- .../kit/src/hooks/useOpenConnectModal.tsx | 2 +- packages/kit/src/hooks/useWalletSettings.tsx | 4 +- packages/kit/src/utils/adapters.ts | 11 +- packages/kit/src/utils/clients.ts | 2 +- packages/kit/src/utils/ethAuth.tsx | 27 +- packages/kit/src/utils/genericContext.tsx | 16 +- .../kit/src/utils/getKitConnectWallets.ts | 24 +- packages/kit/src/utils/helpers.ts | 2 +- packages/kit/src/utils/index.ts | 2 +- packages/kit/src/utils/networks.ts | 12 +- packages/kit/src/utils/styling.ts | 23 +- packages/kit/src/utils/tokens.ts | 30 +- packages/wallet/src/api/data.tsx | 262 ++++++++++-------- packages/wallet/src/api/index.tsx | 2 +- packages/wallet/src/constants/abi.ts | 2 +- packages/wallet/src/constants/currency.ts | 2 +- packages/wallet/src/constants/index.ts | 2 +- packages/wallet/src/constants/sizing.ts | 2 +- packages/wallet/src/contexts/Navigation.tsx | 63 +++-- packages/wallet/src/contexts/WalletModal.tsx | 2 +- packages/wallet/src/contexts/index.ts | 2 +- packages/wallet/src/hooks/data.ts | 70 +++-- packages/wallet/src/hooks/index.ts | 2 +- packages/wallet/src/hooks/useNavigation.tsx | 13 +- .../wallet/src/hooks/useOpenWalletModal.tsx | 4 +- packages/wallet/src/hooks/useSettings.tsx | 46 ++- packages/wallet/src/shared/CoinIcon.tsx | 11 +- packages/wallet/src/shared/CoinRow.tsx | 59 ++-- .../src/shared/CollectibleTileImage.tsx | 29 +- packages/wallet/src/shared/CopyButton.tsx | 4 +- packages/wallet/src/shared/DefaultIcon.tsx | 8 +- packages/wallet/src/shared/Loader.tsx | 6 +- packages/wallet/src/shared/NetworkBadge.tsx | 20 +- packages/wallet/src/shared/SendItemInfo.tsx | 33 ++- packages/wallet/src/shared/index.tsx | 2 +- packages/wallet/src/shared/styles.css.ts | 15 +- packages/wallet/src/utils/helpers.ts | 10 +- packages/wallet/src/utils/index.ts | 2 +- packages/wallet/src/utils/networks.ts | 2 +- packages/wallet/src/utils/tokens.ts | 34 +-- packages/wallet/src/views/History.tsx | 14 +- packages/wallet/src/views/Receive.tsx | 43 ++- packages/wallet/src/views/SendCoin.tsx | 177 +++++------- packages/wallet/src/views/SendCollectible.tsx | 147 +++++----- packages/wallet/src/views/index.ts | 2 +- 75 files changed, 739 insertions(+), 822 deletions(-) diff --git a/package.json b/package.json index 32fe3b36..e3b16ce3 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "lint:fix": "eslint -c .eslintrc.js --fix 'packages/**/src/**/*.{ts,tsx}'", "lint:tests": "eslint -c .eslintrc.js 'packages/**/tests/**/*.{ts,tsx}'", "lint:tests:fix": "eslint -c .eslintrc.js 'packages/**/tests/**/*.{ts,tsx}'", - "format": "prettier --write packages/**/src/**/*.ts packages/**/tests/**/*.ts", + "format": "prettier --write packages/**/src/**/*.{ts,tsx}", "audit:fix": "pnpm audit --fix", "typecheck": "tsc --noEmit", "coverage": "rimraf ./coverage && rimraf ./.nyc_output && nyc pnpm test", diff --git a/packages/checkout/src/api/data.tsx b/packages/checkout/src/api/data.tsx index c4fadaa0..34392665 100644 --- a/packages/checkout/src/api/data.tsx +++ b/packages/checkout/src/api/data.tsx @@ -7,16 +7,16 @@ import { ethers } from 'ethers' import { getPaperNetworkName } from '../utils' export interface GetTokenBalancesArgs { - accountAddress: string, + accountAddress: string chainId: number } export const getNativeToken = async ({ accountAddress, chainId }: GetTokenBalancesArgs) => { try { - const { indexerClient } = await getNetworkConfigAndClients(chainId) + const { indexerClient } = await getNetworkConfigAndClients(chainId) const res = await indexerClient.getEtherBalance({ accountAddress }) - + const tokenBalance: TokenBalance = { chainId, contractAddress: ethers.constants.AddressZero, @@ -25,10 +25,10 @@ export const getNativeToken = async ({ accountAddress, chainId }: GetTokenBalanc contractType: ContractType.UNKNOWN, blockHash: '', blockNumber: 0, - tokenID: '', + tokenID: '' } return [tokenBalance] - } catch(e) { + } catch (e) { console.error(e) return [] } @@ -36,7 +36,7 @@ export const getNativeToken = async ({ accountAddress, chainId }: GetTokenBalanc export const getTokenBalances = async ({ accountAddress, chainId }: GetTokenBalancesArgs) => { try { - const { indexerClient } = await getNetworkConfigAndClients(chainId) + const { indexerClient } = await getNetworkConfigAndClients(chainId) const res = await indexerClient.getTokenBalances({ accountAddress, @@ -45,9 +45,9 @@ export const getTokenBalances = async ({ accountAddress, chainId }: GetTokenBala verifiedOnly: true } }) - + return res?.balances || [] - } catch(e) { + } catch (e) { console.error(e) return [] } @@ -63,26 +63,26 @@ export const fetchBalances = async ({ accountAddress, chainId }: GetTokenBalance }), getTokenBalances({ accountAddress, - chainId, + chainId }) ]) ).flat() return tokenBalances - } catch(e) { + } catch (e) { console.error(e) return [] } } export interface GetCollectionBalanceArgs { - accountAddress: string, - chainId: number, + accountAddress: string + chainId: number collectionAddress: string } export const fetchCollectionBalance = async ({ accountAddress, chainId, collectionAddress }: GetCollectionBalanceArgs) => { try { - const { indexerClient } = await getNetworkConfigAndClients(chainId) + const { indexerClient } = await getNetworkConfigAndClients(chainId) const res = await indexerClient.getTokenBalances({ accountAddress, @@ -92,9 +92,9 @@ export const fetchCollectionBalance = async ({ accountAddress, chainId, collecti verifiedOnly: true } }) - + return res?.balances || [] - } catch(e) { + } catch (e) { console.error(e) return [] } @@ -108,15 +108,15 @@ export const getCoinPrices = async ({ tokens }: GetCoinPricesArgs): Promise => { +export const fetchTokenMetadata = async ({ chainId, tokenId, contractAddress }: GetTokenMetadataArgs): Promise => { const { metadataClient } = await getNetworkConfigAndClients(chainId) const response = await metadataClient.getTokenMetadata({ chainID: String(chainId), contractAddress, - tokenIDs: [tokenId], + tokenIDs: [tokenId] }) return response.tokenMetadata[0] } -export const fetchContractInfo = async ({ - chainID, - contractAddress, -}: GetContractInfoArgs): Promise => { +export const fetchContractInfo = async ({ chainID, contractAddress }: GetContractInfoArgs): Promise => { const { metadataClient } = await getNetworkConfigAndClients(chainID) - + const response = await metadataClient.getContractInfo({ chainID, - contractAddress, + contractAddress }) return response.contractInfo } export interface FetchPaperSecretArgs { - chainId: number, - email: string, - abi: string, - contractAddress: string, - recipientAddress: string, - receiptTitle: string, - collectionContractAddress?: string, - methodArguments: MethodArguments, - currency: string, - currencyAmount: string, - methodName: string, + chainId: number + email: string + abi: string + contractAddress: string + recipientAddress: string + receiptTitle: string + collectionContractAddress?: string + methodArguments: MethodArguments + currency: string + currencyAmount: string + methodName: string } export interface MethodArguments { @@ -187,9 +180,9 @@ export const fetchPaperSecret = async ({ currency, currencyAmount, methodName, - recipientAddress, + recipientAddress }: FetchPaperSecretArgs) => { - const { network, apiClient } = await getNetworkConfigAndClients(chainId) + const { network, apiClient } = await getNetworkConfigAndClients(chainId) // @ts-ignore-next-line const chainName = getPaperNetworkName(network) @@ -203,24 +196,26 @@ export const fetchPaperSecret = async ({ args: methodArguments, payment: { currency, - value: `${currencyAmount} * $QUANTITY`, + value: `${currencyAmount} * $QUANTITY` }, - name: methodName, + name: methodName }, walletAddress: recipientAddress, - ...(collectionContractAddress ? { - contractArgs: { - collectionContractAddress - } - } : {}), + ...(collectionContractAddress + ? { + contractArgs: { + collectionContractAddress + } + } + : {}) }) const { secret } = await apiClient.paperSessionSecret2({ - chainName, - contractAddress, - abi, - paramsJson, + chainName, + contractAddress, + abi, + paramsJson }) return secret -} \ No newline at end of file +} diff --git a/packages/checkout/src/api/index.tsx b/packages/checkout/src/api/index.tsx index b7e2a5fa..7f165348 100644 --- a/packages/checkout/src/api/index.tsx +++ b/packages/checkout/src/api/index.tsx @@ -1 +1 @@ -export * from './data' \ No newline at end of file +export * from './data' diff --git a/packages/checkout/src/contexts/CheckoutModal.tsx b/packages/checkout/src/contexts/CheckoutModal.tsx index 19849c9e..2e3cbe9f 100644 --- a/packages/checkout/src/contexts/CheckoutModal.tsx +++ b/packages/checkout/src/contexts/CheckoutModal.tsx @@ -3,13 +3,13 @@ import { MethodArguments } from '../api' import { createGenericContext, Theme } from '@0xsequence/kit' interface CoinQuantity { - contractAddress: string, - amountRequiredRaw: string, + contractAddress: string + amountRequiredRaw: string } interface OrderSummaryItem { - contractAddress: string, - quantityRaw: string, + contractAddress: string + quantityRaw: string tokenId: string } @@ -28,12 +28,12 @@ export interface CheckoutSettings { email?: string onSuccess?: (transactionHash: string) => void onError?: (error: Error) => void - }, + } cryptoCheckout?: { - chainId: number, - triggerTransaction: () => void, - coinQuantity: CoinQuantity, - }, + chainId: number + triggerTransaction: () => void + coinQuantity: CoinQuantity + } orderSummaryItems: OrderSummaryItem[] } @@ -44,4 +44,4 @@ type CheckoutModalContext = { theme: Theme } -export const [useCheckoutModalContext, CheckoutModalContextProvider] = createGenericContext() \ No newline at end of file +export const [useCheckoutModalContext, CheckoutModalContextProvider] = createGenericContext() diff --git a/packages/checkout/src/contexts/Navigation.tsx b/packages/checkout/src/contexts/Navigation.tsx index ba8bc6f7..5cab25ba 100644 --- a/packages/checkout/src/contexts/Navigation.tsx +++ b/packages/checkout/src/contexts/Navigation.tsx @@ -2,11 +2,11 @@ import React from 'react' import { createGenericContext } from '@0xsequence/kit' export interface SelectCheckoutNavigation { - location: 'select-method-checkout', + location: 'select-method-checkout' } export interface TransactionFormNavigation { - location: 'transaction-form', + location: 'transaction-form' } export interface TransactionSuccessParams { @@ -14,7 +14,7 @@ export interface TransactionSuccessParams { } export interface TransactionSuccessNavigation { - location: 'transaction-success', + location: 'transaction-success' params: TransactionSuccessParams } @@ -23,7 +23,7 @@ export interface TransactionErrorParams { } export interface TransactionErrorNavigation { - location: 'transaction-error', + location: 'transaction-error' params: TransactionErrorParams } @@ -32,17 +32,22 @@ export interface TransactionPendingParams { } export interface TransactionPendingNavigation { - location: 'transaction-pending', + location: 'transaction-pending' params: TransactionPendingParams } -export type Navigation = TransactionFormNavigation | TransactionSuccessNavigation | TransactionErrorNavigation | TransactionPendingNavigation | SelectCheckoutNavigation +export type Navigation = + | TransactionFormNavigation + | TransactionSuccessNavigation + | TransactionErrorNavigation + | TransactionPendingNavigation + | SelectCheckoutNavigation export type History = Navigation[] type NavigationContext = { setHistory: (history: History) => void - history: History, + history: History } -export const [useNavigationContext,NavigationContextProvider] = createGenericContext() \ No newline at end of file +export const [useNavigationContext, NavigationContextProvider] = createGenericContext() diff --git a/packages/checkout/src/contexts/index.ts b/packages/checkout/src/contexts/index.ts index 78b44f04..c61c68be 100644 --- a/packages/checkout/src/contexts/index.ts +++ b/packages/checkout/src/contexts/index.ts @@ -1,2 +1,2 @@ export * from './CheckoutModal' -export * from './Navigation' \ No newline at end of file +export * from './Navigation' diff --git a/packages/checkout/src/hooks/data.ts b/packages/checkout/src/hooks/data.ts index a1ed718c..57eecce7 100644 --- a/packages/checkout/src/hooks/data.ts +++ b/packages/checkout/src/hooks/data.ts @@ -11,7 +11,7 @@ import { GetCoinPricesArgs, fetchTokenMetadata, GetTokenMetadataArgs, - fetchContractInfo, + fetchContractInfo } from '../api/data' export const time = { @@ -46,7 +46,7 @@ export const useCoinPrices = (args: GetCoinPricesArgs): UseQueryResult 0 }) - + export const useTokenMetadata = (args: GetTokenMetadataArgs): UseQueryResult => useQuery({ queryKey: ['useTokenMetadata', args], @@ -63,4 +63,4 @@ export const useContractInfo = (args: GetContractInfoArgs): UseQueryResult { const { triggerCheckout, closeCheckout, settings } = useCheckoutModalContext() return { triggerCheckout, closeCheckout, settings } -} \ No newline at end of file +} diff --git a/packages/checkout/src/hooks/useModalTheme.tsx b/packages/checkout/src/hooks/useModalTheme.tsx index ddb033b5..1c6f7b85 100644 --- a/packages/checkout/src/hooks/useModalTheme.tsx +++ b/packages/checkout/src/hooks/useModalTheme.tsx @@ -5,4 +5,4 @@ export const useModalTheme = () => { const { theme } = useCheckoutModalContext() return theme -} \ No newline at end of file +} diff --git a/packages/checkout/src/hooks/useNavigation.tsx b/packages/checkout/src/hooks/useNavigation.tsx index f776974c..9607149a 100644 --- a/packages/checkout/src/hooks/useNavigation.tsx +++ b/packages/checkout/src/hooks/useNavigation.tsx @@ -3,22 +3,19 @@ import { useNavigationContext, Navigation, History } from '../contexts/Navigatio import { DEFAULT_LOCATION } from '../shared/components/KitCheckoutProvider' interface UseNavigation { - setNavigation: (navigation: Navigation) => void, + setNavigation: (navigation: Navigation) => void setHistory: (history: History) => void - history: History, + history: History goBack: () => void navigation: Navigation } export const useNavigation = (): UseNavigation => { - const { - setHistory, - history - } = useNavigationContext() + const { setHistory, history } = useNavigationContext() const setNavigation = (navigation: Navigation) => { // Scroll to top of page when navigating to a new page - const childElement = document.getElementById("sequence-kit-wallet-content") + const childElement = document.getElementById('sequence-kit-wallet-content') const parentElement = childElement?.parentElement parentElement?.scrollTo(0, 0) @@ -35,4 +32,4 @@ export const useNavigation = (): UseNavigation => { const navigation = history.length > 0 ? history[history.length - 1] : DEFAULT_LOCATION return { setNavigation, history, setHistory, goBack, navigation } -} \ No newline at end of file +} diff --git a/packages/checkout/src/shared/styles.css.ts b/packages/checkout/src/shared/styles.css.ts index 4a92c0a4..2c9d9a2d 100644 --- a/packages/checkout/src/shared/styles.css.ts +++ b/packages/checkout/src/shared/styles.css.ts @@ -1,14 +1,13 @@ import { style, globalStyle } from '@vanilla-extract/css' -export const walletContent = style({ -}) +export const walletContent = style({}) // Will affect the close button in the modal globalStyle(`${walletContent} + button`, { - backgroundColor: 'transparent', + backgroundColor: 'transparent' }) globalStyle(`${walletContent} + button > svg`, { width: '20px', height: '20px' -}) \ No newline at end of file +}) diff --git a/packages/checkout/src/utils/helpers.ts b/packages/checkout/src/utils/helpers.ts index ea71483d..fe731ef5 100644 --- a/packages/checkout/src/utils/helpers.ts +++ b/packages/checkout/src/utils/helpers.ts @@ -6,10 +6,7 @@ export const truncateAtMiddle = (text: string, truncateAt: number) => { let finalText = text if (text.length >= truncateAt) { - finalText = - text.slice(0, truncateAt / 2) + - '...' + - text.slice(text.length - truncateAt / 2, text.length) + finalText = text.slice(0, truncateAt / 2) + '...' + text.slice(text.length - truncateAt / 2, text.length) } return finalText @@ -51,10 +48,7 @@ export const formatDisplay = (_val: number | string): string => { } let notation: Intl.NumberFormatOptions['notation'] = undefined - let config: Pick< - Intl.NumberFormatOptions, - 'maximumFractionDigits' | 'maximumSignificantDigits' - > + let config: Pick switch (valMode) { case ValueType.VERY_LARGE: @@ -90,4 +84,4 @@ export const formatDisplay = (_val: number | string): string => { export const capitalize = (word: string) => { return word.charAt(0).toUpperCase() + word.slice(1) -} \ No newline at end of file +} diff --git a/packages/checkout/src/utils/index.ts b/packages/checkout/src/utils/index.ts index 6563fe28..c897b9cc 100644 --- a/packages/checkout/src/utils/index.ts +++ b/packages/checkout/src/utils/index.ts @@ -1,2 +1,2 @@ export * from './helpers' -export * from './networks' \ No newline at end of file +export * from './networks' diff --git a/packages/checkout/src/utils/networks.ts b/packages/checkout/src/utils/networks.ts index 5155f520..1c8a22f4 100644 --- a/packages/checkout/src/utils/networks.ts +++ b/packages/checkout/src/utils/networks.ts @@ -5,5 +5,5 @@ export const getPaperNetworkName = (network: NetworkConfig): string => { if (network.chainId === 1) { return 'Ethereum' } - return (capitalize(network.name)) + return capitalize(network.name) } diff --git a/packages/checkout/src/views/PaperTransactionForm.tsx b/packages/checkout/src/views/PaperTransactionForm.tsx index 3746fccd..de9bf244 100644 --- a/packages/checkout/src/views/PaperTransactionForm.tsx +++ b/packages/checkout/src/views/PaperTransactionForm.tsx @@ -1,8 +1,5 @@ import React, { useState } from 'react' -import { - Box, - Text, -} from '@0xsequence/design-system' +import { Box, Text } from '@0xsequence/design-system' import { useCheckoutModal } from '../hooks/useCheckoutModal' import { PaperTransaction } from '../shared/components/PaperTransaction' import { HEADER_HEIGHT } from '../constants' @@ -20,9 +17,7 @@ export const PaperTransactionForm = () => { marginTop: HEADER_HEIGHT }} > - {settings && ( - - )} + {settings && } ) -} \ No newline at end of file +} diff --git a/packages/checkout/src/views/PendingTransaction.tsx b/packages/checkout/src/views/PendingTransaction.tsx index 5af9e27a..b07e572f 100644 --- a/packages/checkout/src/views/PendingTransaction.tsx +++ b/packages/checkout/src/views/PendingTransaction.tsx @@ -8,7 +8,9 @@ const POLLING_TIME = 10 * 1000 export const PendingTransaction = () => { const nav = useNavigation() - const { params: { transactionId } } = nav.navigation as TransactionPendingNavigation + const { + params: { transactionId } + } = nav.navigation as TransactionPendingNavigation const { setNavigation } = nav const paperGetStatusUrl = `https://withpaper.com/api/v1/transaction-status/${transactionId}` @@ -31,31 +33,34 @@ export const PendingTransaction = () => { return } if (status === 'TRANSFER_SUCCEEDED') { - setNavigation && setNavigation({ - location: 'transaction-success', - params: { - transactionHash, - } - }) + setNavigation && + setNavigation({ + location: 'transaction-success', + params: { + transactionHash + } + }) return } if (status === 'TRANSFER_FAILED' || status === 'PAYMENT_FAILED') { - setNavigation && setNavigation({ - location: 'transaction-error', - params: { - error: new Error('Failed to transfer collectible'), - } - }) + setNavigation && + setNavigation({ + location: 'transaction-error', + params: { + error: new Error('Failed to transfer collectible') + } + }) return } } catch (e) { console.error('An error occurred while fetching the transaction status') - setNavigation && setNavigation({ - location: 'transaction-error', - params: { - error: e, - } - }) + setNavigation && + setNavigation({ + location: 'transaction-error', + params: { + error: e + } + }) } } @@ -83,9 +88,10 @@ export const PendingTransaction = () => { > - Transaction in progress.
This may take a few minutes. + Transaction in progress.
+ This may take a few minutes.
) -} \ No newline at end of file +} diff --git a/packages/checkout/src/views/TransactionError.tsx b/packages/checkout/src/views/TransactionError.tsx index cc2a98aa..e4de24ab 100644 --- a/packages/checkout/src/views/TransactionError.tsx +++ b/packages/checkout/src/views/TransactionError.tsx @@ -22,7 +22,7 @@ export const TransactionError = () => { flexDirection="column" alignItems="center" position="absolute" - style={{top: '50%', right: '50%', transform: 'translate(50%, -50%)'}} + style={{ top: '50%', right: '50%', transform: 'translate(50%, -50%)' }} > Error @@ -31,7 +31,7 @@ export const TransactionError = () => { - ) + ) } export const NotificationErrorIcon = () => ( diff --git a/packages/checkout/src/views/TransactionSuccess.tsx b/packages/checkout/src/views/TransactionSuccess.tsx index 83d690c4..cbca6a7e 100644 --- a/packages/checkout/src/views/TransactionSuccess.tsx +++ b/packages/checkout/src/views/TransactionSuccess.tsx @@ -8,7 +8,7 @@ export const TransactionSuccess = () => { const { closeCheckout, settings } = useCheckoutModal() const nav = useNavigation() const navigation = nav.navigation as TransactionSuccessNavigation - + useEffect(() => { setTimeout(() => { closeCheckout() @@ -22,7 +22,7 @@ export const TransactionSuccess = () => { flexDirection="column" alignItems="center" position="absolute" - style={{top: '50%', right: '50%', transform: 'translate(50%, -50%)'}} + style={{ top: '50%', right: '50%', transform: 'translate(50%, -50%)' }} > Success! @@ -31,7 +31,7 @@ export const TransactionSuccess = () => { - ) + ) } export const NotificationSuccessIcon = () => ( diff --git a/packages/checkout/src/views/index.ts b/packages/checkout/src/views/index.ts index fb803ecf..ba584db6 100644 --- a/packages/checkout/src/views/index.ts +++ b/packages/checkout/src/views/index.ts @@ -2,4 +2,4 @@ export * from './PaperTransactionForm' export * from './PendingTransaction' export * from './TransactionSuccess' export * from './TransactionError' -export * from './CheckoutSelection' \ No newline at end of file +export * from './CheckoutSelection' diff --git a/packages/kit/src/components/index.tsx b/packages/kit/src/components/index.tsx index 51848fe9..65e177e3 100644 --- a/packages/kit/src/components/index.tsx +++ b/packages/kit/src/components/index.tsx @@ -1 +1 @@ -export * from './KitProvider' \ No newline at end of file +export * from './KitProvider' diff --git a/packages/kit/src/components/styles.css.ts b/packages/kit/src/components/styles.css.ts index ba0391ab..795c1cb9 100644 --- a/packages/kit/src/components/styles.css.ts +++ b/packages/kit/src/components/styles.css.ts @@ -18,27 +18,26 @@ export const clickable = style({ } }) -export const walletLogoContainer = style({}) +export const walletLogoContainer = style({}) -globalStyle (`${walletLogoContainer} svg`, { +globalStyle(`${walletLogoContainer} svg`, { height: '40px' }) -export const walletLogoContainerExtended = style({}) +export const walletLogoContainerExtended = style({}) -globalStyle (`${walletLogoContainerExtended} svg`, { +globalStyle(`${walletLogoContainerExtended} svg`, { width: '30px' }) -export const walletContent = style({ -}) +export const walletContent = style({}) // Will affect the close button in the modal globalStyle(`${walletContent} + button`, { - backgroundColor: 'transparent', + backgroundColor: 'transparent' }) globalStyle(`${walletContent} + button > svg`, { width: '20px', height: '20px' -}) \ No newline at end of file +}) diff --git a/packages/kit/src/constants/defaultSignInOptions.ts b/packages/kit/src/constants/defaultSignInOptions.ts index 55b18f3c..9e7d5b7b 100644 --- a/packages/kit/src/constants/defaultSignInOptions.ts +++ b/packages/kit/src/constants/defaultSignInOptions.ts @@ -2,4 +2,4 @@ export const defaultSignInOptions = { showEmailInput: true, walletAuthOptions: ['sequence', 'metamask', 'wallet-connect', 'coinbase-wallet'], socialAuthOptions: ['google', 'facebook', 'twitch', 'apple'] -} \ No newline at end of file +} diff --git a/packages/kit/src/constants/index.ts b/packages/kit/src/constants/index.ts index 05518883..3757d94b 100644 --- a/packages/kit/src/constants/index.ts +++ b/packages/kit/src/constants/index.ts @@ -1,3 +1,3 @@ export * from './localStorage' export * from './defaultSignInOptions' -export * from './ethAuth' \ No newline at end of file +export * from './ethAuth' diff --git a/packages/kit/src/contexts/Analytics.tsx b/packages/kit/src/contexts/Analytics.tsx index 2b69e5c6..48886ebb 100644 --- a/packages/kit/src/contexts/Analytics.tsx +++ b/packages/kit/src/contexts/Analytics.tsx @@ -1,12 +1,12 @@ -import { SequenceClient } from '0xsequence/dist/declarations/src/provider'; +import { SequenceClient } from '0xsequence/dist/declarations/src/provider' import React from 'react' import { createGenericContext } from '../utils' type AnalyticsContext = { - setAnalytics: React.Dispatch> - analytics: SequenceClient["analytics"] + setAnalytics: React.Dispatch> + analytics: SequenceClient['analytics'] } const [useAnalyticsContext, AnalyticsContextProvider] = createGenericContext() -export { useAnalyticsContext, AnalyticsContextProvider } \ No newline at end of file +export { useAnalyticsContext, AnalyticsContextProvider } diff --git a/packages/kit/src/contexts/ConnectModal.tsx b/packages/kit/src/contexts/ConnectModal.tsx index 04e7352c..42de3ac1 100644 --- a/packages/kit/src/contexts/ConnectModal.tsx +++ b/packages/kit/src/contexts/ConnectModal.tsx @@ -7,4 +7,4 @@ type ConnectModalContext = { } const [useConnectModalContext, ConnectModalContextProvider] = createGenericContext() -export { useConnectModalContext, ConnectModalContextProvider } \ No newline at end of file +export { useConnectModalContext, ConnectModalContextProvider } diff --git a/packages/kit/src/contexts/Theme.tsx b/packages/kit/src/contexts/Theme.tsx index 5177da5a..c18ed64a 100644 --- a/packages/kit/src/contexts/Theme.tsx +++ b/packages/kit/src/contexts/Theme.tsx @@ -4,9 +4,9 @@ import { createGenericContext, ModalPosition } from '../utils' type ThemeContext = { setTheme: React.Dispatch> - theme: Theme, - position: ModalPosition, + theme: Theme + position: ModalPosition setPosition: React.Dispatch> } -export const [useThemeContext, ThemeContextProvider] = createGenericContext() \ No newline at end of file +export const [useThemeContext, ThemeContextProvider] = createGenericContext() diff --git a/packages/kit/src/contexts/WalletSettings.tsx b/packages/kit/src/contexts/WalletSettings.tsx index f431e338..e5ace070 100644 --- a/packages/kit/src/contexts/WalletSettings.tsx +++ b/packages/kit/src/contexts/WalletSettings.tsx @@ -4,7 +4,7 @@ import { DisplayedAsset } from '../components/KitProvider' type WalletConfigContext = { setDisplayedAssets: React.Dispatch> - displayedAssets: DisplayedAsset[], + displayedAssets: DisplayedAsset[] } export const [useWalletConfigContext, WalletConfigContextProvider] = createGenericContext() diff --git a/packages/kit/src/contexts/index.ts b/packages/kit/src/contexts/index.ts index 9ed28841..d11f949c 100644 --- a/packages/kit/src/contexts/index.ts +++ b/packages/kit/src/contexts/index.ts @@ -1,4 +1,4 @@ export * from './Analytics' export * from './ConnectModal' export * from './Theme' -export * from './WalletSettings' \ No newline at end of file +export * from './WalletSettings' diff --git a/packages/kit/src/hooks/index.ts b/packages/kit/src/hooks/index.ts index 4fdd6174..bb917a5b 100644 --- a/packages/kit/src/hooks/index.ts +++ b/packages/kit/src/hooks/index.ts @@ -1,3 +1,3 @@ export * from './useOpenConnectModal' export * from './useTheme' -export * from './useWalletSettings' \ No newline at end of file +export * from './useWalletSettings' diff --git a/packages/kit/src/hooks/useOpenConnectModal.tsx b/packages/kit/src/hooks/useOpenConnectModal.tsx index a80512ad..92fc9c51 100644 --- a/packages/kit/src/hooks/useOpenConnectModal.tsx +++ b/packages/kit/src/hooks/useOpenConnectModal.tsx @@ -5,4 +5,4 @@ export const useOpenConnectModal = () => { const { setOpenConnectModal, openConnectModalState } = useConnectModalContext() return { setOpenConnectModal, openConnectModalState } -} \ No newline at end of file +} diff --git a/packages/kit/src/hooks/useWalletSettings.tsx b/packages/kit/src/hooks/useWalletSettings.tsx index 5553f7e8..8942460a 100644 --- a/packages/kit/src/hooks/useWalletSettings.tsx +++ b/packages/kit/src/hooks/useWalletSettings.tsx @@ -6,6 +6,6 @@ export const useWalletSettings = () => { return { displayedAssets, - setDisplayedAssets, + setDisplayedAssets } -} \ No newline at end of file +} diff --git a/packages/kit/src/utils/adapters.ts b/packages/kit/src/utils/adapters.ts index c2208952..babfe4d0 100644 --- a/packages/kit/src/utils/adapters.ts +++ b/packages/kit/src/utils/adapters.ts @@ -1,13 +1,12 @@ import { providers } from 'ethers' import { type HttpTransport, Account, Chain, Client, Transport } from 'viem' - export function walletClientToSigner(walletClient: Client) { const { account, chain, transport } = walletClient const network = { chainId: chain.id, name: chain.name, - ensAddress: chain.contracts?.ensRegistry?.address, + ensAddress: chain.contracts?.ensRegistry?.address } const provider = new providers.Web3Provider(transport, network) const signer = provider.getSigner(account.address) @@ -19,13 +18,11 @@ export function publicClientToProvider(publicClient: Client) { const network = { chainId: chain.id, name: chain.name, - ensAddress: chain.contracts?.ensRegistry?.address, + ensAddress: chain.contracts?.ensRegistry?.address } if (transport.type === 'fallback') return new providers.FallbackProvider( - (transport.transports as ReturnType[]).map( - ({ value }) => new providers.JsonRpcProvider(value?.url, network), - ), + (transport.transports as ReturnType[]).map(({ value }) => new providers.JsonRpcProvider(value?.url, network)) ) return new providers.JsonRpcProvider(transport.url, network) -} \ No newline at end of file +} diff --git a/packages/kit/src/utils/clients.ts b/packages/kit/src/utils/clients.ts index 3c821796..3c351dcc 100644 --- a/packages/kit/src/utils/clients.ts +++ b/packages/kit/src/utils/clients.ts @@ -7,7 +7,7 @@ import { LocalStorageKey } from '../constants' export const getNetworkConfigAndClients = (chainID: number | string) => { const network = networks[chainID as ChainId] - + if (!network) { throw 'invalid network' } diff --git a/packages/kit/src/utils/ethAuth.tsx b/packages/kit/src/utils/ethAuth.tsx index 053267a2..4ab4b77f 100644 --- a/packages/kit/src/utils/ethAuth.tsx +++ b/packages/kit/src/utils/ethAuth.tsx @@ -1,14 +1,14 @@ import { ethers } from 'ethers' -import { ETHAuthProof } from "@0xsequence/auth" -import { ETHAuth, Proof, } from '@0xsequence/ethauth' +import { ETHAuthProof } from '@0xsequence/auth' +import { ETHAuth, Proof } from '@0xsequence/ethauth' import { sequence } from '0xsequence' import { UsePublicClientReturnType } from 'wagmi' import { GetWalletClientData } from 'wagmi/query' import { publicClientToProvider, walletClientToSigner } from './adapters' -import { LocalStorageKey, DEFAULT_SESSION_EXPIRATION } from "../constants" -import { EthAuthSettings } from "../components/KitProvider" +import { LocalStorageKey, DEFAULT_SESSION_EXPIRATION } from '../constants' +import { EthAuthSettings } from '../components/KitProvider' export const signEthAuthProof = async (walletClient: GetWalletClientData): Promise => { const proofInformation = localStorage.getItem(LocalStorageKey.EthAuthProof) @@ -43,25 +43,23 @@ export const signEthAuthProof = async (walletClient: GetWalletClientData, publicClient: UsePublicClientReturnType, - proof: ETHAuthProof, + proof: ETHAuthProof ): Promise => { const walletAddress = walletClient.account.address const ethAuth = new ETHAuth() @@ -69,12 +67,7 @@ export const validateEthProof = async ( const decodedProof = await ethAuth.decodeProof(proof.proofString, true) const provider = publicClientToProvider(publicClient) - const isValid = await sequence.utils.isValidTypedDataSignature( - walletAddress, - proof.typedData, - decodedProof.signature, - provider, - ) + const isValid = await sequence.utils.isValidTypedDataSignature(walletAddress, proof.typedData, decodedProof.signature, provider) return isValid -} \ No newline at end of file +} diff --git a/packages/kit/src/utils/genericContext.tsx b/packages/kit/src/utils/genericContext.tsx index a641f64c..e097feea 100644 --- a/packages/kit/src/utils/genericContext.tsx +++ b/packages/kit/src/utils/genericContext.tsx @@ -1,19 +1,19 @@ -import React from "react"; +import React from 'react' // https://medium.com/@rivoltafilippo/typing-react-context-to-avoid-an-undefined-default-value-2c7c5a7d5947 export const createGenericContext = () => { // Create a context with a generic parameter or undefined - const genericContext = React.createContext(undefined); + const genericContext = React.createContext(undefined) // Check if the value provided to the context is defined or throw an error const useGenericContext = () => { - const contextIsDefined = React.useContext(genericContext); + const contextIsDefined = React.useContext(genericContext) if (!contextIsDefined) { - throw new Error("useGenericContext must be used within a Provider"); + throw new Error('useGenericContext must be used within a Provider') } - return contextIsDefined; - }; + return contextIsDefined + } - return [useGenericContext, genericContext.Provider] as const; -}; + return [useGenericContext, genericContext.Provider] as const +} diff --git a/packages/kit/src/utils/getKitConnectWallets.ts b/packages/kit/src/utils/getKitConnectWallets.ts index 6686ad89..2c54eee2 100644 --- a/packages/kit/src/utils/getKitConnectWallets.ts +++ b/packages/kit/src/utils/getKitConnectWallets.ts @@ -4,15 +4,15 @@ import { CreateConnectorFn } from 'wagmi' import { LocalStorageKey } from '../constants' export interface WalletProperties { - id: string, - logoDark: React.FunctionComponent, - logoLight: React.FunctionComponent, - monochromeLogoDark?: React.FunctionComponent, - monochromeLogoLight?: React.FunctionComponent, - name: string, - iconBackground?: string, - hideConnectorId?: string | null, - isSequenceBased?: boolean, + id: string + logoDark: React.FunctionComponent + logoLight: React.FunctionComponent + monochromeLogoDark?: React.FunctionComponent + monochromeLogoLight?: React.FunctionComponent + name: string + iconBackground?: string + hideConnectorId?: string | null + isSequenceBased?: boolean } export type Wallet = WalletProperties & { @@ -21,11 +21,11 @@ export type Wallet = WalletProperties & { export interface WalletField { _wallet: WalletProperties -} +} export type ExtendedConnector = CreateConnectorFn & WalletField -export const getKitConnectWallets = (projectAccessKey:string, wallets: any[]): CreateConnectorFn[] => { +export const getKitConnectWallets = (projectAccessKey: string, wallets: any[]): CreateConnectorFn[] => { localStorage.setItem(LocalStorageKey.ProjectAccessKey, projectAccessKey) const connectors: CreateConnectorFn[] = [] @@ -47,4 +47,4 @@ export const getKitConnectWallets = (projectAccessKey:string, wallets: any[]): C }) return connectors -} \ No newline at end of file +} diff --git a/packages/kit/src/utils/helpers.ts b/packages/kit/src/utils/helpers.ts index 32fccedd..fe415e89 100644 --- a/packages/kit/src/utils/helpers.ts +++ b/packages/kit/src/utils/helpers.ts @@ -1,3 +1,3 @@ export const isEmailValid = (email: string) => { return /^\S+@\S+\.\S{2,}$/.test(email) -} \ No newline at end of file +} diff --git a/packages/kit/src/utils/index.ts b/packages/kit/src/utils/index.ts index 98ffe685..f7fc1960 100644 --- a/packages/kit/src/utils/index.ts +++ b/packages/kit/src/utils/index.ts @@ -6,4 +6,4 @@ export * from './styling' export * from './networks' export * from './adapters' export * from './ethAuth' -export * from './clients' \ No newline at end of file +export * from './clients' diff --git a/packages/kit/src/utils/networks.ts b/packages/kit/src/utils/networks.ts index 2ae1df6f..7529c94d 100644 --- a/packages/kit/src/utils/networks.ts +++ b/packages/kit/src/utils/networks.ts @@ -1,7 +1,4 @@ -export const getChainColor = ( - chainId: number, - mode: 'dark' | 'light' = 'light' -) => { +export const getChainColor = (chainId: number, mode: 'dark' | 'light' = 'light') => { switch (chainId) { case 1: return mode === 'light' ? '#abf' : '#abf' @@ -26,12 +23,9 @@ export const getChainColor = ( } } -export const getChainBGColor = ( - chainId: number, - mode: 'dark' | 'light' = 'light' -) => { +export const getChainBGColor = (chainId: number, mode: 'dark' | 'light' = 'light') => { switch (chainId) { - case 1: + case 1: return mode === 'light' ? '#132362' : '#132362' case 137: return mode === 'light' ? '#350881' : '#350881' diff --git a/packages/kit/src/utils/styling.ts b/packages/kit/src/utils/styling.ts index ae5e875f..666970c9 100644 --- a/packages/kit/src/utils/styling.ts +++ b/packages/kit/src/utils/styling.ts @@ -1,5 +1,13 @@ -export type ModalPosition = 'center' | 'middle-right' | 'middle-left' | 'top-center' | 'top-right' | 'top-left' | 'bottom-center' | 'bottom-right' | 'bottom-left' - +export type ModalPosition = + | 'center' + | 'middle-right' + | 'middle-left' + | 'top-center' + | 'top-right' + | 'top-left' + | 'bottom-center' + | 'bottom-right' + | 'bottom-left' export interface modalPositionCss { top?: string @@ -9,7 +17,7 @@ export interface modalPositionCss { } export const getModalPositionCss = (position: ModalPosition) => { - switch(position) { + switch (position) { case 'top-right': return { top: '0px', @@ -22,7 +30,7 @@ export const getModalPositionCss = (position: ModalPosition) => { } case 'top-center': return { - top: '0px', + top: '0px' } case 'bottom-right': return { @@ -36,19 +44,18 @@ export const getModalPositionCss = (position: ModalPosition) => { } case 'bottom-center': return { - bottom: '0px', + bottom: '0px' } case 'middle-right': return { - right: '0px', + right: '0px' } case 'middle-left': return { - left: '0px', + left: '0px' } case 'center': default: return {} } - } diff --git a/packages/kit/src/utils/tokens.ts b/packages/kit/src/utils/tokens.ts index 7aef68f3..d1169307 100644 --- a/packages/kit/src/utils/tokens.ts +++ b/packages/kit/src/utils/tokens.ts @@ -1,10 +1,10 @@ import { Chain } from 'wagmi/chains' export interface NativeTokenInfo { - name: string, - symbol: string, - logoURI: string, - decimals: number, + name: string + symbol: string + logoURI: string + decimals: number blockExplorerUrl: string blockExplorerName: string } @@ -28,7 +28,7 @@ export const nativeTokenInfos: TokenInfos = { decimals: 18, logoURI: 'https://assets.coingecko.com/coins/images/279/thumb/ethereum.png', blockExplorerName: 'Etherscan (Goerli)', - blockExplorerUrl: 'https://goerli.etherscan.io', + blockExplorerUrl: 'https://goerli.etherscan.io' }, 10: { name: 'Optimism', @@ -36,7 +36,7 @@ export const nativeTokenInfos: TokenInfos = { logoURI: 'https://assets.coingecko.com/coins/images/25244/small/Optimism.png', decimals: 18, blockExplorerName: 'Etherscan (Optimism)', - blockExplorerUrl: 'https://optimistic.etherscan.io', + blockExplorerUrl: 'https://optimistic.etherscan.io' }, 56: { name: 'BNB', @@ -52,7 +52,7 @@ export const nativeTokenInfos: TokenInfos = { logoURI: 'https://assets.coingecko.com/coins/images/662/small/logo_square_simple_300px.png', decimals: 18, blockExplorerUrl: 'https://gnosisscan.io', - blockExplorerName: 'Gnosis Scan', + blockExplorerName: 'Gnosis Scan' }, 137: { name: 'Polygon', @@ -68,16 +68,15 @@ export const nativeTokenInfos: TokenInfos = { logoURI: 'https://assets.coingecko.com/coins/images/4713/thumb/matic-token-icon.png', decimals: 18, blockExplorerName: 'PolygonScan', - blockExplorerUrl: 'https://zkevm.polygonscan.com', + blockExplorerUrl: 'https://zkevm.polygonscan.com' }, 42161: { name: 'Arbitrum', symbol: 'ARB', - logoURI:'https://assets.coingecko.com/asset_platforms/images/33/small/arbitrum-one.png', + logoURI: 'https://assets.coingecko.com/asset_platforms/images/33/small/arbitrum-one.png', decimals: 18, blockExplorerName: 'Arbiscan', - blockExplorerUrl: 'https://arbiscan.io', - + blockExplorerUrl: 'https://arbiscan.io' }, 43114: { name: 'Avalanche', @@ -93,16 +92,15 @@ export const nativeTokenInfos: TokenInfos = { logoURI: 'https://assets.coingecko.com/coins/images/4713/thumb/matic-token-icon.png', decimals: 18, blockExplorerName: 'Polyscan (Mumbai)', - blockExplorerUrl: 'https://mumbai.polygonscan.com', - }, + blockExplorerUrl: 'https://mumbai.polygonscan.com' + } } export const getChainIdList = () => { return Object.keys(nativeTokenInfos).map(chainId => parseInt(chainId)) } - -export const defaultNativeTokenInfo = (chainId: number, wagmiChains: readonly [Chain, ...Chain[]] ) => { +export const defaultNativeTokenInfo = (chainId: number, wagmiChains: readonly [Chain, ...Chain[]]) => { const foundChain = wagmiChains.find(chain => chain.id === chainId) if (foundChain) { @@ -121,4 +119,4 @@ export const defaultNativeTokenInfo = (chainId: number, wagmiChains: readonly [C export const getNativeTokenInfoByChainId = (chainId: number, wagmiChains: readonly [Chain, ...Chain[]]) => { return nativeTokenInfos[chainId] || defaultNativeTokenInfo(chainId, wagmiChains) || nativeTokenInfos[1] -} \ No newline at end of file +} diff --git a/packages/wallet/src/api/data.tsx b/packages/wallet/src/api/data.tsx index 2bc4d464..26e99e55 100644 --- a/packages/wallet/src/api/data.tsx +++ b/packages/wallet/src/api/data.tsx @@ -8,17 +8,17 @@ import { compareAddress, sortBalancesByType } from '../utils' import sampleSize from 'lodash/sampleSize' export interface GetTokenBalancesArgs { - accountAddress: string, - chainId: number, + accountAddress: string + chainId: number contractAddress?: string } export const getNativeToken = async ({ accountAddress, chainId }: GetTokenBalancesArgs) => { try { - const { indexerClient } = await getNetworkConfigAndClients(chainId) + const { indexerClient } = await getNetworkConfigAndClients(chainId) const res = await indexerClient.getEtherBalance({ accountAddress }) - + const tokenBalance: TokenBalance = { chainId, contractAddress: ethers.constants.AddressZero, @@ -27,10 +27,10 @@ export const getNativeToken = async ({ accountAddress, chainId }: GetTokenBalanc contractType: ContractType.UNKNOWN, blockHash: '', blockNumber: 0, - tokenID: '', + tokenID: '' } return [tokenBalance] - } catch(e) { + } catch (e) { console.error(e) return [] } @@ -44,37 +44,32 @@ export const getCoinPrices = async ({ tokens }: GetCoinPricesArgs) => { try { if (tokens.length === 0) return [] const chainId = tokens[0].chainId - + const { apiClient } = await getNetworkConfigAndClients(chainId) - + const res = await apiClient.getCoinPrices({ tokens }) return res?.tokenPrices || [] - } catch(e) { + } catch (e) { console.error(e) return } } export interface GetTokenBalancesOptions { - hideUnlistedTokens: boolean, - hideCollectibles?: boolean, + hideUnlistedTokens: boolean + hideCollectibles?: boolean includeMetadata?: boolean } -export const getTokenBalances = async ({ - accountAddress, - chainId, - contractAddress -}: GetTokenBalancesArgs, { - hideUnlistedTokens, - hideCollectibles, - includeMetadata = true, -}: GetTokenBalancesOptions) => { +export const getTokenBalances = async ( + { accountAddress, chainId, contractAddress }: GetTokenBalancesArgs, + { hideUnlistedTokens, hideCollectibles, includeMetadata = true }: GetTokenBalancesOptions +) => { try { - const { indexerClient } = await getNetworkConfigAndClients(chainId) + const { indexerClient } = await getNetworkConfigAndClients(chainId) const res = await indexerClient.getTokenBalances({ accountAddress, @@ -85,43 +80,46 @@ export const getTokenBalances = async ({ ...(contractAddress ? { contractAddress } : {}) }) - let returnedBalances = res?.balances || [] + let returnedBalances = res?.balances || [] if (hideUnlistedTokens && returnedBalances.length > 0) { - const coinPrices = await getCoinPrices({ tokens: returnedBalances.map(balance => ({ - chainId: balance.chainId, - contractAddress: balance.contractAddress, - tokenId: balance.tokenID + const coinPrices = await getCoinPrices({ + tokens: returnedBalances.map(balance => ({ + chainId: balance.chainId, + contractAddress: balance.contractAddress, + tokenId: balance.tokenID })) }) returnedBalances = returnedBalances.filter(balance => { - const price = coinPrices?.find(price => ( - compareAddress(price.token.contractAddress, balance.contractAddress) && - price.token.chainId === balance.chainId - )) + const price = coinPrices?.find( + price => compareAddress(price.token.contractAddress, balance.contractAddress) && price.token.chainId === balance.chainId + ) return balance.contractType !== 'ERC20' || (!!price && price.price !== null) }) } if (hideCollectibles && returnedBalances.length > 0) { - returnedBalances = returnedBalances.filter(balance => (balance.contractType !== 'ERC721' && balance.contractType !== 'ERC1155')) + returnedBalances = returnedBalances.filter( + balance => balance.contractType !== 'ERC721' && balance.contractType !== 'ERC1155' + ) } - + return returnedBalances - } catch(e) { + } catch (e) { console.error(e) return [] } } export interface FetchBalancesOptions { - hideUnlistedTokens: boolean, - hideCollectibles?: boolean, + hideUnlistedTokens: boolean + hideCollectibles?: boolean } export const fetchBalances = async ( { accountAddress, chainId }: GetTokenBalancesArgs, - { hideUnlistedTokens, hideCollectibles } : FetchBalancesOptions) => { + { hideUnlistedTokens, hideCollectibles }: FetchBalancesOptions +) => { try { const tokenBalances = ( await Promise.all([ @@ -129,23 +127,26 @@ export const fetchBalances = async ( accountAddress, chainId }), - getTokenBalances({ - accountAddress, - chainId, - }, { hideUnlistedTokens, hideCollectibles }) + getTokenBalances( + { + accountAddress, + chainId + }, + { hideUnlistedTokens, hideCollectibles } + ) ]) ).flat() return tokenBalances - } catch(e) { + } catch (e) { console.error(e) return [] } } export interface GetCollectionBalanceArgs { - accountAddress: string, - chainId: number, - collectionAddress: string, + accountAddress: string + chainId: number + collectionAddress: string includeMetadata?: boolean } @@ -153,10 +154,10 @@ export const fetchCollectionBalance = async ({ accountAddress, chainId, collectionAddress, - includeMetadata = true, + includeMetadata = true }: GetCollectionBalanceArgs) => { try { - const { indexerClient } = await getNetworkConfigAndClients(chainId) + const { indexerClient } = await getNetworkConfigAndClients(chainId) const res = await indexerClient.getTokenBalances({ accountAddress, @@ -166,17 +167,17 @@ export const fetchCollectionBalance = async ({ verifiedOnly: true } }) - + return res?.balances || [] - } catch(e) { + } catch (e) { console.error(e) return [] } } export interface FetchBalancesAssetsArgs { - accountAddress: string, - chainIds: number[], - displayAssets: DisplayedAsset[] + accountAddress: string + chainIds: number[] + displayAssets: DisplayedAsset[] } export interface FetchBalancesAssetsSummaryOptions { @@ -186,9 +187,10 @@ export interface FetchBalancesAssetsSummaryOptions { export const fetchBalancesAssetsSummary = async ( { accountAddress, chainIds, displayAssets }: FetchBalancesAssetsArgs, - { hideUnlistedTokens, hideCollectibles }: FetchBalancesAssetsSummaryOptions) => { + { hideUnlistedTokens, hideCollectibles }: FetchBalancesAssetsSummaryOptions +) => { const MAX_COLLECTIBLES_AMOUNTS = 10 - + let tokenBalances: TokenBalance[] = [] const customDisplayAssets = displayAssets.length > 0 @@ -221,29 +223,46 @@ export const fetchBalancesAssetsSummary = async ( tokenBalances = ( await Promise.all([ - ...Object.keys(nativeTokensByChainId).map(chainId => getNativeToken({ - accountAddress, - chainId: Number(chainId) - })), - ...Object.keys(otherAssetsByChainId).map(chainId => otherAssetsByChainId[Number(chainId)].map(asset => getTokenBalances({ + ...Object.keys(nativeTokensByChainId).map(chainId => + getNativeToken({ accountAddress, - chainId: Number(chainId), - contractAddress: asset.contractAddress - }, { hideUnlistedTokens, hideCollectibles, includeMetadata: false } - ))).flat() + chainId: Number(chainId) + }) + ), + ...Object.keys(otherAssetsByChainId) + .map(chainId => + otherAssetsByChainId[Number(chainId)].map(asset => + getTokenBalances( + { + accountAddress, + chainId: Number(chainId), + contractAddress: asset.contractAddress + }, + { hideUnlistedTokens, hideCollectibles, includeMetadata: false } + ) + ) + ) + .flat() ]) ).flat() } else { tokenBalances = ( await Promise.all([ - ...chainIds.map(chainId => getNativeToken({ - accountAddress, - chainId - })), - ...chainIds.map(chainId => getTokenBalances({ - accountAddress, - chainId, - }, { hideUnlistedTokens, hideCollectibles, includeMetadata: false })) + ...chainIds.map(chainId => + getNativeToken({ + accountAddress, + chainId + }) + ), + ...chainIds.map(chainId => + getTokenBalances( + { + accountAddress, + chainId + }, + { hideUnlistedTokens, hideCollectibles, includeMetadata: false } + ) + ) ]) ).flat() } @@ -256,7 +275,7 @@ export const fetchBalancesAssetsSummary = async ( chainId: token.chainId, contractAddress: token.contractAddress })) - const prices = await getCoinPrices({ tokens }) || [] + const prices = (await getCoinPrices({ tokens })) || [] resolve(prices) } else { resolve([]) @@ -301,18 +320,22 @@ export const fetchBalancesAssetsSummary = async ( const contractInfoPromises = Object.keys(erc20BalanceByChainId).map(async chainId => { const { metadataClient } = getNetworkConfigAndClients(chainId) const tokenBalances = erc20BalanceByChainId[Number(chainId)] - const contractAddresses = tokenBalances.map(balance => balance.contractAddress) + const contractAddresses = tokenBalances.map(balance => balance.contractAddress) const result = await metadataClient.getContractInfoBatch({ chainID: String(chainId), contractAddresses }) contractInfoMapByChainId[Number(chainId)] = result }) - await Promise.all([...contractInfoPromises]) + await Promise.all([...contractInfoPromises]) return contractInfoMapByChainId } - const [prices, contractInfoMapByChainId, ...collectionCollectibles] = await Promise.all([fetchPricesPromise, fetchErc20ContractInfoPromise(), ...fetchCollectiblesPromises]) + const [prices, contractInfoMapByChainId, ...collectionCollectibles] = await Promise.all([ + fetchPricesPromise, + fetchErc20ContractInfoPromise(), + ...fetchCollectiblesPromises + ]) const erc20HighestValue = erc20Tokens.sort((a, b) => { const aPriceData = prices.find(price => compareAddress(price.token.contractAddress, a.contractAddress)) @@ -325,28 +348,26 @@ export const fetchBalancesAssetsSummary = async ( const bDecimals = contractInfoMapByChainId[b.chainId].contractInfoMap[b.contractAddress]?.decimals const aFormattedBalance = aDecimals === undefined ? 0 : Number(ethers.utils.formatUnits(a.balance, aDecimals)) - const bFormattedBalance = bDecimals === undefined ? 0 : Number(ethers.utils.formatUnits(b.balance, bDecimals)) + const bFormattedBalance = bDecimals === undefined ? 0 : Number(ethers.utils.formatUnits(b.balance, bDecimals)) - const aValue =aFormattedBalance * aPrice + const aValue = aFormattedBalance * aPrice const bValue = bFormattedBalance * bPrice return bValue - aValue }) - const collectibles: TokenBalance[] = sampleSize(collectionCollectibles.flat(), MAX_COLLECTIBLES_AMOUNTS).sort( - (a, b) => { - return a.contractAddress.localeCompare(b.contractAddress) - } - ) + const collectibles: TokenBalance[] = sampleSize(collectionCollectibles.flat(), MAX_COLLECTIBLES_AMOUNTS).sort((a, b) => { + return a.contractAddress.localeCompare(b.contractAddress) + }) if (hideCollectibles) { const summaryBalances: TokenBalance[] = [ ...(nativeTokens.length > 0 ? [nativeTokens[0]] : []), // the spots normally occupied by collectibles will be filled by erc20 tokens - ...(erc20HighestValue.length > 0 ? erc20HighestValue.slice(0, MAX_COLLECTIBLES_AMOUNTS + 1) : []), + ...(erc20HighestValue.length > 0 ? erc20HighestValue.slice(0, MAX_COLLECTIBLES_AMOUNTS + 1) : []) ] - - return summaryBalances + + return summaryBalances } const summaryBalances: TokenBalance[] = [ @@ -356,15 +377,15 @@ export const fetchBalancesAssetsSummary = async ( ] return summaryBalances - } catch(e) { + } catch (e) { console.error(e) return [] } } export interface GetCollectibleBalanceArgs { - accountAddress: string, - chainId: number, + accountAddress: string + chainId: number collectionAddress: string tokenId: string } @@ -375,7 +396,7 @@ export const getCollectibleBalance = async ({ collectionAddress, tokenId }: GetCollectibleBalanceArgs) => { - const { indexerClient } = await getNetworkConfigAndClients(chainId) + const { indexerClient } = await getNetworkConfigAndClients(chainId) const res = await indexerClient.getTokenBalances({ accountAddress, @@ -391,7 +412,6 @@ export const getCollectibleBalance = async ({ return tokenBalance } - export interface GetCollectiblePricesArgs { tokens: Token[] } @@ -400,24 +420,24 @@ export const getCollectiblePrices = async ({ tokens }: GetCollectiblePricesArgs) try { if (tokens.length === 0) return [] const chainId = tokens[0].chainId - + const { apiClient } = await getNetworkConfigAndClients(chainId) - + const res = await apiClient.getCollectiblePrices({ tokens }) return res?.tokenPrices || [] - } catch(e) { + } catch (e) { console.error(e) return } } export interface GetTransactionHistoryArgs { - chainId: number, - accountAddress: string, - contractAddress?: string, + chainId: number + accountAddress: string + contractAddress?: string tokenId?: string page?: Page } @@ -429,7 +449,7 @@ export const getTransactionHistory = async ({ tokenId, page }: GetTransactionHistoryArgs): Promise => { - const { indexerClient } = getNetworkConfigAndClients(chainId) + const { indexerClient } = getNetworkConfigAndClients(chainId) const response = indexerClient.getTransactionHistory({ includeMetadata: true, @@ -437,7 +457,7 @@ export const getTransactionHistory = async ({ filter: { accountAddress, contractAddress, - tokenID: tokenId, + tokenID: tokenId } }) @@ -445,25 +465,29 @@ export const getTransactionHistory = async ({ } export interface GetTransactionHistorySummaryArgs { - chainIds: number[], - accountAddress: string, + chainIds: number[] + accountAddress: string } export const getTransactionHistorySummary = async ({ chainIds, accountAddress }: GetTransactionHistorySummaryArgs): Promise => { - const histories = await Promise.all([...chainIds.map(chainId => getTransactionHistory({ - chainId, - accountAddress, - page: { - page: 1 - } - }))]) + const histories = await Promise.all([ + ...chainIds.map(chainId => + getTransactionHistory({ + chainId, + accountAddress, + page: { + page: 1 + } + }) + ) + ]) const unorderedTransactions = histories.map(history => history.transactions).flat() const orderedTransactions = unorderedTransactions.sort((a, b) => { - const firstDate = new Date(a.timestamp).getTime() + const firstDate = new Date(a.timestamp).getTime() const secondDate = new Date(b.timestamp).getTime() return secondDate - firstDate }) @@ -475,25 +499,23 @@ export interface FetchFiatConversionRateArgs { toCurrency: string } -export const fetchFiatConversionRate = async ({ - toCurrency -}: FetchFiatConversionRateArgs) => { +export const fetchFiatConversionRate = async ({ toCurrency }: FetchFiatConversionRateArgs) => { if (toCurrency === 'USD') { return 1 - } + } - const { apiClient } = getNetworkConfigAndClients(137) + const { apiClient } = getNetworkConfigAndClients(137) const response = await apiClient.getExchangeRate({ - toCurrency, + toCurrency }) return response.exchangeRate.value } interface Collectibles { - contractAddress: string, - chainId: number, + contractAddress: string + chainId: number tokenIds: string[] } @@ -501,10 +523,8 @@ export interface FetchTokenMetadataArgs { tokens: Collectibles } -export const fetchTokenMetadata = async ({ - tokens -}: FetchTokenMetadataArgs): Promise => { - const { metadataClient } = getNetworkConfigAndClients(tokens.chainId) +export const fetchTokenMetadata = async ({ tokens }: FetchTokenMetadataArgs): Promise => { + const { metadataClient } = getNetworkConfigAndClients(tokens.chainId) const response = await metadataClient.getTokenMetadata({ chainID: tokens.chainId.toString(), @@ -516,9 +536,9 @@ export const fetchTokenMetadata = async ({ } export const getContractInfo = async (args: GetContractInfoArgs): Promise => { - const { metadataClient } = getNetworkConfigAndClients(Number(args.chainID)) + const { metadataClient } = getNetworkConfigAndClients(Number(args.chainID)) const response = await metadataClient.getContractInfo(args) return response.contractInfo -} \ No newline at end of file +} diff --git a/packages/wallet/src/api/index.tsx b/packages/wallet/src/api/index.tsx index b7e2a5fa..7f165348 100644 --- a/packages/wallet/src/api/index.tsx +++ b/packages/wallet/src/api/index.tsx @@ -1 +1 @@ -export * from './data' \ No newline at end of file +export * from './data' diff --git a/packages/wallet/src/constants/abi.ts b/packages/wallet/src/constants/abi.ts index c02c0b00..184100b5 100644 --- a/packages/wallet/src/constants/abi.ts +++ b/packages/wallet/src/constants/abi.ts @@ -87,4 +87,4 @@ export const ERC_721_ABI = [ stateMutability: 'nonpayable', type: 'function' } -] \ No newline at end of file +] diff --git a/packages/wallet/src/constants/currency.ts b/packages/wallet/src/constants/currency.ts index b5b50aef..69359611 100644 --- a/packages/wallet/src/constants/currency.ts +++ b/packages/wallet/src/constants/currency.ts @@ -29,7 +29,7 @@ export const supportedFiatCurrencies: FiatCurrency[] = [ { symbol: 'DKK', sign: 'kr ', name: { message: 'Danish Krone' }, decimals: 2 }, { symbol: 'PLN', sign: 'zł ', name: { message: 'Polish Zloty' }, decimals: 2 }, { symbol: 'THB', sign: '฿', name: { message: 'Thai Baht' }, decimals: 2 }, - { symbol: 'IDR', sign: 'Rp', name: { message: 'Indonesian Rupiah' }, decimals: 2 }, + { symbol: 'IDR', sign: 'Rp', name: { message: 'Indonesian Rupiah' }, decimals: 2 } ] export const defaultFiatCurrency = supportedFiatCurrencies[0] diff --git a/packages/wallet/src/constants/index.ts b/packages/wallet/src/constants/index.ts index 60262795..2bf65e68 100644 --- a/packages/wallet/src/constants/index.ts +++ b/packages/wallet/src/constants/index.ts @@ -1,3 +1,3 @@ export * from './abi' export * from './currency' -export * from './sizing' \ No newline at end of file +export * from './sizing' diff --git a/packages/wallet/src/constants/sizing.ts b/packages/wallet/src/constants/sizing.ts index 6d698a2d..6ddd4dea 100644 --- a/packages/wallet/src/constants/sizing.ts +++ b/packages/wallet/src/constants/sizing.ts @@ -1,2 +1,2 @@ export const HEADER_HEIGHT = '54px' -export const SCROLLBAR_WIDTH = navigator.userAgent.match(/chrome|chromium|crios/i) ? '13px' : '0px' \ No newline at end of file +export const SCROLLBAR_WIDTH = navigator.userAgent.match(/chrome|chromium|crios/i) ? '13px' : '0px' diff --git a/packages/wallet/src/contexts/Navigation.tsx b/packages/wallet/src/contexts/Navigation.tsx index 579f4e85..9f4c2a74 100644 --- a/packages/wallet/src/contexts/Navigation.tsx +++ b/packages/wallet/src/contexts/Navigation.tsx @@ -8,18 +8,17 @@ export interface CollectionDetailsParams { } export interface CollectionDetailsNavigation { - location: 'collection-details', + location: 'collection-details' params: CollectionDetailsParams } - export interface CoinDetailsParams { contractAddress: string chainId: number } export interface CoinDetailsNavigation { - location: 'coin-details', + location: 'coin-details' params: CoinDetailsParams } @@ -30,7 +29,7 @@ export interface CollectibleDetailsParams { } export interface CollectibleDetailsNavigation { - location: 'collectible-details', + location: 'collectible-details' params: CollectibleDetailsParams } @@ -39,7 +38,7 @@ export interface TransactionDetailsParams { } export interface TransactionDetailsNavigation { - location: 'transaction-details', + location: 'transaction-details' params: TransactionDetailsParams } @@ -48,59 +47,59 @@ export interface SearchViewAllParams { } export interface SearchViewAllNavigation { - location: 'search-view-all', + location: 'search-view-all' params: SearchViewAllParams } export interface SendCoinParams { - chainId: number, - contractAddress: string, + chainId: number + contractAddress: string } export interface SendCoinNavigation { - location: 'send-coin', + location: 'send-coin' params: SendCoinParams } export interface SendCollectibleParams { - chainId: number, - contractAddress: string, - tokenId: string, + chainId: number + contractAddress: string + tokenId: string } export interface SendCollectibleNavigation { - location: 'send-collectible', + location: 'send-collectible' params: SendCollectibleParams } export interface BasicNavigation { location: - 'home' | - 'receive' | - 'history' | - 'receive' | - 'settings' | - 'settings-general' | - 'settings-currency' | - 'settings-networks' | - 'search' + | 'home' + | 'receive' + | 'history' + | 'receive' + | 'settings' + | 'settings-general' + | 'settings-currency' + | 'settings-networks' + | 'search' } export type Navigation = - BasicNavigation | - CoinDetailsNavigation | - CollectibleDetailsNavigation | - CollectionDetailsNavigation | - TransactionDetailsNavigation | - SearchViewAllNavigation | - SendCoinNavigation | - SendCollectibleNavigation + | BasicNavigation + | CoinDetailsNavigation + | CollectibleDetailsNavigation + | CollectionDetailsNavigation + | TransactionDetailsNavigation + | SearchViewAllNavigation + | SendCoinNavigation + | SendCollectibleNavigation export type History = Navigation[] type NavigationContext = { setHistory: (history: History) => void - history: History, + history: History } -export const [useNavigationContext, NavigationContextProvider] = createGenericContext() \ No newline at end of file +export const [useNavigationContext, NavigationContextProvider] = createGenericContext() diff --git a/packages/wallet/src/contexts/WalletModal.tsx b/packages/wallet/src/contexts/WalletModal.tsx index 38650293..f9cbce4c 100644 --- a/packages/wallet/src/contexts/WalletModal.tsx +++ b/packages/wallet/src/contexts/WalletModal.tsx @@ -6,4 +6,4 @@ type WalletModalContext = { openWalletModalState: boolean } -export const [useWalletModalContext,WalletModalContextProvider] = createGenericContext() \ No newline at end of file +export const [useWalletModalContext, WalletModalContextProvider] = createGenericContext() diff --git a/packages/wallet/src/contexts/index.ts b/packages/wallet/src/contexts/index.ts index 89d43fa3..73eb035f 100644 --- a/packages/wallet/src/contexts/index.ts +++ b/packages/wallet/src/contexts/index.ts @@ -1,2 +1,2 @@ export * from './WalletModal' -export * from './Navigation' \ No newline at end of file +export * from './Navigation' diff --git a/packages/wallet/src/hooks/data.ts b/packages/wallet/src/hooks/data.ts index c5ef1d91..e6ddc5e3 100644 --- a/packages/wallet/src/hooks/data.ts +++ b/packages/wallet/src/hooks/data.ts @@ -38,7 +38,7 @@ export const time = { oneHour: 60 * 60 * 1000 } -export interface UseBalancesArgs extends Omit { +export interface UseBalancesArgs extends Omit { chainIds: number[] } @@ -47,11 +47,7 @@ export const useBalances = (args: UseBalancesArgs, options: GetTokenBalancesOpti queryKey: ['balances', args, options], queryFn: async () => { const { chainIds, ...restArgs } = args - const balances = await Promise.all( - chainIds.map(chainId => ( - fetchBalances({...restArgs, chainId}, options) - )) - ) + const balances = await Promise.all(chainIds.map(chainId => fetchBalances({ ...restArgs, chainId }, options))) return balances.flat() }, retry: true, @@ -71,7 +67,7 @@ export const useCollectionBalance = (args: GetCollectionBalanceArgs) => export const useCoinPrices = ({ disabled, ...args -}: GetCoinPricesArgs & { disabled?: boolean } ): UseQueryResult => +}: GetCoinPricesArgs & { disabled?: boolean }): UseQueryResult => useQuery({ queryKey: ['coinPrices', args], queryFn: () => getCoinPrices(args), @@ -79,15 +75,15 @@ export const useCoinPrices = ({ staleTime: 1 * time.oneMinute, enabled: args.tokens.length > 0 && !disabled }) - -export const useBalancesAssetsSummary = (args: FetchBalancesAssetsArgs, options: GetTokenBalancesOptions) => ( + +export const useBalancesAssetsSummary = (args: FetchBalancesAssetsArgs, options: GetTokenBalancesOptions) => useQuery({ queryKey: ['balancesAssetsSummary', args, options], queryFn: () => fetchBalancesAssetsSummary(args, options), retry: true, staleTime: 10 * time.oneMinute, enabled: args.chainIds.length > 0 && !!args.accountAddress - })) + }) export const useCoinBalance = (args: GetTokenBalancesArgs, options: GetTokenBalancesOptions) => useQuery({ @@ -96,7 +92,7 @@ export const useCoinBalance = (args: GetTokenBalancesArgs, options: GetTokenBala if (compareAddress(args?.contractAddress || '', ethers.constants.AddressZero)) { const response = getNativeToken({ accountAddress: args.accountAddress, - chainId: args.chainId, + chainId: args.chainId }).then(response => response[0]) return response } @@ -106,25 +102,25 @@ export const useCoinBalance = (args: GetTokenBalancesArgs, options: GetTokenBala retry: true, staleTime: 1 * time.oneMinute, enabled: !!args.chainId && !!args.accountAddress -}) + }) -export const useCollectibleBalance = (args: GetCollectibleBalanceArgs) => ( +export const useCollectibleBalance = (args: GetCollectibleBalanceArgs) => useQuery({ queryKey: ['collectibleBalance', args], queryFn: () => getCollectibleBalance(args), retry: true, staleTime: 5 * time.oneMinute, enabled: !!args.chainId && !!args.accountAddress && !!args.collectionAddress && !!args.tokenId - })) + }) -export const useCollectiblePrices = (args: GetCollectiblePricesArgs) => ( +export const useCollectiblePrices = (args: GetCollectiblePricesArgs) => useQuery({ queryKey: ['useCollectiblePrices', args], queryFn: () => getCollectiblePrices(args), retry: true, staleTime: 5 * time.oneMinute, - enabled: args.tokens.length > 0 - })) + enabled: args.tokens.length > 0 + }) export const useTransactionHistory = ( arg: Omit & { disabled?: boolean } @@ -133,54 +129,52 @@ export const useTransactionHistory = ( queryKey: ['transactionHistory', arg], queryFn: ({ pageParam }: { pageParam?: number }) => { return getTransactionHistory({ - ...(arg as Omit ), - ...(pageParam ? { page: { page: pageParam } }: { page: { page: 1 } }), + ...(arg as Omit), + ...(pageParam ? { page: { page: pageParam } } : { page: { page: 1 } }) }) }, getNextPageParam: ({ page }) => { // Note: must return undefined instead of null to stop the infinite scroll if (!page.more) return undefined - return (page?.page || 1) + return page?.page || 1 }, retry: true, staleTime: 10 * time.oneMinute, enabled: !!arg.chainId && !arg.disabled && !!arg.accountAddress }) - export const useTransactionHistorySummary = ( - args: GetTransactionHistorySummaryArgs - ): UseQueryResult => - useQuery({ - queryKey: ['transactionHistorySummary', args], - queryFn: () => getTransactionHistorySummary(args), - retry: true, - staleTime: 10 * time.oneMinute, - enabled: args.chainIds.length > 0 && !!args.accountAddress - }) - -export const useConversionRate = (args: FetchFiatConversionRateArgs) => ( +export const useTransactionHistorySummary = (args: GetTransactionHistorySummaryArgs): UseQueryResult => + useQuery({ + queryKey: ['transactionHistorySummary', args], + queryFn: () => getTransactionHistorySummary(args), + retry: true, + staleTime: 10 * time.oneMinute, + enabled: args.chainIds.length > 0 && !!args.accountAddress + }) + +export const useConversionRate = (args: FetchFiatConversionRateArgs) => useQuery({ queryKey: ['useConversionRate', args], queryFn: () => fetchFiatConversionRate(args), retry: true, - staleTime: 60 * time.oneMinute, - })) + staleTime: 60 * time.oneMinute + }) -export const useTokenMetadata = (args: FetchTokenMetadataArgs): UseQueryResult => ( +export const useTokenMetadata = (args: FetchTokenMetadataArgs): UseQueryResult => useQuery({ queryKey: ['useTokenMetadata', args], queryFn: () => fetchTokenMetadata(args), retry: true, staleTime: 60 * time.oneMinute, enabled: !!args.tokens.chainId && !!args.tokens.contractAddress - })) + }) -export const useContractInfo = (args: GetContractInfoArgs): UseQueryResult => ( +export const useContractInfo = (args: GetContractInfoArgs): UseQueryResult => useQuery({ queryKey: ['useContractInfo', args], queryFn: () => getContractInfo(args), retry: true, staleTime: 60 * time.oneMinute, enabled: !!args.chainID && !!args.contractAddress - })) + }) diff --git a/packages/wallet/src/hooks/index.ts b/packages/wallet/src/hooks/index.ts index 6f452bd5..3ac07c07 100644 --- a/packages/wallet/src/hooks/index.ts +++ b/packages/wallet/src/hooks/index.ts @@ -1,4 +1,4 @@ export * from './useOpenWalletModal' export * from './data' export * from './useNavigation' -export * from './useSettings' \ No newline at end of file +export * from './useSettings' diff --git a/packages/wallet/src/hooks/useNavigation.tsx b/packages/wallet/src/hooks/useNavigation.tsx index f5d5a476..a9116cd7 100644 --- a/packages/wallet/src/hooks/useNavigation.tsx +++ b/packages/wallet/src/hooks/useNavigation.tsx @@ -3,21 +3,18 @@ import { useNavigationContext, Navigation, History } from '../contexts/Navigatio import { useOpenWalletModal } from './useOpenWalletModal' interface UseNavigation { - setNavigation: (navigation: Navigation) => void, + setNavigation: (navigation: Navigation) => void setHistory?: (history: History) => void - history: History, + history: History goBack: () => void } export const useNavigation = (): UseNavigation => { - const { - setHistory, - history - } = useNavigationContext() + const { setHistory, history } = useNavigationContext() const setNavigation = (navigation: Navigation) => { // Scroll to top of page when navigating to a new page - const childElement = document.getElementById("sequence-kit-wallet-content") + const childElement = document.getElementById('sequence-kit-wallet-content') const parentElement = childElement?.parentElement parentElement?.scrollTo(0, 0) @@ -32,4 +29,4 @@ export const useNavigation = (): UseNavigation => { } return { setNavigation, history, setHistory, goBack } -} \ No newline at end of file +} diff --git a/packages/wallet/src/hooks/useOpenWalletModal.tsx b/packages/wallet/src/hooks/useOpenWalletModal.tsx index d0cb5f57..df467944 100644 --- a/packages/wallet/src/hooks/useOpenWalletModal.tsx +++ b/packages/wallet/src/hooks/useOpenWalletModal.tsx @@ -4,5 +4,5 @@ import { useWalletModalContext } from '../contexts/WalletModal' export const useOpenWalletModal = () => { const { setOpenWalletModal, openWalletModalState } = useWalletModalContext() - return { setOpenWalletModal, openWalletModalState} -} \ No newline at end of file + return { setOpenWalletModal, openWalletModalState } +} diff --git a/packages/wallet/src/hooks/useSettings.tsx b/packages/wallet/src/hooks/useSettings.tsx index 628fcab0..29849f1c 100644 --- a/packages/wallet/src/hooks/useSettings.tsx +++ b/packages/wallet/src/hooks/useSettings.tsx @@ -4,31 +4,30 @@ import { useConfig } from 'wagmi' import { FiatCurrency, defaultFiatCurrency } from '../constants' interface Settings { - hideCollectibles: boolean, - hideUnlistedTokens: boolean, - fiatCurrency: FiatCurrency, - selectedNetworks: number[], - setFiatCurrency: (newFiatCurrency: FiatCurrency) => void, - setHideCollectibles: (newState: boolean) => void, - setHideUnlistedTokens: (newState: boolean) => void, - setSelectedNetworks: (newNetworks: number[]) => void, + hideCollectibles: boolean + hideUnlistedTokens: boolean + fiatCurrency: FiatCurrency + selectedNetworks: number[] + setFiatCurrency: (newFiatCurrency: FiatCurrency) => void + setHideCollectibles: (newState: boolean) => void + setHideUnlistedTokens: (newState: boolean) => void + setSelectedNetworks: (newNetworks: number[]) => void } -type SettingsItems = Pick +type SettingsItems = Pick -export const useSettings = ():Settings => { +export const useSettings = (): Settings => { const { chains } = useConfig() - const getSettingsFromStorage = ():SettingsItems => { - + const getSettingsFromStorage = (): SettingsItems => { let hideUnlistedTokens = true let hideCollectibles = false let fiatCurrency = defaultFiatCurrency - let selectedNetworks = chains.map((chain) => chain.id) + let selectedNetworks = chains.map(chain => chain.id) try { const settingsStorage = localStorage.getItem(LocalStorageKey.Settings) - + const settings = JSON.parse(settingsStorage || '{}') if (settings?.hideUnlistedTokens !== undefined) { hideUnlistedTokens = settings?.hideUnlistedTokens @@ -43,7 +42,7 @@ export const useSettings = ():Settings => { if (settings?.selectedNetworks !== undefined) { let areSelectedNetworksValid = true settings.selectedNetworks.forEach((chainId: number) => { - if (chains.find(chain => chain.id === chainId) === undefined) { + if (chains.find(chain => chain.id === chainId) === undefined) { areSelectedNetworksValid = false } }) @@ -51,8 +50,7 @@ export const useSettings = ():Settings => { selectedNetworks = settings?.selectedNetworks as number[] } } - - } catch(e) { + } catch (e) { console.error(e, 'Failed to fetch settings') } @@ -60,18 +58,18 @@ export const useSettings = ():Settings => { hideUnlistedTokens, hideCollectibles, fiatCurrency, - selectedNetworks, + selectedNetworks } } const defaultSettings = getSettingsFromStorage() const [settings, setSettings] = useState(defaultSettings) - + const setHideUnlistedTokens = (newState: boolean) => { const oldSettings = getSettingsFromStorage() const newSettings = { ...oldSettings, - hideUnlistedTokens: newState, + hideUnlistedTokens: newState } localStorage.setItem(LocalStorageKey.Settings, JSON.stringify(newSettings)) setSettings(newSettings) @@ -81,7 +79,7 @@ export const useSettings = ():Settings => { const oldSettings = getSettingsFromStorage() const newSettings = { ...oldSettings, - hideCollectibles: newState, + hideCollectibles: newState } localStorage.setItem(LocalStorageKey.Settings, JSON.stringify(newSettings)) setSettings(newSettings) @@ -91,7 +89,7 @@ export const useSettings = ():Settings => { const oldSettings = getSettingsFromStorage() const newSettings = { ...oldSettings, - fiatCurrency: newFiatCurrency, + fiatCurrency: newFiatCurrency } localStorage.setItem(LocalStorageKey.Settings, JSON.stringify(newSettings)) setSettings(newSettings) @@ -101,7 +99,7 @@ export const useSettings = ():Settings => { const oldSettings = getSettingsFromStorage() const newSettings = { ...oldSettings, - selectedNetworks: newSelectedNetworks, + selectedNetworks: newSelectedNetworks } localStorage.setItem(LocalStorageKey.Settings, JSON.stringify(newSettings)) setSettings(newSettings) @@ -112,6 +110,6 @@ export const useSettings = ():Settings => { setFiatCurrency, setHideCollectibles, setHideUnlistedTokens, - setSelectedNetworks, + setSelectedNetworks } } diff --git a/packages/wallet/src/shared/CoinIcon.tsx b/packages/wallet/src/shared/CoinIcon.tsx index f892bdce..864a5f0a 100644 --- a/packages/wallet/src/shared/CoinIcon.tsx +++ b/packages/wallet/src/shared/CoinIcon.tsx @@ -8,15 +8,10 @@ interface CoinIconProps { size?: number } -export const CoinIcon = ({ - imageUrl, - size = 30 -}: CoinIconProps) => { +export const CoinIcon = ({ imageUrl, size = 30 }: CoinIconProps) => { if (imageUrl) { - return ( - - ) + return } return -} \ No newline at end of file +} diff --git a/packages/wallet/src/shared/CoinRow.tsx b/packages/wallet/src/shared/CoinRow.tsx index 757b5c17..f12ca6f7 100644 --- a/packages/wallet/src/shared/CoinRow.tsx +++ b/packages/wallet/src/shared/CoinRow.tsx @@ -8,18 +8,26 @@ import { CoinIcon } from './CoinIcon' import { formatDisplay, getPercentageColor } from '../utils' interface CoinRowProps { - name: string, - symbol: string, - decimals: number, - balance: string, - imageUrl?: string, - fiatValue: string, + name: string + symbol: string + decimals: number + balance: string + imageUrl?: string + fiatValue: string priceChangePercentage: number } export const CoinRowSkeleton = () => { return ( - + @@ -35,35 +43,38 @@ export const CoinRowSkeleton = () => { ) } -export const CoinRow = ({ - imageUrl, - name, - decimals, - balance, - symbol, - fiatValue, - priceChangePercentage, -}: CoinRowProps) => { +export const CoinRow = ({ imageUrl, name, decimals, balance, symbol, fiatValue, priceChangePercentage }: CoinRowProps) => { const formattedBalance = ethers.utils.formatUnits(balance, decimals) const balanceDisplayed = formatDisplay(formattedBalance) return ( - + - {name} - {`${balanceDisplayed} ${symbol}`} + + {name} + + + {' '} + {`${balanceDisplayed} ${symbol}`} + {`$${fiatValue}`} - {priceChangePercentage.toFixed(2)}% + + {priceChangePercentage.toFixed(2)}% ) -} \ No newline at end of file +} diff --git a/packages/wallet/src/shared/CollectibleTileImage.tsx b/packages/wallet/src/shared/CollectibleTileImage.tsx index 2dab98f2..d65702c8 100644 --- a/packages/wallet/src/shared/CollectibleTileImage.tsx +++ b/packages/wallet/src/shared/CollectibleTileImage.tsx @@ -5,21 +5,18 @@ interface CollectibleTileImageProps { imageUrl?: string } -export const CollectibleTileImage = ({ - imageUrl -}: CollectibleTileImageProps) => { - +export const CollectibleTileImage = ({ imageUrl }: CollectibleTileImageProps) => { return ( - - - + + + ) -} \ No newline at end of file +} diff --git a/packages/wallet/src/shared/CopyButton.tsx b/packages/wallet/src/shared/CopyButton.tsx index b65b4be5..44dc11c3 100644 --- a/packages/wallet/src/shared/CopyButton.tsx +++ b/packages/wallet/src/shared/CopyButton.tsx @@ -5,7 +5,7 @@ import { CopyToClipboard } from 'react-copy-to-clipboard' type ButtonProps = ComponentProps interface CopyButtonProps extends ButtonProps { - text: string, + text: string buttonVariant: 'icon' | 'with-label' } @@ -35,7 +35,7 @@ export const CopyButton = (props: CopyButtonProps) => { icon={isCopied ? CheckmarkIcon : CopyIcon} {...rest} style={{ background: backgroundColor, ...props?.style }} - label={buttonVariant === 'with-label' ? label: undefined} + label={buttonVariant === 'with-label' ? label : undefined} /> ) diff --git a/packages/wallet/src/shared/DefaultIcon.tsx b/packages/wallet/src/shared/DefaultIcon.tsx index 01ccd8a5..fdde5359 100644 --- a/packages/wallet/src/shared/DefaultIcon.tsx +++ b/packages/wallet/src/shared/DefaultIcon.tsx @@ -15,10 +15,12 @@ export const DefaultIcon = ({ size = 30 }: DefaultIconProps) => { flexShrink="0" style={{ width: `${size}px`, - height: `${size}px`, + height: `${size}px` }} > - ? + + ? + ) -} \ No newline at end of file +} diff --git a/packages/wallet/src/shared/Loader.tsx b/packages/wallet/src/shared/Loader.tsx index 43ac75a8..02ffd65a 100644 --- a/packages/wallet/src/shared/Loader.tsx +++ b/packages/wallet/src/shared/Loader.tsx @@ -4,7 +4,9 @@ import { Box, Spinner } from '@0xsequence/design-system' export const Loader = () => { return ( - + + + ) -} \ No newline at end of file +} diff --git a/packages/wallet/src/shared/NetworkBadge.tsx b/packages/wallet/src/shared/NetworkBadge.tsx index 861ecc65..29c017cf 100644 --- a/packages/wallet/src/shared/NetworkBadge.tsx +++ b/packages/wallet/src/shared/NetworkBadge.tsx @@ -1,11 +1,6 @@ import React from 'react' import { Box, Image, Text } from '@0xsequence/design-system' -import { - getNativeTokenInfoByChainId, - getChainColor, - getChainBGColor, - getNetworkConfigAndClients -} from '@0xsequence/kit' +import { getNativeTokenInfoByChainId, getChainColor, getChainBGColor, getNetworkConfigAndClients } from '@0xsequence/kit' import { useConfig } from 'wagmi' import { capitalize } from '../utils' @@ -14,10 +9,8 @@ interface NetworkBadgeProps { chainId: number } -export const NetworkBadge = ({ - chainId -}: NetworkBadgeProps) => { - const { chains } = useConfig() +export const NetworkBadge = ({ chainId }: NetworkBadgeProps) => { + const { chains } = useConfig() const { network } = getNetworkConfigAndClients(chainId) const nativeTokenInfo = getNativeTokenInfoByChainId(chainId, chains) const chainColor = getChainColor(chainId) @@ -39,10 +32,7 @@ export const NetworkBadge = ({ alignItems="center" width="min" > - + ) -} \ No newline at end of file +} diff --git a/packages/wallet/src/shared/SendItemInfo.tsx b/packages/wallet/src/shared/SendItemInfo.tsx index f5fb7094..534e4c7a 100644 --- a/packages/wallet/src/shared/SendItemInfo.tsx +++ b/packages/wallet/src/shared/SendItemInfo.tsx @@ -13,14 +13,14 @@ import { useSettings } from '../hooks' import { CollectibleTileImage } from '../shared/CollectibleTileImage' interface SendItemInfoProps { - name: string, - symbol: string, - decimals: number, - balance: string, - imageUrl?: string, - fiatValue?: string, - chainId: number, - showSquareImage?: boolean, + name: string + symbol: string + decimals: number + balance: string + imageUrl?: string + fiatValue?: string + chainId: number + showSquareImage?: boolean } export const SendItemInfoSkeleton = () => { @@ -49,7 +49,7 @@ export const SendItemInfo = ({ symbol, fiatValue, chainId, - showSquareImage, + showSquareImage }: SendItemInfoProps) => { const { chains } = useConfig() const { fiatCurrency } = useSettings() @@ -69,17 +69,20 @@ export const SendItemInfo = ({ )} - {name} + + {name} + - {`${balanceDisplayed} ${symbol} available`} + + {' '} + {`${balanceDisplayed} ${symbol} available`} + - {fiatValue && ( - {`${fiatCurrency.sign}${fiatValue}`} - )} + {fiatValue && {`${fiatCurrency.sign}${fiatValue}`}} ) -} \ No newline at end of file +} diff --git a/packages/wallet/src/shared/index.tsx b/packages/wallet/src/shared/index.tsx index 8757e8f3..dd11985c 100644 --- a/packages/wallet/src/shared/index.tsx +++ b/packages/wallet/src/shared/index.tsx @@ -1 +1 @@ -export * from './KitWalletProvider' \ No newline at end of file +export * from './KitWalletProvider' diff --git a/packages/wallet/src/shared/styles.css.ts b/packages/wallet/src/shared/styles.css.ts index f920bb86..66a89219 100644 --- a/packages/wallet/src/shared/styles.css.ts +++ b/packages/wallet/src/shared/styles.css.ts @@ -12,31 +12,30 @@ export const clickable = style({ export const scrollbar = style({ /* @ts-ignore-next-line */ '> div': { - overflowY: 'scroll', - }, + overflowY: 'scroll' + } }) globalStyle(`html:not(.is-apple) ${scrollbar} > div::-webkit-scrollbar-thumb`, { background: 'none', backgroundClip: 'content-box', // The transition doesn't work. It might possibly be a chrome issue - transition: 'background 0.5s linear', + transition: 'background 0.5s linear' }) globalStyle(`html:not(.is-apple) ${scrollbar} > div:hover::-webkit-scrollbar-thumb`, { background: vars.colors.text50, - backgroundClip: 'content-box', + backgroundClip: 'content-box' }) -export const walletContent = style({ -}) +export const walletContent = style({}) // Will affect the close button in the modal globalStyle(`${walletContent} + button`, { - backgroundColor: 'transparent', + backgroundColor: 'transparent' }) globalStyle(`${walletContent} + button > svg`, { width: '20px', height: '20px' -}) \ No newline at end of file +}) diff --git a/packages/wallet/src/utils/helpers.ts b/packages/wallet/src/utils/helpers.ts index b0efa23b..97591461 100644 --- a/packages/wallet/src/utils/helpers.ts +++ b/packages/wallet/src/utils/helpers.ts @@ -6,10 +6,7 @@ export const truncateAtMiddle = (text: string, truncateAt: number) => { let finalText = text if (text.length >= truncateAt) { - finalText = - text.slice(0, truncateAt / 2) + - '...' + - text.slice(text.length - truncateAt / 2, text.length) + finalText = text.slice(0, truncateAt / 2) + '...' + text.slice(text.length - truncateAt / 2, text.length) } return finalText @@ -51,10 +48,7 @@ export const formatDisplay = (_val: number | string): string => { } let notation: Intl.NumberFormatOptions['notation'] = undefined - let config: Pick< - Intl.NumberFormatOptions, - 'maximumFractionDigits' | 'maximumSignificantDigits' - > + let config: Pick switch (valMode) { case ValueType.VERY_LARGE: diff --git a/packages/wallet/src/utils/index.ts b/packages/wallet/src/utils/index.ts index dc0692f2..61379d14 100644 --- a/packages/wallet/src/utils/index.ts +++ b/packages/wallet/src/utils/index.ts @@ -1,3 +1,3 @@ export * from './helpers' export * from './tokens' -export * from './networks' \ No newline at end of file +export * from './networks' diff --git a/packages/wallet/src/utils/networks.ts b/packages/wallet/src/utils/networks.ts index 5155f520..1c8a22f4 100644 --- a/packages/wallet/src/utils/networks.ts +++ b/packages/wallet/src/utils/networks.ts @@ -5,5 +5,5 @@ export const getPaperNetworkName = (network: NetworkConfig): string => { if (network.chainId === 1) { return 'Ethereum' } - return (capitalize(network.name)) + return capitalize(network.name) } diff --git a/packages/wallet/src/utils/tokens.ts b/packages/wallet/src/utils/tokens.ts index 94c8d40e..f3b3a682 100644 --- a/packages/wallet/src/utils/tokens.ts +++ b/packages/wallet/src/utils/tokens.ts @@ -8,19 +8,19 @@ import { vars } from '@0xsequence/design-system' import { compareAddress } from './helpers' export const getPercentageColor = (value: number) => { - if(value > 0) { + if (value > 0) { return vars.colors.positive } else if (value < 0) { return vars.colors.negative - } else { - return vars.colors.text50 - } + } else { + return vars.colors.text50 + } } export const getPercentagePriceChange = (balance: TokenBalance, prices: TokenPrice[]) => { const priceForToken = prices.find(p => compareAddress(p.token.contractAddress, balance.contractAddress)) if (!priceForToken) { - return 0; + return 0 } const price24HourChange = priceForToken?.price24hChange?.value || 0 @@ -28,23 +28,18 @@ export const getPercentagePriceChange = (balance: TokenBalance, prices: TokenPri } interface ComputeBalanceFiat { - balance: TokenBalance, - prices: TokenPrice[], - decimals: number, + balance: TokenBalance + prices: TokenPrice[] + decimals: number conversionRate: number } -export const computeBalanceFiat = ({ - balance, - prices, - decimals, - conversionRate -}: ComputeBalanceFiat): string => { +export const computeBalanceFiat = ({ balance, prices, decimals, conversionRate }: ComputeBalanceFiat): string => { let totalUsd = 0 const priceForToken = prices.find(p => compareAddress(p.token.contractAddress, balance.contractAddress)) if (!priceForToken) { - return '0.00'; + return '0.00' } const priceFiat = priceForToken.price?.value || 0 const valueFormatted = ethers.utils.formatUnits(balance.balance, decimals) @@ -56,10 +51,9 @@ export const computeBalanceFiat = ({ return `${fiatValue.toFixed(2)}` } - interface SortBalancesByTypeReturn { - nativeTokens: TokenBalance[], - erc20Tokens: TokenBalance[], + nativeTokens: TokenBalance[] + erc20Tokens: TokenBalance[] collectibles: TokenBalance[] } @@ -67,8 +61,8 @@ export const sortBalancesByType = (balances: TokenBalance[]): SortBalancesByType const nativeTokens: TokenBalance[] = [] const erc20Tokens: TokenBalance[] = [] const collectibles: TokenBalance[] = [] - - balances.forEach((balance) => { + + balances.forEach(balance => { // Note: contractType for the native token should be "UNKNOWN" if (balance.contractAddress === ethers.constants.AddressZero) { nativeTokens.push(balance) diff --git a/packages/wallet/src/views/History.tsx b/packages/wallet/src/views/History.tsx index 2337b488..eb50f744 100644 --- a/packages/wallet/src/views/History.tsx +++ b/packages/wallet/src/views/History.tsx @@ -7,7 +7,7 @@ import { useSettings, useTransactionHistorySummary } from '../hooks' import { TransactionHistoryList } from '../shared/TransactionHistoryList' export const History = () => { - const { selectedNetworks } = useSettings() + const { selectedNetworks } = useSettings() const { address: accountAddress } = useAccount() const { data: transactionHistory = [], isLoading: isLoadingTransactionHistory } = useTransactionHistorySummary({ @@ -25,12 +25,12 @@ export const History = () => { paddingRight: `calc(${vars.space[5]} - ${SCROLLBAR_WIDTH})` }} > - + ) -} \ No newline at end of file +} diff --git a/packages/wallet/src/views/Receive.tsx b/packages/wallet/src/views/Receive.tsx index 27aa3e9e..c4b9e5ee 100644 --- a/packages/wallet/src/views/Receive.tsx +++ b/packages/wallet/src/views/Receive.tsx @@ -35,34 +35,29 @@ export const Receive = () => { return ( - + - + My Wallet - icon + icon - + { - + -