Skip to content

Commit

Permalink
feat: chainId inference
Browse files Browse the repository at this point in the history
  • Loading branch information
tmm committed Jun 16, 2023
1 parent ea27d80 commit a2a6819
Show file tree
Hide file tree
Showing 29 changed files with 353 additions and 259 deletions.
40 changes: 40 additions & 0 deletions docs/react/createConfig.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# createConfig

Creates new [`Config`](#return-type).

## Import

```ts
import { createConfig } from 'wagmi'
```

## Usage

::: code-group
```tsx [index.ts]
import { mainnet, sepolia } from 'viem/chains'
import { createConfig } from 'wagmi'

const config = createConfig({
chains: [mainnet, sepolia],
transports: {
[mainnet.id]: http('https://...'),
[sepolia.id]: http('https://...'),
},
})
```
:::

## Parameters

```ts
import { type CreateConfigParameters } from 'wagmi'
```

## Return Type

The wagmi `Config` is a framework agnostic object that manages connections and state.

```ts
import { type Config } from 'wagmi'
```
35 changes: 21 additions & 14 deletions packages/core/src/actions/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@ import { type CreateConnectorFn } from '../connector.js'
import { ConnectorAlreadyConnectedError } from '../errors/config.js'
import type { IsUndefined, Pretty } from '../types/utils.js'

export type ConnectParameters = {
chainId?: number | undefined
export type ConnectParameters<config extends Config = Config> = {
chainId?: config['chains'][number]['id'] | undefined
connector: CreateConnectorFn | Connector
}

export type ConnectReturnType = {
export type ConnectReturnType<config extends Config = Config> = {
accounts: readonly Address[]
chainId: number
chainId:
| config['chains'][number]['id']
| (number extends config['chains'][number]['id'] ? number : number & {})
}

export type ConnectError =
Expand All @@ -30,10 +32,10 @@ export type ConnectError =
| Error

/** https://wagmi.sh/core/actions/connect */
export async function connect(
config: Config,
{ chainId, connector: connector_ }: ConnectParameters,
): Promise<ConnectReturnType> {
export async function connect<config extends Config>(
config: config,
{ chainId, connector: connector_ }: ConnectParameters<config>,
): Promise<ConnectReturnType<config>> {
// "Register" connector if not already created
let connector: Connector
if (typeof connector_ === 'function') {
Expand Down Expand Up @@ -85,29 +87,34 @@ export async function connect(
///////////////////////////////////////////////////////////////////////////
// TanStack Query

export type ConnectMutationData = Pretty<ConnectReturnType>
export type ConnectMutationData<config extends Config> = Pretty<
ConnectReturnType<config>
>
export type ConnectMutationVariables<
config extends Config,
connector extends ConnectParameters['connector'] | undefined,
> = Pretty<
{
chainId?: number | undefined
chainId?: ConnectParameters<config>['chainId']
} & (IsUndefined<connector> extends false
? { connector?: ConnectParameters['connector'] | undefined }
: { connector: ConnectParameters['connector'] | undefined })
>
export type ConnectMutationParameters<
config extends Config,
connector extends ConnectParameters['connector'] | undefined,
> = Pretty<{
chainId?: ConnectParameters['chainId'] | undefined
chainId?: ConnectParameters<config>['chainId']
connector?: connector | ConnectParameters['connector'] | undefined
}>

/** https://wagmi.sh/core/actions/connect#tanstack-query */
export const connectMutationOptions = <
config extends Config,
connector extends ConnectParameters['connector'] | undefined,
>(
config: Config,
{ chainId, connector }: ConnectMutationParameters<connector>,
{ chainId, connector }: ConnectMutationParameters<config, connector>,
) =>
({
mutationFn(variables) {
Expand All @@ -118,7 +125,7 @@ export const connectMutationOptions = <
},
mutationKey: ['connect', { connector, chainId }],
}) as const satisfies MutationOptions<
ConnectMutationData,
ConnectMutationData<config>,
ConnectError,
ConnectMutationVariables<connector>
ConnectMutationVariables<config, connector>
>
8 changes: 4 additions & 4 deletions packages/core/src/actions/disconnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { type MutationOptions } from '@tanstack/query-core'
import { type Config, type Connection, type Connector } from '../config.js'
import type { BaseError } from '../errors/base.js'
import { ConnectorNotFoundError } from '../errors/config.js'
import type { NonVoid, Pretty } from '../types/utils.js'
import type { Pretty } from '../types/utils.js'

export type DisconnectParameters = {
connector?: Connector | undefined
Expand Down Expand Up @@ -60,9 +60,9 @@ export type DisconnectMutationData = void
export type DisconnectMutationVariables = Pretty<{
connector?: Connector | undefined
}> | void
export type DisconnectMutationParameters = Pretty<
NonVoid<DisconnectMutationVariables>
>
export type DisconnectMutationParameters = Pretty<{
connector?: Connector | undefined
}>

/** https://wagmi.sh/core/actions/disconnect#tanstack-query */
export const disconnectMutationOptions = (
Expand Down
47 changes: 28 additions & 19 deletions packages/core/src/actions/getBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
formatUnits,
} from 'viem'

import { type Config } from '../config.js'
import type { Config } from '../config.js'
import { type Unit } from '../types/unit.js'
import { type PartialBy, type Pretty } from '../types/utils.js'
import { getUnit } from '../utils/getUnit.js'
Expand All @@ -17,9 +17,9 @@ import type {
WatchBlockNumberReturnType,
} from './getBlockNumber.js'

export type GetBalanceParameters = Pretty<
export type GetBalanceParameters<config extends Config = Config> = Pretty<
GetBalanceParameters_ & {
chainId?: number | undefined
chainId?: config['chains'][number]['id'] | undefined
token?: Address | undefined
unit?: Unit | undefined
}
Expand All @@ -39,9 +39,15 @@ export type GetBalanceError =
| Error

/** https://wagmi.sh/core/actions/getBalance */
export async function getBalance(
config: Config,
{ address, chainId, token, unit = 'ether', ...rest }: GetBalanceParameters,
export async function getBalance<config extends Config>(
config: config,
{
address,
chainId,
token,
unit = 'ether',
...rest
}: GetBalanceParameters<config>,
): Promise<GetBalanceReturnType> {
const publicClient = config.getPublicClient({ chainId })

Expand All @@ -66,8 +72,8 @@ export async function getBalance(
///////////////////////////////////////////////////////////////////////////
// Watcher

export type WatchBalanceParameters = Pretty<
Omit<GetBalanceParameters, 'blockNumber' | 'blockTag'> & {
export type WatchBalanceParameters<config extends Config = Config> = Pretty<
Omit<GetBalanceParameters<config>, 'blockNumber' | 'blockTag'> & {
onBalance: (parameters: GetBalanceReturnType) => void
onError?: (error: GetBalanceError | GetBlockNumberError) => void
syncConnectedChain?: boolean
Expand All @@ -78,8 +84,8 @@ export type WatchBalanceReturnType = () => void

// TODO: wrap in viem's `observe` to avoid duplicate invocations.
/** https://wagmi.sh/core/actions/getBalance#watcher */
export function watchBalance(
config: Config,
export function watchBalance<config extends Config>(
config: config,
{
address,
chainId,
Expand All @@ -88,7 +94,7 @@ export function watchBalance(
syncConnectedChain = config._internal.syncConnectedChain,
token,
unit,
}: WatchBalanceParameters,
}: WatchBalanceParameters<config>,
): WatchBalanceReturnType {
let unwatch: WatchBlockNumberReturnType | undefined

Expand Down Expand Up @@ -150,24 +156,27 @@ export function watchBalance(
///////////////////////////////////////////////////////////////////////////
// TanStack Query

export type GetBalanceQueryParameters = PartialBy<
GetBalanceParameters,
export type GetBalanceQueryParameters<config extends Config> = PartialBy<
GetBalanceParameters<config>,
'address'
>
export type GetBalanceQueryKey = readonly ['balance', GetBalanceQueryParameters]
export type GetBalanceQueryKey<config extends Config> = readonly [
'balance',
GetBalanceQueryParameters<config>,
]
export type GetBalanceQueryFnData = NonNullable<GetBalanceReturnType> | null

/** https://wagmi.sh/core/actions/getBalance#tanstack-query */
export const getBalanceQueryOptions = (
config: Config,
export const getBalanceQueryOptions = <config extends Config>(
config: config,
{
address,
blockNumber,
blockTag,
chainId,
token,
unit,
}: GetBalanceQueryParameters,
}: GetBalanceQueryParameters<config>,
) =>
({
async queryFn() {
Expand All @@ -179,13 +188,13 @@ export const getBalanceQueryOptions = (
chainId,
token,
unit,
} as GetBalanceParameters)
} as GetBalanceParameters<config>)
return balance ?? null
},
queryKey: ['balance', { address, chainId, token, unit }],
}) as const satisfies QueryOptions<
GetBalanceQueryFnData,
GetBalanceError,
GetBalanceQueryFnData,
GetBalanceQueryKey
GetBalanceQueryKey<config>
>
33 changes: 17 additions & 16 deletions packages/core/src/actions/getBlockNumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import {

import { type Config } from '../config.js'

export type GetBlockNumberParameters = {
chainId?: number | undefined
export type GetBlockNumberParameters<config extends Config = Config> = {
chainId?: config['chains'][number]['id'] | undefined
}

export type GetBlockNumberReturnType = GetBlockNumberReturnType_ | undefined
Expand All @@ -19,9 +19,9 @@ export type GetBlockNumberError =
| Error

/** https://wagmi.sh/core/actions/getBlockNumber */
export function getBlockNumber(
config: Config,
{ chainId }: GetBlockNumberParameters = {},
export function getBlockNumber<config extends Config>(
config: config,
{ chainId }: GetBlockNumberParameters<config> = {},
): Promise<GetBlockNumberReturnType> {
const publicClient = config.getPublicClient({ chainId })
return publicClient?.getBlockNumber()
Expand All @@ -30,8 +30,8 @@ export function getBlockNumber(
///////////////////////////////////////////////////////////////////////////
// Watcher

export type WatchBlockNumberParameters = {
chainId?: number | undefined
export type WatchBlockNumberParameters<config extends Config = Config> = {
chainId?: config['chains'][number]['id'] | undefined
onBlockNumber: WatchBlockNumberParameters_['onBlockNumber']
onError?: WatchBlockNumberParameters_['onError']
syncConnectedChain?: boolean
Expand All @@ -41,14 +41,14 @@ export type WatchBlockNumberReturnType = () => void

// TODO: wrap in viem's `observe` to avoid duplicate invocations.
/** https://wagmi.sh/core/actions/getBlockNumber#watcher */
export function watchBlockNumber(
config: Config,
export function watchBlockNumber<config extends Config>(
config: config,
{
chainId,
onBlockNumber,
onError,
syncConnectedChain = config._internal.syncConnectedChain,
}: WatchBlockNumberParameters,
}: WatchBlockNumberParameters<config>,
): WatchBlockNumberReturnType {
let unwatch: WatchBlockNumberReturnType | undefined

Expand Down Expand Up @@ -94,18 +94,19 @@ export function watchBlockNumber(
///////////////////////////////////////////////////////////////////////////
// TanStack Query

export type GetBlockNumberQueryParameters = GetBlockNumberParameters
export type GetBlockNumberQueryKey = readonly [
export type GetBlockNumberQueryParameters<config extends Config> =
GetBlockNumberParameters<config>
export type GetBlockNumberQueryKey<config extends Config> = readonly [
'blockNumber',
{ chainId: GetBlockNumberQueryParameters['chainId'] },
{ chainId: GetBlockNumberQueryParameters<config>['chainId'] },
]
export type GetBlockNumberQueryFnData =
NonNullable<GetBlockNumberReturnType> | null

/** https://wagmi.sh/core/actions/getBlockNumber#tanstack-query */
export const getBlockNumberQueryOptions = (
export const getBlockNumberQueryOptions = <config extends Config>(
config: Config,
{ chainId }: GetBlockNumberQueryParameters = {},
{ chainId }: GetBlockNumberQueryParameters<config> = {},
) =>
({
gcTime: 0,
Expand All @@ -118,5 +119,5 @@ export const getBlockNumberQueryOptions = (
GetBlockNumberQueryFnData,
GetBlockNumberError,
GetBlockNumberQueryFnData,
GetBlockNumberQueryKey
GetBlockNumberQueryKey<config>
>
4 changes: 2 additions & 2 deletions packages/core/src/actions/getChainId.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ describe('watchChainId', () => {
})
config.setState((x) => ({ ...x, chainId: testChains.anvilTwo.id }))
config.setState((x) => ({ ...x, chainId: testChains.anvil.id }))
config.setState((x) => ({ ...x, chainId: 69 }))
config.setState((x) => ({ ...x, chainId: 456 }))

expect(chainIds).toMatchInlineSnapshot(`
[
123,
69,
456,
]
`)

Expand Down
Loading

0 comments on commit a2a6819

Please sign in to comment.