Skip to content
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

Add tests for op-app #25

Merged
merged 4 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion packages/op-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"typecheck": "tsc --noEmit --emitDeclarationOnly false",
"lint": "eslint \"**/*.{ts,tsx}\" && pnpm prettier --check \"**/*.{ts,tsx}\"",
"lint:fix": "eslint \"**/*.{ts,tsx}\" --fix --quiet && pnpm prettier \"**/*.{ts,tsx}\" --write --loglevel=warn",
"codegen": "ts-node --esm ./scripts/codegen"
"codegen": "ts-node --esm ./scripts/codegen",
"test": "vitest run"
},
"dependencies": {
"@eth-optimism/contracts-ts": "^0.17.0",
Expand All @@ -24,6 +25,7 @@
"devDependencies": {
"@eth-optimism/superchain-registry": "github:ethereum-optimism/superchain-registry",
"@tanstack/react-query": "^5.10.0",
"@testing-library/react": "^14.1.2",
"@types/node": "^20.10.0",
"@types/react": "^18.2.37",
"@types/react-dom": "^18.2.15",
Expand All @@ -34,13 +36,15 @@
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.4",
"eta": "^3.1.1",
"jsdom": "^23.2.0",
"node-fetch": "^3.3.2",
"op-viem": "1.1.0",
"op-wagmi": "^0.2.2",
"ts-node": "^10.9.1",
"typescript": "^5.2.2",
"viem": "2.0.3",
"vite": "^5.0.5",
"vitest": "^1.1.3",
"wagmi": "2.0.3"
},
"peerDependencies": {
Expand Down
27 changes: 27 additions & 0 deletions packages/op-app/src/hooks/useIsNetworkUnsupported.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { waitFor } from '@testing-library/react'
import { describe, expect, it } from 'vitest'

import { renderConnectedHook } from '../test-utils/react'
import { useIsNetworkUnsupported } from '.'

describe('useIsNetowrkUnsupported', () => {
it('should return supported', () => {
const { result } = renderConnectedHook(() => useIsNetworkUnsupported(), {
network: 'l2',
})

waitFor(() => {
expect(result.current.isUnsupported).toBeTruthy()
})
})

it('should return unsupported', () => {
const { result } = renderConnectedHook(() => useIsNetworkUnsupported(), {
network: 'unsupported',
})

waitFor(() => {
expect(result.current.isUnsupported).toBeFalsy()
})
})
})
22 changes: 22 additions & 0 deletions packages/op-app/src/hooks/useL1PublicClient.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { describe, expect, it } from 'vitest'

import { l1 } from '../test-utils/chains'
import { renderConnectedHook } from '../test-utils/react'
import { useL1PublicClient } from '.'

describe('useL1PublicClient', () => {
it('should return default l1PublicClient', () => {
const { result } = renderConnectedHook(() =>
useL1PublicClient({ type: 'op' }),
)

expect(result.current.l1PublicClient.chain?.id).toEqual(l1.id)
})

it('should return expected l1PublicClient when providing a chain id', () => {
const { result } = renderConnectedHook(() =>
useL1PublicClient({ type: 'op', chainId: l1.id }),
)
expect(result.current.l1PublicClient.chain?.id).toEqual(l1.id)
})
})
21 changes: 21 additions & 0 deletions packages/op-app/src/hooks/useL2PublicClient.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { describe, expect, it } from 'vitest'

import { l2 } from '../test-utils/chains'
import { renderConnectedHook } from '../test-utils/react'
import { useL2PublicClient } from '.'

describe('useL2PublicClient', () => {
it('should return default l1PublicClient', () => {
const { result } = renderConnectedHook(() =>
useL2PublicClient({ type: 'op' }),
)
expect(result.current.l2PublicClient.chain?.id).toEqual(l2.id)
})

it('should return expected l1PublicClient when providing a chain id', () => {
const { result } = renderConnectedHook(() =>
useL2PublicClient({ type: 'op', chainId: l2.id }),
)
expect(result.current.l2PublicClient.chain?.id).toEqual(l2.id)
})
})
35 changes: 35 additions & 0 deletions packages/op-app/src/hooks/useOPNetwork.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { describe, expect, it } from 'vitest'

import type { NetworkType } from '..'
import { networkPairsByGroup, useOPNetwork } from '..'
import { renderConnectedHook } from '../test-utils/react'

describe('useOPNetwork', () => {
Object.keys(networkPairsByGroup).forEach((group) => {
const networkPairs = networkPairsByGroup[group as NetworkType]

Object.keys(networkPairs).forEach((network) => {
it(`should return expected l1 & l2 for ${group} ${network}`, () => {
const [expectedL1, expectedL2] = networkPairs[network]

const { result: l1FilterResult } = renderConnectedHook(() =>
useOPNetwork({
type: group as NetworkType,
chainId: expectedL1.id,
}),
)
expect(l1FilterResult.current.networkPair.l1.id).toEqual(expectedL1.id)
expect(l1FilterResult.current.networkPair.l2.id).toEqual(expectedL2.id)

const { result: l2FilterResult } = renderConnectedHook(() =>
useOPNetwork({
type: group as NetworkType,
chainId: expectedL2.id,
}),
)
expect(l2FilterResult.current.networkPair.l1.id).toEqual(expectedL1.id)
expect(l2FilterResult.current.networkPair.l2.id).toEqual(expectedL2.id)
})
})
})
})
20 changes: 20 additions & 0 deletions packages/op-app/src/hooks/useOPTokens.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, it } from 'vitest'

import { renderConnectedHook } from '../test-utils/react'
import { useOPTokens } from '.'

describe('useOPTokens', () => {
it('should return all tokens for the chain id provided', () => {
const chainId = 1
const { result } = renderConnectedHook(() => useOPTokens({ chainId }))

expect(result.current.ethToken.extensions.opTokenId.toLowerCase()).toEqual(
'eth',
)

result.current.erc20Tokens.forEach((token) => {
expect(token.chainId).toEqual(chainId)
expect(token.extensions.opTokenId.toLowerCase() !== 'eth')
})
})
})
53 changes: 53 additions & 0 deletions packages/op-app/src/hooks/useOPWagmiConfig.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { predeploys } from '@eth-optimism/contracts-ts'
import { describe, expect, it } from 'vitest'

import type { NetworkType } from '..'
import { deploymentAddresses, networkPairsByGroup, useOPWagmiConfig } from '..'
import { renderConnectedHook } from '../test-utils/react'

describe('useOPWagmiConfig', () => {
const groups = Object.keys(networkPairsByGroup) as NetworkType[]

groups.forEach((group) => {
const networkPairs = networkPairsByGroup[group]

Object.entries(networkPairs).forEach(([network, [_, l2]]) => {
it(`should return valid OpConfig with correct protocol contract addresses for ${group} ${network}`, () => {
const { result } = renderConnectedHook(() =>
useOPWagmiConfig({ type: group, chainId: l2.id }),
)

const deploymentAddress = deploymentAddresses[l2.id]
expect(deploymentAddress).toBeTruthy()

const addressConfig = result.current.opConfig?.l2chains[l2.id]
expect(addressConfig).toBeTruthy()

// l1 addresses
expect(addressConfig?.l1Addresses.portal.address).toEqual(
deploymentAddress.OptimismPortalProxy,
)
expect(addressConfig?.l1Addresses.l2OutputOracle.address).toEqual(
deploymentAddress.L2OutputOracleProxy,
)
expect(addressConfig?.l1Addresses.l1StandardBridge.address).toEqual(
deploymentAddress.L1StandardBridgeProxy,
)
expect(
addressConfig?.l1Addresses.l1CrossDomainMessenger.address,
).toEqual(deploymentAddress.L1CrossDomainMessengerProxy)
expect(addressConfig?.l1Addresses.l1Erc721Bridge.address).toEqual(
deploymentAddress.L1ERC721BridgeProxy,
)

// l2 addresses
expect(
addressConfig?.l2Addresses.l2L1MessagePasserAddress.address,
).toEqual(predeploys.L2ToL1MessagePasser.address)
expect(addressConfig?.l2Addresses.l2StandardBridge.address).toEqual(
predeploys.L2StandardBridge.address,
)
})
})
})
})
7 changes: 3 additions & 4 deletions packages/op-app/src/hooks/useOPWagmiConfig.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { predeploys } from '@eth-optimism/contracts-ts'
import { useMemo } from 'react'
import type { Config } from 'wagmi'
import { useConfig } from 'wagmi'

import { deploymentAddresses } from '../configs/deploymentAddresses'
import type { NetworkType } from '../types'
import type { NetworkType, OpConfig } from '../types'
import { useOPNetwork } from './useOPNetwork'

export type UseOPWagmiConfigArgs = {
Expand All @@ -16,7 +15,7 @@ export const useOPWagmiConfig = ({ type, chainId }: UseOPWagmiConfigArgs) => {
const config = useConfig()
const { networkPair } = useOPNetwork({ type, chainId })

const opConfig = useMemo<Config | undefined>(() => {
const opConfig = useMemo<OpConfig | undefined>(() => {
if (!networkPair) {
return
}
Expand Down Expand Up @@ -64,7 +63,7 @@ export const useOPWagmiConfig = ({ type, chainId }: UseOPWagmiConfigArgs) => {
},
},
},
} as Config // we typecase to Config here, because op-wagmi for now is missing the OpConfig export
} as OpConfig
}, [config, networkPair])

return { opConfig }
Expand Down
38 changes: 38 additions & 0 deletions packages/op-app/src/test-utils/chains.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { Chain } from 'viem'

import { networkPairsByGroup } from '..'
import { L1_PORT, L2_PORT } from './constants'

const [mainnet, opMainnet] = networkPairsByGroup.op.mainnet

const vitestPool = process.env.VITEST_vitestPool_ID ?? 1

export const l1 = {
...mainnet,
port: L1_PORT,
rpcUrls: {
default: {
http: [`http://127.0.0.1:${L1_PORT}/${vitestPool}`],
webSocket: [`ws://127.0.0.1:${L1_PORT}/${vitestPool}`],
},
public: {
http: [`http://127.0.0.1:${L1_PORT}/${vitestPool}`],
webSocket: [`ws://127.0.0.1:${L1_PORT}/${vitestPool}`],
},
},
} as Chain

export const l2 = {
...opMainnet,
port: L2_PORT,
rpcUrls: {
default: {
http: [`http://127.0.0.1:${L2_PORT}/${vitestPool}`],
webSocket: [`ws://127.0.0.1:${L2_PORT}/${vitestPool}`],
},
public: {
http: [`http://127.0.0.1:${L2_PORT}/${vitestPool}`],
webSocket: [`ws://127.0.0.1:${L2_PORT}/${vitestPool}`],
},
},
} as Chain
3 changes: 3 additions & 0 deletions packages/op-app/src/test-utils/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const L1_PORT = 8545
export const L2_PORT = 8546
export const TEST_ACCOUNT = '0x0BB3e1eE3A7C97aC27835BACa5b3D5825D1A788a'
97 changes: 97 additions & 0 deletions packages/op-app/src/test-utils/react.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { RenderHookResult } from '@testing-library/react'
import { renderHook } from '@testing-library/react'
import { createElement } from 'react'
import type { Address } from 'viem'
import type { Config, WagmiProviderProps } from 'wagmi'
import { createConfig, http, WagmiProvider } from 'wagmi'
import { mock } from 'wagmi/connectors'

import type { OpConfig } from '..'
import { l1, l2 } from './chains'
import { TEST_ACCOUNT } from './constants'

export type RenderConnectedHooksArgs = {
type: 'l1' | 'l2' | 'unsupported'
}

export const queryClient = new QueryClient()

const opConfig = {
...createConfig({
chains: [l1, l2],
connectors: [mock({ accounts: [TEST_ACCOUNT] })],
pollingInterval: 100,
storage: null,
transports: {
[l1.id]: http(),
[l2.id]: http(),
},
}),
l2chains: {
[l2.id]: l2,
},
} as Config

function mockConnectedWallet(chainId: number, account: Address): Config {
return {
...opConfig,
state: {
chainId: chainId,
connections: new Map().set(opConfig.connectors[0].uid, {
accounts: [account],
chainId: chainId,
connector: opConfig.connectors[0],
}),
current: opConfig.connectors[0].uid,
status: 'connected',
},
} as Config
}

type WrapperProps = { children?: React.ReactNode | undefined }

export function createWrapper<
TComponent extends React.FunctionComponent<WagmiProviderProps>,
>(Wrapper: TComponent, props: WagmiProviderProps) {
return function CreatedWrapper({ children }: WrapperProps) {
return createElement(
Wrapper,
props,
createElement(QueryClientProvider, { client: queryClient }, children),
)
}
}

export type RenderConnectedHooksOptions =
| {
network?: 'l1' | 'l2' | 'unsupported'
account?: Address
config?: OpConfig
}
| undefined

export function renderConnectedHook<Result, Props>(
render: (props: Props) => Result,
connection?: RenderConnectedHooksOptions,
options?: RenderConnectedHooksOptions,
): RenderHookResult<Result, Props> {
queryClient.clear()

let chainId = 100
if (!connection || connection.network === 'l1') {
chainId = l1.id
} else if (connection.network === 'l2') {
chainId = l2.id
}

return renderHook(render, {
wrapper: createWrapper(WagmiProvider, {
config: connection?.config
? connection.config
: mockConnectedWallet(chainId, connection?.account ?? TEST_ACCOUNT),
reconnectOnMount: false,
}),
...options,
})
}
Loading