-
Notifications
You must be signed in to change notification settings - Fork 1.2k
fix(types): better types and autocomplete for custom contract hooks #202
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 12 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
20ef318
fix(types): better types and autocomplete for custom contract hooks
sverps e5b0acb
fix(types): small improvements based on pr comments
sverps a26b2f7
Use isMounted hook rather than local variable & Move deployedContract…
sverps ce47566
feature: beetter typing of args
sverps ed8d262
fix: import order
sverps 401dbba
Merge branch 'main' into fix/116-type-inference
sverps 8bb7a92
build: generate step in ci
sverps 80c186a
fix: let typescript 'as const' set the type of the config to force na…
sverps 6582be0
Merge branch 'main' into fix/116-type-inference
carletex 30360ee
feat: group read/write hook params in one config
sverps 0b09b9c
fix: make args tupple elements allow undefined
sverps 0c79d44
Fix conflicts
carletex a4d41cc
Use ~~ and update function comment
carletex 0f088cc
../.. => ~~
carletex File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import * as fs from "fs"; | ||
| //@ts-expect-error This script runs after `hardhat deploy --export` therefore its deterministic that it will present | ||
| import allGeneratedContracts from "../../nextjs/generated/hardhat_contracts.json"; | ||
| import prettier from "prettier"; | ||
|
|
||
| function main() { | ||
| const GENERATED_PATH = "../nextjs/generated/hardhat_contracts"; | ||
|
|
||
| const fileContent = Object.entries(allGeneratedContracts).reduce((content, [chainId, chainConfig]) => { | ||
| return `${content}${parseInt(chainId).toFixed(0)}:${JSON.stringify(chainConfig, null, 2)},`; | ||
| }, ""); | ||
|
|
||
| fs.writeFileSync( | ||
| `${GENERATED_PATH}.ts`, | ||
| prettier.format(`export default {${fileContent}} as const;`, { parser: "typescript" }), | ||
| ); | ||
| // remove json file due to ambiguity | ||
| fs.unlinkSync(`${GENERATED_PATH}.json`); | ||
| } | ||
|
|
||
| try { | ||
| main(); | ||
| } catch (error) { | ||
| console.error(error); | ||
| process.exitCode = 1; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| import contracts from "../../generated/hardhat_contracts"; | ||
| import { Abi, AbiParametersToPrimitiveTypes, ExtractAbiEvent, ExtractAbiEventNames, ExtractAbiFunction } from "abitype"; | ||
| import type { ExtractAbiFunctionNames } from "abitype"; | ||
| import { UseContractReadConfig, UseContractWriteConfig } from "wagmi"; | ||
| import scaffoldConfig from "~~/scaffold.config"; | ||
|
|
||
| export type Chain = keyof typeof contracts; | ||
|
|
||
| type SelectedChainId = (typeof scaffoldConfig)["targetNetwork"]["id"]; | ||
|
|
||
| type Contracts = (typeof contracts)[SelectedChainId][0]["contracts"]; | ||
|
|
||
| export type ContractName = keyof Contracts; | ||
|
|
||
| export type Contract<TContractName extends ContractName> = Contracts[TContractName]; | ||
|
|
||
| type InferContractAbi<TContract> = TContract extends { abi: infer TAbi } ? TAbi : never; | ||
|
|
||
| export type ContractAbi<TContractName extends ContractName = ContractName> = InferContractAbi<Contract<TContractName>>; | ||
|
|
||
| export type AbiFunctionInputs<TAbi extends Abi, TFunctionName extends string> = ExtractAbiFunction< | ||
| TAbi, | ||
| TFunctionName | ||
| >["inputs"]; | ||
|
|
||
| export type AbiFunctionArguments<TAbi extends Abi, TFunctionName extends string> = AbiParametersToPrimitiveTypes< | ||
| AbiFunctionInputs<TAbi, TFunctionName> | ||
| >; | ||
|
|
||
| export type AbiFunctionOutputs<TAbi extends Abi, TFunctionName extends string> = ExtractAbiFunction< | ||
| TAbi, | ||
| TFunctionName | ||
| >["outputs"]; | ||
|
|
||
| export type AbiFunctionReturnType<TAbi extends Abi, TFunctionName extends string> = AbiParametersToPrimitiveTypes< | ||
| AbiFunctionOutputs<TAbi, TFunctionName> | ||
| >[0]; | ||
|
|
||
| export type AbiEventInputs<TAbi extends Abi, TEventName extends ExtractAbiEventNames<TAbi>> = ExtractAbiEvent< | ||
| TAbi, | ||
| TEventName | ||
| >["inputs"]; | ||
|
|
||
| export type AbiEventArgs< | ||
| TAbi extends Abi, | ||
| TEventName extends ExtractAbiEventNames<TAbi>, | ||
| > = AbiParametersToPrimitiveTypes<AbiEventInputs<TAbi, TEventName>>; | ||
|
|
||
| export enum ContractCodeStatus { | ||
| "LOADING", | ||
| "DEPLOYED", | ||
| "NOT_FOUND", | ||
| } | ||
|
|
||
| type AbiStateMutability = "pure" | "view" | "nonpayable" | "payable"; | ||
|
|
||
| export type FunctionNamesWithoutInputs< | ||
| TAbi extends Abi, | ||
| TAbiStateMutibility extends AbiStateMutability = AbiStateMutability, | ||
| > = Extract< | ||
| TAbi[number], | ||
| { | ||
| type: "function"; | ||
| stateMutability: TAbiStateMutibility; | ||
| inputs: readonly []; | ||
| } | ||
| >["name"]; | ||
|
|
||
| export type FunctionNamesWithInputs< | ||
| TAbi extends Abi, | ||
| TAbiStateMutibility extends AbiStateMutability = AbiStateMutability, | ||
| > = Exclude< | ||
| Extract< | ||
| TAbi[number], | ||
| { | ||
| type: "function"; | ||
| stateMutability: TAbiStateMutibility; | ||
| } | ||
| >, | ||
| { | ||
| inputs: readonly []; | ||
| } | ||
| >["name"]; | ||
|
|
||
| type ReadAbiStateMutability = "view" | "pure"; | ||
| type WriteAbiStateMutability = "nonpayable" | "payable"; | ||
|
|
||
| type RestConfigParam<TAbiStateMutability extends AbiStateMutability> = Partial< | ||
| Omit< | ||
| TAbiStateMutability extends ReadAbiStateMutability ? UseContractReadConfig : UseContractWriteConfig, | ||
| "chainId" | "abi" | "address" | "functionName" | "args" | ||
| > | ||
| >; | ||
|
|
||
| type OptionalTupple<T> = T extends readonly [infer H, ...infer R] ? readonly [H | undefined, ...OptionalTupple<R>] : T; | ||
|
|
||
| type UseScaffoldArgsParam< | ||
| TContractName extends ContractName, | ||
| TAbiStateMutability extends AbiStateMutability, | ||
| TFunctionName extends ExtractAbiFunctionNames<ContractAbi<TContractName>, TAbiStateMutability>, | ||
| > = TFunctionName extends FunctionNamesWithInputs<ContractAbi<TContractName>, TAbiStateMutability> | ||
| ? { | ||
| args: OptionalTupple<AbiFunctionArguments<ContractAbi<TContractName>, TFunctionName>>; | ||
| } | ||
| : { | ||
| args?: never; | ||
| }; | ||
|
|
||
| export type UseScaffoldReadConfig< | ||
| TContractName extends ContractName, | ||
| TFunctionName extends ExtractAbiFunctionNames<ContractAbi<TContractName>, ReadAbiStateMutability>, | ||
| > = { | ||
| contractName: TContractName; | ||
| functionName: TFunctionName; | ||
| } & UseScaffoldArgsParam<TContractName, ReadAbiStateMutability, TFunctionName> & | ||
| RestConfigParam<ReadAbiStateMutability>; | ||
|
|
||
| export type UseScaffoldWriteConfig< | ||
| TContractName extends ContractName, | ||
| TFunctionName extends ExtractAbiFunctionNames<ContractAbi<TContractName>, WriteAbiStateMutability>, | ||
| > = { | ||
| contractName: TContractName; | ||
| functionName: TFunctionName; | ||
| value?: string; | ||
| } & UseScaffoldArgsParam<TContractName, WriteAbiStateMutability, TFunctionName> & | ||
| RestConfigParam<WriteAbiStateMutability>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 31 additions & 38 deletions
69
packages/nextjs/hooks/scaffold-eth/useDeployedContractInfo.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,54 +1,47 @@ | ||
| import { useEffect, useState } from "react"; | ||
| import contracts from "../../generated/hardhat_contracts"; | ||
| import { Contract, ContractCodeStatus, ContractName } from "./contract.types"; | ||
| import { useIsMounted } from "usehooks-ts"; | ||
| import { useProvider } from "wagmi"; | ||
| import { getTargetNetwork } from "~~/utils/scaffold-eth"; | ||
|
|
||
| type GeneratedContractType = { | ||
| address: string; | ||
| abi: any[]; | ||
| }; | ||
| import scaffoldConfig from "~~/scaffold.config"; | ||
|
|
||
| /** | ||
| * @dev use this hook to get a deployed contract from `yarn deploy` generated files. | ||
| * @param contractName - name of deployed contract | ||
| * @returns {GeneratedContractType | undefined} object containing contract address and abi or undefined if contract is not found | ||
carletex marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| */ | ||
| export const useDeployedContractInfo = (contractName: string | undefined | null) => { | ||
| const [deployedContractData, setDeployedContractData] = useState<undefined | GeneratedContractType>(undefined); | ||
| const [isLoading, setIsLoading] = useState(true); | ||
| const configuredNetwork = getTargetNetwork(); | ||
|
|
||
| const provider = useProvider({ chainId: configuredNetwork.id }); | ||
| export const useDeployedContractInfo = <TContractName extends ContractName>(contractName: TContractName) => { | ||
| const isMounted = useIsMounted(); | ||
| const deployedContract = contracts[scaffoldConfig.targetNetwork.id]?.[0]?.contracts?.[ | ||
| contractName as ContractName | ||
| ] as Contract<TContractName>; | ||
| const [status, setStatus] = useState<ContractCodeStatus>(ContractCodeStatus.LOADING); | ||
| const provider = useProvider({ chainId: scaffoldConfig.targetNetwork.id }); | ||
|
|
||
| useEffect(() => { | ||
| const getDeployedContractInfo = async () => { | ||
| setIsLoading(true); | ||
| let ContractData; | ||
| try { | ||
| ContractData = require("~~/generated/hardhat_contracts.json"); | ||
| const contractsAtChain = ContractData[configuredNetwork.id as keyof typeof ContractData]; | ||
| const contractsData = contractsAtChain?.[0]?.contracts; | ||
| const deployedContract = contractsData?.[contractName as keyof typeof contractsData]; | ||
|
|
||
| if (!deployedContract || !contractName || !provider) { | ||
| return; | ||
| } | ||
| const checkContractDeployment = async () => { | ||
| if (!deployedContract) { | ||
| setStatus(ContractCodeStatus.NOT_FOUND); | ||
| return; | ||
| } | ||
| const code = await provider.getCode((deployedContract as Contract<TContractName>).address); | ||
|
|
||
| const code = await provider.getCode(deployedContract.address); | ||
| // If contract code is `0x` => no contract deployed on that address | ||
| if (code === "0x" || !contractsData || !(contractName in contractsData)) { | ||
| return; | ||
| } | ||
| setDeployedContractData(contractsData[contractName]); | ||
| } catch (e) { | ||
| // Contract not deployed or file doesn't exist. | ||
| setDeployedContractData(undefined); | ||
| } finally { | ||
| setIsLoading(false); | ||
| if (!isMounted()) { | ||
| return; | ||
| } | ||
| // If contract code is `0x` => no contract deployed on that address | ||
| if (code === "0x") { | ||
| setStatus(ContractCodeStatus.NOT_FOUND); | ||
| return; | ||
| } | ||
| setStatus(ContractCodeStatus.DEPLOYED); | ||
| }; | ||
|
|
||
| getDeployedContractInfo(); | ||
| }, [configuredNetwork.id, contractName, provider]); | ||
| checkContractDeployment(); | ||
| }, [isMounted, contractName, deployedContract, provider]); | ||
|
|
||
| return { data: deployedContractData, isLoading }; | ||
| return { | ||
| data: status === ContractCodeStatus.DEPLOYED ? deployedContract : undefined, | ||
| isLoading: status === ContractCodeStatus.LOADING, | ||
| }; | ||
| }; | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.