import type { Abi, Address, ContractFunctionArgs, ContractFunctionName, } from 'viem' import type { Config } from '../../createConfig.js' import type { UnionCompute, UnionStrictOmit } from '../../types/utils.js' import { getChainId } from '../getChainId.js' import { type ReadContractParameters, type ReadContractReturnType, readContract, } from '../readContract.js' type stateMutability = 'pure' | 'view' export type CreateReadContractParameters< abi extends Abi | readonly unknown[], address extends Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, > = { abi: abi | Abi | readonly unknown[] address?: address | Address | Record | undefined functionName?: | functionName | ContractFunctionName | undefined } export type CreateReadContractReturnType< abi extends Abi | readonly unknown[], address extends Address | Record | undefined, functionName extends ContractFunctionName | undefined, /// omittedProperties extends 'abi' | 'address' | 'chainId' | 'functionName' = | 'abi' | (address extends undefined ? never : 'address') | (address extends Record ? 'chainId' : never) | (functionName extends undefined ? never : 'functionName'), > = < config extends Config, name extends functionName extends ContractFunctionName ? functionName : ContractFunctionName, args extends ContractFunctionArgs, >( config: config, parameters: UnionCompute< UnionStrictOmit< ReadContractParameters, omittedProperties > > & (address extends Record ? { chainId?: keyof address | undefined } : unknown), ) => Promise> export function createReadContract< const abi extends Abi | readonly unknown[], const address extends | Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, >( c: CreateReadContractParameters, ): CreateReadContractReturnType { if (c.address !== undefined && typeof c.address === 'object') return (config, parameters) => { const configChainId = getChainId(config) const chainId = (parameters as { chainId?: number })?.chainId ?? configChainId return readContract(config, { ...(parameters as any), ...(c.functionName ? { functionName: c.functionName } : {}), address: c.address?.[chainId], abi: c.abi, }) } return (config, parameters) => { return readContract(config, { ...(parameters as any), ...(c.address ? { address: c.address } : {}), ...(c.functionName ? { functionName: c.functionName } : {}), abi: c.abi, }) } }