Files
js/@3rdweb-sdk/react/hooks/useSDK.ts
T
1064350681 Any EVM + middleware (#814)
* homepage: infinite looping logo carousel

* split partners logo among two rows on mobile

* remove lazy loading from partner logos

* Fix partner logo cut off on safari

* fade-in logo carousel at the container edge

* v1

* v2

* remove temp code changes

* switch network *technically* works, and new chains package

* Fix src warning in AsyncContractTypeCell

* Updated Design for config form, fix metadata error

* add initial deployment status modal

* Fix contract duplication bug in dashboard

* Make RPC url always editable

* v3 - middleware + refactor

* reset form when selecting custom option

* Fix crash on sources tab for unsupported chains

* add missing deps in effects

* /evm - use SSG with fallback

* /evm - add ensQuery dehydration back

* /solana - fix program page loading issue

* Allow editing details for custom chains

* solana program context

* fix build crash

* fix all the networkOrAddress getters

* use chain icons from chains package

* separation of fallback and final page

* Fix wrong default network type in form

* validation improvements in configure network form

* disable custom chains from dropdown on On non thirdweb contracts deploy page

* Fix wrong network slug

* custom chain improvement

* Fix Lightmode UI of Network Config Form

* UI improvements for network search dropdown

* UI tweaks

* code review cleanup

* UI tweaks

* Network Config Form: Better Keyboard UX

* fix broken /contracts/release and /contracts/deploy routes

* add configure networks button for custom contract deployment page

* UI tweaks for network configurator

* fix merge

* add the icon to the custom chain

* Bunch of Improvements

* Improve auto chain configuration
* Do not allow adding custom network with existing chain id
* Show delete default chains with 1-click add
* Convert delete dialog to a popover
* Retain all fields when selecting a chain from list
* Allow configuring chain Icons
* Allow using chainId as network slug for custom networks
* Remove unnecessary chainInfos object passed in provider

* configurable slug + prefill form

* improve scrollbar styling

* upgrade to newer sdk etc

* make it work

* Various testjame improvements

* Stop form submit event propagation
* preselect “testnet” for custom network based on name
* Clear form errors when selecting a network from list
* Improved UI for Delete network popover
* Disable “Add Network” button when on add network page
* Change fallback chain icon

* custom and search tabs

* reduce layout shift when switching tabs

* allChains caching with idb

* Add IPFS upload button for icon input

* Deploy Modal, chain icon, code cleanup

* Fix Deploy Modal not working for custom contract deployment
* Fix Fantom testnet icon
* Remove useDashboardNetwork()
* Update Deploy Modal wording in case for 3 prompt scenario
* Remove hardhat and localhost from CURRENCIES object
* Remove gateway.ipfscdn.io from images.remotePatterns in next config

* add chain config tracking

* remove useChainInfos()

* Remove EVM_RPC_URL_MAP usage as much as possible

* Fix Network Switcher for non-default chains

* upgrade new dev sdk versions

* fix versions

* Fix contractInfo.chain not available on contract page of custom chain

* Fix contract page links in overview page

* Update default chain Icon

* bunch of UI improvements for network configuration modal

* Better active state for add network button and chains
* Suggest a slug for custom network
* Show chain id next to network names in list
* Allow searching by chain id
* Autofocus on first input of the form
* Add cross button for clearing search input
* Toggle search results open state with chevron icon
* Add icons in chain list

* handle wallet connected to unsupported network in <SupportedNetworkSelect/>

* No reload required after adding a network

* revert last commit - reload still required

* handle case where wallet is connected to an auto configured chain - show it as unknown network

* update dependencies and switch to activeChain and supportedChains

* nightly sdk versions

* Improved Icon Uploader

* always use default chains for polygon registry work

* dev version & updated list fetching

* Improved Chain ID input in Network Configurator

* Improved Network ID validation and prefill

* Hide etherscan verification button for non-default chains

* Form Refactor + network type toolip

* update deps

* update package versions

* upgrade dependencies

* show "create custom"  when no search results found

* slug calculated from prefillName should not be considered dirty

* open edit screen when selecting already configured network from list

* fuzzy search with fuse.js

* replace thirdweb key with it's value in form

* temp fix for getChainRPC throwing error

* update to newer chains package

* lots of rpc cleanup etc

* fix nightly maybe?

* upgrade to nightly packages

* add initial import contract search input

* fix localhost

* clean up smoe more stuff

* lots of updates

* Show "Request Testnet Funds" button in wallet when applicable (#856)

* fix crash on events page

* Fix Links in Overview page

* import contract improvements

* Fix wrong explorer tab link in ContractPermissionsPage

* make search faster (individual queries)

* properly split contract and program routing

* remove all via stuff etc

* various further improvements

* add a proxy and setup storage to hit that proxy

* further cleanup

---------

Co-authored-by: Jonas Daniels <[email protected]>
Co-authored-by: Joaquim Verges <[email protected]>
2023-02-14 09:37:47 +00:00

406 lines
11 KiB
TypeScript

import { contractKeys, networkKeys } from "../cache-keys";
import { useQuery } from "@tanstack/react-query";
import {
Arbitrum,
ArbitrumGoerli,
Avalanche,
AvalancheFuji,
Binance,
BinanceTestnet,
Ethereum,
Fantom,
FantomTestnet,
Goerli,
Mumbai,
Optimism,
OptimismGoerli,
Polygon,
} from "@thirdweb-dev/chains";
import { ChainId, ContractWithMetadata } from "@thirdweb-dev/sdk/evm";
import { useAutoConfigureChains } from "hooks/chains/allChains";
import {
useConfiguredChains,
useConfiguredChainsRecord,
} from "hooks/chains/configureChains";
import { getDashboardChainRpc } from "lib/rpc";
import { getEVMThirdwebSDK, getSOLThirdwebSDK } from "lib/sdk";
import { useEffect, useMemo } from "react";
import invariant from "tiny-invariant";
import { DashboardSolanaNetwork } from "utils/solanaUtils";
export function useContractList(
chainId: number,
rpcUrl: string,
walletAddress?: string,
) {
return useQuery(
[...networkKeys.chain(chainId), ...contractKeys.list(walletAddress)],
async () => {
if (!walletAddress) {
return;
}
const sdk = getEVMThirdwebSDK(chainId, rpcUrl);
const contractList = await sdk.getContractList(walletAddress);
return [...contractList].reverse();
},
{
enabled: !!walletAddress && !!chainId,
},
);
}
export function useMultiChainRegContractList(walletAddress?: string) {
const configuredChains = useConfiguredChains();
return useQuery(
[
...networkKeys.multiChainRegistry,
walletAddress,
{ chainIds: configuredChains.map((c) => c.chainId) },
],
async () => {
if (!walletAddress) {
return [];
}
const polygonSDK = getEVMThirdwebSDK(
Polygon.chainId,
getDashboardChainRpc(Polygon),
);
const contractList = await polygonSDK.getMultichainContractList(
walletAddress,
configuredChains,
);
return [...contractList].reverse();
},
{
enabled: !!walletAddress,
},
);
}
export function useMainnetsContractList(walletAddress: string | undefined) {
const mainnetQuery = useContractList(
Ethereum.chainId,
getDashboardChainRpc(Ethereum),
walletAddress,
);
const polygonQuery = useContractList(
Polygon.chainId,
getDashboardChainRpc(Polygon),
walletAddress,
);
const fantomQuery = useContractList(
Fantom.chainId,
getDashboardChainRpc(Fantom),
walletAddress,
);
const avalancheQuery = useContractList(
Avalanche.chainId,
getDashboardChainRpc(Avalanche),
walletAddress,
);
const optimismQuery = useContractList(
Optimism.chainId,
getDashboardChainRpc(Optimism),
walletAddress,
);
const arbitrumQuery = useContractList(
Arbitrum.chainId,
getDashboardChainRpc(Arbitrum),
walletAddress,
);
const binanceQuery = useContractList(
Binance.chainId,
getDashboardChainRpc(Binance),
walletAddress,
);
const mainnetList = useMemo(() => {
return (
mainnetQuery.data?.map((d) => ({ ...d, chainId: ChainId.Mainnet })) || []
)
.concat(
polygonQuery.data?.map((d) => ({
...d,
chainId: ChainId.Polygon,
})) || [],
)
.concat(
avalancheQuery.data?.map((d) => ({
...d,
chainId: ChainId.Avalanche,
})) || [],
)
.concat(
fantomQuery.data?.map((d) => ({ ...d, chainId: ChainId.Fantom })) || [],
)
.concat(
optimismQuery.data?.map((d) => ({ ...d, chainId: ChainId.Optimism })) ||
[],
)
.concat(
arbitrumQuery.data?.map((d) => ({ ...d, chainId: ChainId.Arbitrum })) ||
[],
)
.concat(
binanceQuery.data?.map((d) => ({
...d,
chainId: ChainId.BinanceSmartChainMainnet,
})) || [],
);
}, [
mainnetQuery.data,
polygonQuery.data,
fantomQuery.data,
avalancheQuery.data,
optimismQuery.data,
arbitrumQuery.data,
binanceQuery.data,
]);
return {
data: mainnetList,
isLoading:
mainnetQuery.isLoading ||
polygonQuery.isLoading ||
fantomQuery.isLoading ||
avalancheQuery.isLoading ||
optimismQuery.isLoading ||
arbitrumQuery.isLoading ||
binanceQuery.isLoading,
isFetched:
mainnetQuery.isFetched &&
polygonQuery.isFetched &&
fantomQuery.isFetched &&
avalancheQuery.isFetched &&
optimismQuery.isFetched &&
arbitrumQuery.isFetched &&
binanceQuery.isFetched,
};
}
export function useTestnetsContractList(walletAddress: string | undefined) {
const goerliQuery = useContractList(
Goerli.chainId,
getDashboardChainRpc(Goerli),
walletAddress,
);
const mumbaiQuery = useContractList(
Mumbai.chainId,
getDashboardChainRpc(Mumbai),
walletAddress,
);
const fantomTestnetQuery = useContractList(
FantomTestnet.chainId,
getDashboardChainRpc(FantomTestnet),
walletAddress,
);
const avalancheFujiTestnetQuery = useContractList(
AvalancheFuji.chainId,
getDashboardChainRpc(AvalancheFuji),
walletAddress,
);
const optimismGoerliQuery = useContractList(
OptimismGoerli.chainId,
getDashboardChainRpc(OptimismGoerli),
walletAddress,
);
const arbitrumGoerliQuery = useContractList(
ArbitrumGoerli.chainId,
getDashboardChainRpc(ArbitrumGoerli),
walletAddress,
);
const binanceTestnetQuery = useContractList(
BinanceTestnet.chainId,
getDashboardChainRpc(BinanceTestnet),
walletAddress,
);
const testnetList = useMemo(() => {
return (
goerliQuery.data?.map((d) => ({ ...d, chainId: ChainId.Goerli })) || []
)
.concat(
mumbaiQuery.data?.map((d) => ({ ...d, chainId: ChainId.Mumbai })) || [],
)
.concat(
avalancheFujiTestnetQuery.data?.map((d) => ({
...d,
chainId: ChainId.AvalancheFujiTestnet,
})) || [],
)
.concat(
fantomTestnetQuery.data?.map((d) => ({
...d,
chainId: ChainId.FantomTestnet,
})) || [],
)
.concat(
optimismGoerliQuery.data?.map((d) => ({
...d,
chainId: ChainId.OptimismGoerli,
})) || [],
)
.concat(
arbitrumGoerliQuery.data?.map((d) => ({
...d,
chainId: ChainId.ArbitrumGoerli,
})) || [],
)
.concat(
binanceTestnetQuery.data?.map((d) => ({
...d,
chainId: ChainId.BinanceSmartChainTestnet,
})) || [],
);
}, [
goerliQuery.data,
mumbaiQuery.data,
fantomTestnetQuery.data,
avalancheFujiTestnetQuery.data,
optimismGoerliQuery.data,
arbitrumGoerliQuery.data,
binanceTestnetQuery.data,
]);
return {
data: testnetList,
isLoading:
goerliQuery.isLoading ||
mumbaiQuery.isLoading ||
fantomTestnetQuery.isLoading ||
avalancheFujiTestnetQuery.isLoading ||
optimismGoerliQuery.isLoading ||
arbitrumGoerliQuery.isLoading ||
binanceTestnetQuery.isLoading,
isFetched:
goerliQuery.isFetched &&
mumbaiQuery.isFetched &&
fantomTestnetQuery.isFetched &&
avalancheFujiTestnetQuery.isFetched &&
optimismGoerliQuery.isFetched &&
arbitrumGoerliQuery.isFetched &&
binanceTestnetQuery.isFetched,
};
}
export function useAllContractList(walletAddress: string | undefined) {
const mainnetQuery = useMainnetsContractList(walletAddress);
const testnetQuery = useTestnetsContractList(walletAddress);
const multiChainQuery = useMultiChainRegContractList(walletAddress);
const configuredChainsRecord = useConfiguredChainsRecord();
const autoConfigureChains = useAutoConfigureChains();
useEffect(() => {
if (!multiChainQuery.data) {
return;
}
// create a set of unconfigured chains
const unconfiguredChainsSet: Set<number> = new Set();
multiChainQuery.data.forEach((contract) => {
if (!configuredChainsRecord[contract.chainId]) {
unconfiguredChainsSet.add(contract.chainId);
}
});
// auto configure them all if possible
autoConfigureChains(unconfiguredChainsSet);
}, [autoConfigureChains, multiChainQuery.data, configuredChainsRecord]);
const allList = useMemo(() => {
const mainnets: ContractWithMetadata[] = [];
const testnets: ContractWithMetadata[] = [];
const unknownNets: ContractWithMetadata[] = [];
if (multiChainQuery.data) {
multiChainQuery.data.forEach((net) => {
// if network is configured, we can determine if it is a testnet or not
if (net.chainId in configuredChainsRecord) {
const netInfo = configuredChainsRecord[net.chainId];
if (netInfo.testnet) {
testnets.push(net);
} else {
mainnets.push(net);
}
}
// if not configured, we can't determine if it is a testnet or not
else {
unknownNets.push(net);
}
});
}
// only for legacy reasons - can be removed once migration to multi-chain registry is complete
const mergedMainnets = [...mainnets, ...mainnetQuery.data].sort(
(a, b) => a.chainId - b.chainId,
);
const mergedTestnets = [...testnets, ...testnetQuery.data].sort(
(a, b) => a.chainId - b.chainId,
);
let all = [...mergedMainnets, ...mergedTestnets, ...unknownNets];
// remove duplicates (by address + chain) - can happen if a contract is on both muichain registry and legacy registries
const seen: { [key: string]: boolean } = {};
all = all.filter((item) => {
const key = `${item.chainId}-${item.address}`;
const seenBefore = seen[key];
seen[key] = true;
return !seenBefore;
});
return all;
}, [
mainnetQuery.data,
testnetQuery.data,
multiChainQuery.data,
configuredChainsRecord,
]);
return {
data: allList,
isLoading: mainnetQuery.isLoading || testnetQuery.isLoading,
isFetched: mainnetQuery.isFetched && testnetQuery.isFetched,
};
}
function useProgramList(
address: string | undefined,
network: DashboardSolanaNetwork,
) {
return useQuery(
["sol", network, address, "program-list"],
async () => {
invariant(address, "address is required");
const sdk = getSOLThirdwebSDK(network);
// TODO remove this sorting when we have a stable return array from the SDK
return (await sdk.registry.getDeployedPrograms(address))
.sort((a, b) => (a.programName > b.programName ? 1 : -1))
.map((p) => ({ ...p, network }));
},
{ enabled: !!address && !!network },
);
}
export function useAllProgramsList(address: string | undefined) {
const mainnetQuery = useProgramList(address, "mainnet-beta");
const devnetQuery = useProgramList(address, "devnet");
const allList = useMemo(() => {
return (mainnetQuery.data || []).concat(devnetQuery.data || []);
}, [mainnetQuery.data, devnetQuery.data]);
return {
data: allList,
isLoading: mainnetQuery.isLoading || devnetQuery.isLoading,
isFetched: mainnetQuery.isFetched && devnetQuery.isFetched,
};
}