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

wip rewrite to remove MM jsonrpc engine #3

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ The `headless-web3-provider` library emulates a Web3 wallet similar to Metamask
| personal_sign | Yes |
| eth_signTypedData | Yes |
| eth_signTypedData_v1 | Yes |
| eth_signTypedData_v3 | Yes |
| eth_signTypedData_v4 | Yes |
| eth_call | No |
| eth_estimateGas | No |
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
"lint": "biome lint"
},
"dependencies": {
"@metamask/json-rpc-engine": "^9.0.0",
"@metamask/utils": "^9.1.0",
"viem": "^2.17.1"
},
Expand Down
67 changes: 5 additions & 62 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 9 additions & 16 deletions src/Web3ProviderBackend.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
import type { JsonRpcEngine } from '@metamask/json-rpc-engine'
import type { Json, JsonRpcError } from '@metamask/utils'
import {
http,
type Chain,
type EIP1193Parameters,
type EIP1193Provider,
type Hex,
type LocalAccount,
} from 'viem'
import { privateKeyToAccount } from 'viem/accounts'

import type { Json } from '@metamask/utils'
import { EventEmitter } from './EventEmitter.js'
import { createRpcEngine } from './engine.js'
import { ChainDisconnected, Deny, type ErrorWithCode } from './errors.js'
import type { Router } from './middleware.js'
import type { ChainTransport, JsonRpcRequest, PendingRequest } from './types.js'
import type { Web3RequestKind } from './utils.js'
import { WalletPermissionSystem } from './wallet/WalletPermissionSystem.js'
Expand Down Expand Up @@ -41,7 +39,7 @@ export class Web3ProviderBackend
type: 'authorize' | 'reject'
notify: () => Promise<void>
}[] = []
private engine: JsonRpcEngine
private router: Router

constructor({ privateKeys, chains, ...config }: Web3ProviderConfig) {
super()
Expand All @@ -51,7 +49,7 @@ export class Web3ProviderBackend
privateKeys.forEach((pk) => this.accounts.push(privateKeyToAccount(pk)))

this.wps = new WalletPermissionSystem(config.permitted)
this.engine = createRpcEngine({
this.router = createRpcEngine({
emit: (eventName, ...args) => this.emit(eventName, ...args),
debug: config.debug,
logger: config.logger,
Expand All @@ -67,15 +65,10 @@ export class Web3ProviderBackend

isMetaMask?: boolean

// @ts-expect-error
async request(req: EIP1193Parameters): Promise<Json> {
const res = await this.engine
.handle({
method: req.method,
params: req.params as `0x${string}`[],
id: null,
jsonrpc: '2.0',
})
// @ts-expect-error MM utils vs viem
async request(req: JsonRpcRequest): Promise<Json> {
const res = await this.router
.run(req, { result: null, id: '2.0', jsonrpc: '2.0' })
.catch((e) => {
console.error(e)
throw e
Expand All @@ -85,7 +78,7 @@ export class Web3ProviderBackend
return res.result
}

throw res.error
throw (res as { error: JsonRpcError }).error
}

isConnected() {
Expand Down
35 changes: 20 additions & 15 deletions src/engine.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { JsonRpcEngine } from '@metamask/json-rpc-engine'
import type { Chain, LocalAccount } from 'viem'

import { UnsupportedMethod } from './errors.js'
import { Router } from './middleware.js'
import type { ChainTransport, JsonRpcRequest } from './types.js'
import { createAccountsMiddleware } from './wallet/AccountsMiddleware.js'
import { createAuthorizeMiddleware } from './wallet/AuthorizeMiddleware.js'
Expand Down Expand Up @@ -40,29 +40,34 @@ export function createRpcEngine({
getChain,
getChainTransport,
}: RpcEngineConfig) {
const engine = new JsonRpcEngine()
// switch (req.method) {
// case
// }
const engine = new Router()

engine.push((req, _res, next) => {
if (debug) logger?.(`Request: ${req.method}`)
next()
})
if (debug) {
engine.use((req, _res, next) => {
if (debug) logger?.(`Request: ${req.method}`)
next()
})
}

engine.push(createAuthorizeMiddleware({ waitAuthorization }))
engine.push(createAccountsMiddleware({ emit, accounts, wps }))
engine.push(createSignMessageMiddleware({ account: accounts[0] }))
engine.push(createChainMiddleware({ getChain, addChain, switchChain }))
engine.push(
engine.use(createAuthorizeMiddleware({ waitAuthorization }))
engine.use(createAccountsMiddleware({ emit, accounts, wps }))
engine.use(createSignMessageMiddleware({ account: accounts[0] }))
engine.use(createChainMiddleware({ getChain, addChain, switchChain }))
engine.use(
createTransactionMiddleware({
getChain,
account: accounts[0],
getChainTransport,
}),
)
engine.push(createPermissionMiddleware({ emit, accounts }))
engine.push(createPassThroughMiddleware({ getChainTransport }))
engine.use(createPermissionMiddleware({ emit, accounts }))
engine.use(createPassThroughMiddleware({ getChainTransport }))

engine.push((_req, _res, _next, end) => {
end(UnsupportedMethod())
engine.use((_req, _res, _next) => {
throw UnsupportedMethod()
})

return engine
Expand Down
35 changes: 35 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import type { Json, JsonRpcSuccess } from '@metamask/utils'
import type { JsonRpcRequest } from './types.js'

export type Middleware = (
req: JsonRpcRequest,
res: JsonRpcSuccess<Json>,
next: () => Promise<void>,
) => void | Promise<void>

export class Router {
middlewares: Middleware[] = []

use(middleware: Middleware) {
this.middlewares.push(middleware)
}

async run(
req: JsonRpcRequest,
res: JsonRpcSuccess<Json>,
): Promise<JsonRpcSuccess<Json>> {
let index = 0

const next = async () => {
if (index < this.middlewares.length) {
const currentMiddleware = this.middlewares[index]
index++
await currentMiddleware(req, res, next)
}
}

await next()

return res
}
}
1 change: 0 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,5 @@ export enum Web3RequestKind {
SignMessage = 'personal_sign',
SignTypedData = 'eth_signTypedData',
SignTypedDataV1 = 'eth_signTypedData_v1',
SignTypedDataV3 = 'eth_signTypedData_v3',
SignTypedDataV4 = 'eth_signTypedData_v4',
}
49 changes: 21 additions & 28 deletions src/wallet/AccountsMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import {
type JsonRpcMiddleware,
createAsyncMiddleware,
} from '@metamask/json-rpc-engine'
import type { Account, Address } from 'viem'

import type { Middleware } from '../middleware.js'
import { Web3RequestKind } from '../utils.js'
import type { WalletPermissionSystem } from './WalletPermissionSystem.js'

Expand All @@ -17,33 +14,29 @@ export function createAccountsMiddleware({
emit,
accounts,
wps,
}: AccountsMiddlewareConfig) {
const middleware: JsonRpcMiddleware<[], Address[]> = createAsyncMiddleware(
async (req, res, next) => {
switch (req.method) {
case 'eth_accounts':
if (wps.isPermitted(Web3RequestKind.Accounts, '')) {
res.result = accounts.map((a) => a.address)
} else {
res.result = []
}
break

case 'eth_requestAccounts': {
wps.permit(Web3RequestKind.Accounts, '')
}: AccountsMiddlewareConfig): Middleware {
return async (req, res, next) => {
switch (req.method) {
case 'eth_accounts':
if (wps.isPermitted(Web3RequestKind.Accounts, '')) {
res.result = accounts.map((a) => a.address)
} else {
res.result = []
}
break

const addresses = accounts.map((a) => a.address)
case 'eth_requestAccounts': {
wps.permit(Web3RequestKind.Accounts, '')

emit('accountsChanged', addresses)
res.result = addresses
break
}
const addresses = accounts.map((a) => a.address)

default:
void next()
emit('accountsChanged', addresses)
res.result = addresses
break
}
},
)

return middleware
default:
void next()
}
}
}
Loading
Loading