-
Notifications
You must be signed in to change notification settings - Fork 48
feat(web): validation of the token address for ERC20/721/1155 types #2052
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
Open
jaybuidl
wants to merge
5
commits into
dev
Choose a base branch
from
feat/gated-dk-address-validation
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+375
−6
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f1fe7c9
feat(web): validation of the token address for ERC20/721/1155 types
jaybuidl 92852da
Merge branch 'dev' into feat/gated-dk-address-validation
tractorss c99b0c9
chore: refactors
tractorss 7c74b70
fix: validation should fail if token gate address is empty
jaybuidl d78e212
Update web/src/pages/Resolver/Parameters/Court.tsx
tractorss 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,215 @@ | ||
import { useEffect, useState, useMemo } from "react"; | ||
|
||
import { useQuery } from "@tanstack/react-query"; | ||
import { getContract, isAddress } from "viem"; | ||
import { usePublicClient, useChainId } from "wagmi"; | ||
|
||
import { isUndefined } from "utils/index"; | ||
|
||
const ERC1155_ABI = [ | ||
{ | ||
inputs: [ | ||
{ | ||
internalType: "address", | ||
name: "account", | ||
type: "address", | ||
}, | ||
{ | ||
internalType: "uint256", | ||
name: "id", | ||
type: "uint256", | ||
}, | ||
], | ||
name: "balanceOf", | ||
outputs: [ | ||
{ | ||
internalType: "uint256", | ||
name: "", | ||
type: "uint256", | ||
}, | ||
], | ||
stateMutability: "view", | ||
type: "function", | ||
}, | ||
] as const; | ||
|
||
const ERC20_ERC721_ABI = [ | ||
{ | ||
inputs: [ | ||
{ | ||
internalType: "address", | ||
name: "account", | ||
type: "address", | ||
}, | ||
], | ||
name: "balanceOf", | ||
outputs: [ | ||
{ | ||
internalType: "uint256", | ||
name: "", | ||
type: "uint256", | ||
}, | ||
], | ||
stateMutability: "view", | ||
type: "function", | ||
}, | ||
] as const; | ||
|
||
interface UseTokenValidationParams { | ||
address?: string; | ||
enabled?: boolean; | ||
} | ||
|
||
interface TokenValidationResult { | ||
isValidating: boolean; | ||
isValid: boolean | null; | ||
error: string | null; | ||
} | ||
|
||
/** | ||
* Hook to validate if an address is a valid ERC20 or ERC721 token by attempting to call balanceOf(address) | ||
* @param address The address to validate | ||
* @param enabled Whether validation should be enabled | ||
* @returns Validation state including loading, result, and error | ||
*/ | ||
export const useERC20ERC721Validation = ({ | ||
address, | ||
enabled = true, | ||
}: UseTokenValidationParams): TokenValidationResult => { | ||
return useTokenValidation({ | ||
address, | ||
enabled, | ||
abi: ERC20_ERC721_ABI, | ||
contractCall: (contract) => contract.read.balanceOf(["0x0000000000000000000000000000000000000000"]), | ||
tokenType: "ERC-20 or ERC-721", | ||
}); | ||
}; | ||
|
||
/** | ||
* Hook to validate if an address is a valid ERC1155 token by attempting to call balanceOf(address, tokenId) | ||
* @param address The address to validate | ||
* @param enabled Whether validation should be enabled | ||
* @returns Validation state including loading, result, and error | ||
*/ | ||
export const useERC1155Validation = ({ address, enabled = true }: UseTokenValidationParams): TokenValidationResult => { | ||
return useTokenValidation({ | ||
address, | ||
enabled, | ||
abi: ERC1155_ABI, | ||
contractCall: (contract) => contract.read.balanceOf(["0x0000000000000000000000000000000000000000", 0]), | ||
tokenType: "ERC-1155", | ||
}); | ||
}; | ||
|
||
/** | ||
* Generic hook for token contract validation | ||
*/ | ||
const useTokenValidation = ({ | ||
address, | ||
enabled = true, | ||
abi, | ||
contractCall, | ||
tokenType, | ||
}: UseTokenValidationParams & { | ||
abi: readonly any[]; | ||
contractCall: (contract: any) => Promise<any>; | ||
tokenType: string; | ||
}): TokenValidationResult => { | ||
const publicClient = usePublicClient(); | ||
const chainId = useChainId(); | ||
const [debouncedAddress, setDebouncedAddress] = useState<string>(); | ||
|
||
// Debounce address changes to avoid excessive network calls | ||
useEffect(() => { | ||
const timer = setTimeout(() => { | ||
setDebouncedAddress(address); | ||
}, 500); | ||
|
||
return () => clearTimeout(timer); | ||
}, [address]); | ||
|
||
// Early validation - check format | ||
const isValidFormat = useMemo(() => { | ||
if (!debouncedAddress || debouncedAddress.trim() === "") return null; | ||
return isAddress(debouncedAddress); | ||
}, [debouncedAddress]); | ||
|
||
// Contract validation query | ||
const { | ||
data: isValidContract, | ||
isLoading, | ||
error, | ||
} = useQuery({ | ||
queryKey: [`${tokenType}-validation`, chainId, debouncedAddress], | ||
enabled: enabled && !isUndefined(publicClient) && Boolean(isValidFormat), | ||
staleTime: 300000, // Cache for 5 minutes | ||
retry: 1, // Only retry once to fail faster | ||
retryDelay: 1000, // Short retry delay | ||
queryFn: async () => { | ||
if (!publicClient || !debouncedAddress) { | ||
throw new Error("Missing required dependencies"); | ||
} | ||
|
||
try { | ||
const contract = getContract({ | ||
address: debouncedAddress as `0x${string}`, | ||
abi, | ||
client: publicClient, | ||
}); | ||
|
||
// Execute the contract call specific to the token type | ||
await contractCall(contract); | ||
|
||
return true; | ||
} catch { | ||
throw new Error(`Address does not implement ${tokenType} interface`); | ||
} | ||
}, | ||
}); | ||
|
||
// Determine final validation state | ||
const isValid = useMemo(() => { | ||
if (!debouncedAddress || debouncedAddress.trim() === "") { | ||
return null; | ||
} | ||
|
||
if (isValidFormat === false) { | ||
return false; | ||
} | ||
|
||
if (isLoading) { | ||
return null; // Still validating | ||
} | ||
|
||
return isValidContract === true; | ||
}, [debouncedAddress, isValidFormat, isLoading, isValidContract]); | ||
|
||
const validationError = useMemo(() => { | ||
if (!debouncedAddress || debouncedAddress.trim() === "") { | ||
return null; | ||
} | ||
|
||
if (isValidFormat === false) { | ||
return "Invalid Ethereum address format"; | ||
} | ||
|
||
if (error) { | ||
const errorMessage = error instanceof Error ? error.message : "Unknown error"; | ||
if (errorMessage.includes("not a contract")) { | ||
return "Address is not a contract"; | ||
} | ||
if (errorMessage.includes(`does not implement ${tokenType}`)) { | ||
return `Not a valid ${tokenType} token address`; | ||
} | ||
return "Network error - please try again"; | ||
} | ||
|
||
return null; | ||
}, [debouncedAddress, isValidFormat, error, tokenType]); | ||
|
||
return { | ||
isValidating: isLoading && enabled && !!debouncedAddress, | ||
isValid, | ||
error: validationError, | ||
}; | ||
}; |
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
Oops, something went wrong.
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.