Skip to content

Commit

Permalink
chore: portable types (#554)
Browse files Browse the repository at this point in the history
  • Loading branch information
tmm committed May 23, 2023
1 parent 81a3aed commit d5297c6
Show file tree
Hide file tree
Showing 9 changed files with 106 additions and 83 deletions.
5 changes: 5 additions & 0 deletions .changeset/dull-pens-attack.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"viem": patch
---

Fixed portable types
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2023 weth, LLC
Copyright (c) 2023-present weth, LLC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
61 changes: 14 additions & 47 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -111,39 +111,17 @@
},
"typesVersions": {
"*": {
"abi": [
"./dist/types/abi.d.ts"
],
"accounts": [
"./dist/types/accounts/index.d.ts"
],
"chains": [
"./dist/types/chains.d.ts"
],
"contract": [
"./dist/types/contract.d.ts"
],
"ens": [
"./dist/types/ens.d.ts"
],
"ethers": [
"./dist/types/ethers.d.ts"
],
"public": [
"./dist/types/public.d.ts"
],
"test": [
"./dist/types/test.d.ts"
],
"utils": [
"./dist/types/utils/index.d.ts"
],
"wallet": [
"./dist/types/wallet.d.ts"
],
"window": [
"./dist/types/window.d.ts"
]
"abi": ["./dist/types/abi.d.ts"],
"accounts": ["./dist/types/accounts/index.d.ts"],
"chains": ["./dist/types/chains.d.ts"],
"contract": ["./dist/types/contract.d.ts"],
"ens": ["./dist/types/ens.d.ts"],
"ethers": ["./dist/types/ethers.d.ts"],
"public": ["./dist/types/public.d.ts"],
"test": ["./dist/types/test.d.ts"],
"utils": ["./dist/types/utils/index.d.ts"],
"wallet": ["./dist/types/wallet.d.ts"],
"window": ["./dist/types/window.d.ts"]
}
},
"dependencies": {
Expand Down Expand Up @@ -183,23 +161,14 @@
},
"license": "MIT",
"repository": "wagmi-dev/viem",
"authors": [
"awkweb.eth",
"jxom.eth"
],
"authors": ["awkweb.eth", "jxom.eth"],
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/wagmi-dev"
}
],
"keywords": [
"eth",
"ethereum",
"dapps",
"wallet",
"web3"
],
"keywords": ["eth", "ethereum", "dapps", "wallet", "web3"],
"size-limit": [
{
"path": "./dist/cjs/index.js"
Expand All @@ -217,9 +186,7 @@
"vitepress@1.0.0-alpha.61": "patches/vitepress@1.0.0-alpha.61.patch"
},
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search"
]
"ignoreMissing": ["@algolia/client-search"]
}
}
}
6 changes: 3 additions & 3 deletions src/_test/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { custom } from '../clients/transports/custom.js'
import { http } from '../clients/transports/http.js'
import { webSocket } from '../clients/transports/webSocket.js'
import type { Chain } from '../types/chain.js'
import { RpcError } from '../types/eip1193.js'
import { ProviderRpcError } from '../types/eip1193.js'
import type { Hex } from '../types/misc.js'
import { namehash } from '../utils/ens/namehash.js'
import { rpc } from '../utils/rpc.js'
Expand Down Expand Up @@ -79,14 +79,14 @@ const provider = {
}
if (method === 'wallet_watchAsset') {
if (params.type === 'ERC721') {
throw new RpcError(-32602, 'Token type ERC721 not supported.')
throw new ProviderRpcError(-32602, 'Token type ERC721 not supported.')
}
return true
}
if (method === 'wallet_addEthereumChain') return null
if (method === 'wallet_switchEthereumChain') {
if (params[0].chainId === '0xfa') {
throw new RpcError(-4902, 'Unrecognized chain.')
throw new ProviderRpcError(-4902, 'Unrecognized chain.')
}
return null
}
Expand Down
58 changes: 43 additions & 15 deletions src/errors/rpc.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,27 @@
import type { Prettify } from '../types/utils.js'
import { BaseError } from './base.js'
import { RpcRequestError } from './request.js'

const unknownErrorCode = -1

type RpcErrorOptions = {
code?: number
export type RpcErrorCode =
| -1
| -32700 // Parse error
| -32600 // Invalid request
| -32601 // Method not found
| -32602 // Invalid params
| -32603 // Internal error
| -32000 // Invalid input
| -32001 // Resource not found
| -32002 // Resource unavailable
| -32003 // Transaction rejected
| -32004 // Method not supported
| -32005 // Limit exceeded
| -32006 // JSON-RPC version not supported
| -32042 // Method not found

type RpcErrorOptions<TCode extends number = RpcErrorCode> = {
code?: TCode | (number & {})
docsPath?: string
metaMessages?: string[]
shortMessage: string
Expand All @@ -15,17 +32,14 @@ type RpcErrorOptions = {
*
* - EIP https://eips.ethereum.org/EIPS/eip-1474
*/
export class RpcError extends BaseError {
code: number
export class RpcError<TCode extends number = RpcErrorCode> extends BaseError {
override name = 'RpcError'

code: TCode | (number & {})

constructor(
cause: Error,
{
code = unknownErrorCode,
docsPath,
metaMessages,
shortMessage,
}: RpcErrorOptions,
{ code, docsPath, metaMessages, shortMessage }: RpcErrorOptions<TCode>,
) {
super(shortMessage, {
cause,
Expand All @@ -34,25 +48,39 @@ export class RpcError extends BaseError {
metaMessages || (cause as { metaMessages?: string[] })?.metaMessages,
})
this.name = cause.name
this.code = cause instanceof RpcRequestError ? cause.code : code
this.code = (
cause instanceof RpcRequestError ? cause.code : code ?? unknownErrorCode
) as TCode
}
}

export type ProviderRpcErrorCode =
| 4001 // User Rejected Request
| 4100 // Unauthorized
| 4200 // Unsupported Method
| 4900 // Disconnected
| 4901 // Chain Disconnected
| 4902 // Chain Not Recongnized

/**
* Error subclass implementing Ethereum Provider errors per EIP-1193.
*
* - EIP https://eips.ethereum.org/EIPS/eip-1193
*/
export class ProviderRpcError<T = undefined> extends RpcError {
export class ProviderRpcError<
T = undefined,
> extends RpcError<ProviderRpcErrorCode> {
override name = 'ProviderRpcError'

data?: T

constructor(
cause: Error,
options: RpcErrorOptions & {
data?: T
},
options: Prettify<
RpcErrorOptions<ProviderRpcErrorCode> & {
data?: T
}
>,
) {
super(cause, options)

Expand Down
26 changes: 24 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,9 +292,11 @@ export {
ParseRpcError,
ProviderDisconnectedError,
ProviderRpcError,
type ProviderRpcErrorCode,
ResourceNotFoundRpcError,
ResourceUnavailableRpcError,
RpcError,
type RpcErrorCode,
TransactionRejectedRpcError,
SwitchChainError,
UnauthorizedProviderError,
Expand Down Expand Up @@ -430,9 +432,29 @@ export {
type BlockTag,
type Uncle,
} from './types/block.js'
export { type ByteArray, type Hash, type Hex } from './types/misc.js'
export {
type ByteArray,
type Hash,
type Hex,
type LogTopic,
type Signature,
} from './types/misc.js'
export type { Chain } from './types/chain.js'
export type { EIP1193Provider } from './types/eip1193.js'
export type {
EIP1193Provider,
ProviderRpcError as EIP1193ProviderRpcError,
ProviderConnectInfo,
ProviderMessage,
AddEthereumChainParameter,
NetworkSync,
PublicRequests,
Requests,
SignableRequests,
WatchAssetParams,
WalletPermissionCaveat,
WalletPermission,
WalletRequests,
} from './types/eip1193.js'
export {
type FeeHistory,
type FeeValues,
Expand Down
23 changes: 10 additions & 13 deletions src/types/eip1193.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,11 @@ export type EIP1193Provider = Requests & Events
//////////////////////////////////////////////////
// Errors

// rome-ignore format: no formatting
export type RpcErrorCode =
// https://eips.ethereum.org/EIPS/eip-1193#provider-errors
| 4_001 | 4_100 | 4_200 | 4_900 | 4_901
// https://eips.ethereum.org/EIPS/eip-1474#error-codes
| -32700 | -32600 | -32601 | -32602 | -32603 | -32000 | -32001 | -32002 | -32003 | -32004 | -32005 | -32006
export class RpcError extends Error {
code: RpcErrorCode | (number & {})
export class ProviderRpcError extends Error {
code: number
details: string

constructor(code: RpcErrorCode | (number & {}), message: string) {
constructor(code: number, message: string) {
super(message)
this.code = code
this.details = message
Expand All @@ -57,7 +51,7 @@ export type Events = {
event: 'connect',
listener: (connectInfo: ProviderConnectInfo) => void,
): void
on(event: 'disconnect', listener: (error: RpcError) => void): void
on(event: 'disconnect', listener: (error: ProviderRpcError) => void): void
on(event: 'chainChanged', listener: (chainId: string) => void): void
on(event: 'accountsChanged', listener: (accounts: string[]) => void): void
on(event: 'message', listener: (message: ProviderMessage) => void): void
Expand All @@ -66,7 +60,10 @@ export type Events = {
event: 'connect',
listener: (connectInfo: ProviderConnectInfo) => void,
): void
removeListener(event: 'disconnect', listener: (error: RpcError) => void): void
removeListener(
event: 'disconnect',
listener: (error: ProviderRpcError) => void,
): void
removeListener(
event: 'chainChanged',
listener: (chainId: string) => void,
Expand All @@ -84,7 +81,7 @@ export type Events = {
//////////////////////////////////////////////////
// Provider Requests

export type Chain = {
export type AddEthereumChainParameter = {
/** A 0x-prefixed hexadecimal string */
chainId: string
/** The chain name. */
Expand Down Expand Up @@ -1034,7 +1031,7 @@ export type WalletRequests = {
* // => { ... }
*/
method: 'wallet_addEthereumChain'
params: [chain: Chain]
params: [chain: AddEthereumChainParameter]
}): Promise<null>
request(args: {
/**
Expand Down
2 changes: 1 addition & 1 deletion src/utils/buildRequest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ describe('args', () => {

test('retryDelay', async () => {
const start = Date.now()
let end: number = 0
let end = 0

const server = await createHttpServer((_req, res) => {
end = Date.now() - start
Expand Down
6 changes: 5 additions & 1 deletion src/utils/buildRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ import {
MethodNotSupportedRpcError,
ParseRpcError,
ProviderDisconnectedError,
type ProviderRpcErrorCode,
ResourceNotFoundRpcError,
ResourceUnavailableRpcError,
type RpcError,
type RpcErrorCode,
SwitchChainError,
TransactionRejectedRpcError,
UnauthorizedProviderError,
Expand Down Expand Up @@ -66,7 +68,9 @@ export function buildRequest<TRequest extends (args: any) => Promise<any>>(
try {
return await request(args)
} catch (err_) {
const err = err_ as unknown as RpcError
const err = err_ as unknown as RpcError<
RpcErrorCode | ProviderRpcErrorCode
>
if (err.code === -32700) throw new ParseRpcError(err)
if (err.code === -32600) throw new InvalidRequestRpcError(err)
if (err.code === -32601) throw new MethodNotFoundRpcError(err)
Expand Down

1 comment on commit d5297c6

@vercel
Copy link

@vercel vercel bot commented on d5297c6 May 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.