Skip to content

Commit

Permalink
Prettify source
Browse files Browse the repository at this point in the history
  • Loading branch information
cawabunga committed Sep 19, 2023
1 parent a5d8805 commit 77734c7
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 30 deletions.
54 changes: 40 additions & 14 deletions src/Web3ProviderBackend.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import assert from 'node:assert/strict'
import {
filter,
firstValueFrom,
Expand All @@ -9,7 +10,6 @@ import {
} from 'rxjs'
import { ethers, Wallet } from 'ethers'
import { signTypedData, SignTypedDataVersion } from '@metamask/eth-sig-util'
import assert from 'assert/strict'

import { Web3RequestKind } from './utils'
import {
Expand Down Expand Up @@ -111,7 +111,9 @@ export class Web3ProviderBackend extends EventEmitter implements IWeb3Provider {
{ method, params },
async () => {
const accounts = await Promise.all(
this.#wallets.map(async (wallet) => (await wallet.getAddress()).toLowerCase())
this.#wallets.map(async (wallet) =>
(await wallet.getAddress()).toLowerCase()
)
)
this.emit('accountsChanged', accounts)
return accounts
Expand All @@ -123,7 +125,9 @@ export class Web3ProviderBackend extends EventEmitter implements IWeb3Provider {
case 'eth_accounts': {
if (this._authorizedRequests['eth_requestAccounts']) {
return await Promise.all(
this.#wallets.map(async (wallet) => (await wallet.getAddress()).toLowerCase())
this.#wallets.map(async (wallet) =>
(await wallet.getAddress()).toLowerCase()
)
)
}
return []
Expand Down Expand Up @@ -178,7 +182,9 @@ export class Web3ProviderBackend extends EventEmitter implements IWeb3Provider {

return this.waitAuthorization({ method, params }, async () => {
const accounts = await Promise.all(
this.#wallets.map(async (wallet) => (await wallet.getAddress()).toLowerCase())
this.#wallets.map(async (wallet) =>
(await wallet.getAddress()).toLowerCase()
)
)
this.emit('accountsChanged', accounts)
return [{ parentCapability: 'eth_accounts' }]
Expand Down Expand Up @@ -259,7 +265,7 @@ export class Web3ProviderBackend extends EventEmitter implements IWeb3Provider {
waitAuthorization<T>(
requestInfo: PendingRequest['requestInfo'],
task: () => Promise<T>,
permanentPermission = false,
permanentPermission = false
) {
if (this._authorizedRequests[requestInfo.method]) {
return task()
Expand Down Expand Up @@ -349,7 +355,11 @@ export class Web3ProviderBackend extends EventEmitter implements IWeb3Provider {
this.#wallets = privateKeys.map((key) => new ethers.Wallet(key))
this.emit(
'accountsChanged',
await Promise.all(this.#wallets.map(async (wallet) => (await wallet.getAddress()).toLowerCase()))
await Promise.all(
this.#wallets.map(async (wallet) =>
(await wallet.getAddress()).toLowerCase()
)
)
)
}

Expand Down Expand Up @@ -409,31 +419,47 @@ function without<T>(list: T[], item: T): T[] {

// Allowed keys for a JSON-RPC transaction as defined in:
// https://ethereum.github.io/execution-apis/api-documentation/
const allowedTransactionKeys = ['accessList', 'chainId', 'data', 'from', 'gas', 'gasPrice', 'maxFeePerGas',
'maxPriorityFeePerGas', 'nonce', 'to', 'type', 'value']
const allowedTransactionKeys = [
'accessList',
'chainId',
'data',
'from',
'gas',
'gasPrice',
'maxFeePerGas',
'maxPriorityFeePerGas',
'nonce',
'to',
'type',
'value',
]

// Convert a JSON-RPC transaction to an ethers.js transaction.
// The reverse of this function can be found in the ethers.js library:
// https://github.com/ethers-io/ethers.js/blob/v5.7.2/packages/providers/src.ts/json-rpc-provider.ts#L701
function convertJsonRpcTxToEthersTxRequest(tx: { [key: string]: any }): ethers.providers.TransactionRequest {
function convertJsonRpcTxToEthersTxRequest(tx: {
[key: string]: any
}): ethers.providers.TransactionRequest {
const result: any = {}

allowedTransactionKeys.forEach((key) => {
if (tx[key] == null) { return }
if (tx[key] == null) {
return
}

switch (key) {
// gasLimit is referred to as "gas" in JSON-RPC
case "gas":
case 'gas':
result['gasLimit'] = tx[key]
return
// ethers.js expects `chainId` and `type` to be a number
case "chainId":
case "type":
case 'chainId':
case 'type':
result[key] = Number(tx[key])
return
default:
result[key] = tx[key]
}
});
})
return result
}
10 changes: 6 additions & 4 deletions src/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ export function makeHeadlessWeb3Provider(
method: T,
...args: IWeb3Provider[T] extends Fn ? Parameters<IWeb3Provider[T]> : []
) => Promise<void> = async () => {},
config?: Web3ProviderConfig
config?: Web3ProviderConfig
) {
const chainRpc = new ethers.providers.JsonRpcProvider(rpcUrl, chainId)
const web3Provider = new Web3ProviderBackend(privateKeys, [
{ chainId, rpcUrl },
], config)
const web3Provider = new Web3ProviderBackend(
privateKeys,
[{ chainId, rpcUrl }],
config
)

relayEvents(web3Provider, evaluate)

Expand Down
27 changes: 15 additions & 12 deletions tests/e2e/metamask.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ test.beforeEach(async ({ page, injectWeb3Provider }) => {
})

test('connect the wallet', async ({ page, accounts }) => {
// Until the wallet is connected, the accounts should be empty
let ethAccounts = await page.evaluate(() =>
window.ethereum.request({ method: 'eth_accounts', params: [] })
// Until the wallet is connected, the accounts should be empty
let ethAccounts = await page.evaluate(() =>
window.ethereum.request({ method: 'eth_accounts', params: [] })
)
expect(ethAccounts).toEqual([])

Expand Down Expand Up @@ -118,12 +118,16 @@ test('deploy a token', async ({ page }) => {
await expect(page.locator('#tokenAddress')).toContainText(/0x.+/)
})

const getTransactionCount = async (page: Page, account: string): Promise<number> => {
const res = await page.evaluate(addr =>
window.ethereum.request({
method: 'eth_getTransactionCount',
params: [addr, 'latest']
}),
const getTransactionCount = async (
page: Page,
account: string
): Promise<number> => {
const res = await page.evaluate(
(addr) =>
window.ethereum.request({
method: 'eth_getTransactionCount',
params: [addr, 'latest'],
}),
account
)
return Number(res)
Expand All @@ -138,10 +142,9 @@ test('send legacy transaction', async ({ page, accounts }) => {
await wallet.authorize(Web3RequestKind.SendTransaction)

const nonceAfter = await getTransactionCount(page, accounts[0])
expect(nonceAfter).toEqual(nonceBefore+1)
expect(nonceAfter).toEqual(nonceBefore + 1)
})


test('send EIP-1559 transaction', async ({ page, accounts }) => {
await page.locator('text=Connect').click()
await wallet.authorize(Web3RequestKind.RequestAccounts)
Expand All @@ -151,7 +154,7 @@ test('send EIP-1559 transaction', async ({ page, accounts }) => {
await wallet.authorize(Web3RequestKind.SendTransaction)

const nonceAfter = await getTransactionCount(page, accounts[0])
expect(nonceAfter).toEqual(nonceBefore+1)
expect(nonceAfter).toEqual(nonceBefore + 1)
})

/**
Expand Down

0 comments on commit 77734c7

Please sign in to comment.