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

Update WalletConnect eth_RequestAccounts flow along with update WC deps and add new optional params #1622

Merged
merged 4 commits into from
Apr 3, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
"@web3-onboard/trezor": "^2.3.4",
"@web3-onboard/trust": "^2.0.1",
"@web3-onboard/uauth": "^2.0.2",
"@web3-onboard/walletconnect": "^2.3.3",
"@web3-onboard/walletconnect": "^2.3.4-alpha.1",
"@web3-onboard/web3auth": "^2.2.0",
"@web3-onboard/xdefi": "^2.0.1",
"animejs": "^3.2.1",
Expand Down
4 changes: 4 additions & 0 deletions docs/src/routes/docs/[...4]wallets/walletconnect.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ type WalletConnectOptions = {
* optional chains for the WalletConnect module
*/
requiredChains?: number[] | undefined
/**
* `undefined` by default, see https://docs.walletconnect.com/2.0/web3modal/options
*/
qrModalOptions?: Web3ModalConfig
}
)
```
Expand Down
4 changes: 2 additions & 2 deletions packages/demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"webpack-dev-server": "4.7.4"
},
"dependencies": {
"@web3-onboard/core": "^2.16.0",
"@web3-onboard/core": "^2.16.1-alpha.1",
"@web3-onboard/coinbase": "^2.2.1",
"@web3-onboard/transaction-preview": "^2.0.5",
"@web3-onboard/dcent": "^2.2.4",
Expand All @@ -45,7 +45,7 @@
"@web3-onboard/torus": "^2.2.2",
"@web3-onboard/taho": "^2.0.1",
"@web3-onboard/web3auth": "^2.2.0",
"@web3-onboard/walletconnect": "^2.3.3",
"@web3-onboard/walletconnect": "^2.3.4-alpha.1",
"@web3-onboard/enkrypt": "^2.0.1",
"@web3-onboard/mew-wallet": "^2.0.0",
"@web3-onboard/xdefi": "^2.0.1",
Expand Down
4 changes: 4 additions & 0 deletions packages/walletconnect/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ type WalletConnectOptions = {
* optional chains for the WalletConnect module
*/
requiredChains?: number[] | undefined
/**
* `undefined` by default, see https://docs.walletconnect.com/2.0/web3modal/options
*/
qrModalOptions?: Web3ModalConfig
}
)
```
Expand Down
7 changes: 4 additions & 3 deletions packages/walletconnect/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@web3-onboard/walletconnect",
"version": "2.3.3",
"version": "2.3.4-alpha.1",
"description": "WalletConnect SDK module for connecting to Web3-Onboard. Web3-Onboard makes it simple to connect Ethereum hardware and software wallets to your dapp. Features standardised spec compliant web3 providers for all supported wallets, framework agnostic modern javascript UI with code splitting, CSS customization, multi-chain and multi-account support, reactive wallet state subscriptions and real-time transaction state change notifications.",
"keywords": [
"Ethereum",
Expand Down Expand Up @@ -56,11 +56,12 @@
"license": "MIT",
"devDependencies": {
"typescript": "^4.5.5",
"@walletconnect/types": "^2.3.3"
"@walletconnect/types": "^2.5.2",
"@web3modal/standalone": "^2.2.2"
},
"dependencies": {
"@ethersproject/providers": "^5.5.0",
"@walletconnect/ethereum-provider": "2.4.10",
"@walletconnect/ethereum-provider": "2.5.2",
"@walletconnect/client": "^1.8.0",
"@walletconnect/qrcode-modal": "^1.8.0",
"@web3-onboard/common": "^2.3.0",
Expand Down
10 changes: 7 additions & 3 deletions packages/walletconnect/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { WalletInit } from '@web3-onboard/common'
import type { Web3ModalConfig } from '@web3modal/standalone'
import v1 from './v1.js'
import v2 from './v2.js'

Expand All @@ -11,8 +12,7 @@ export type WalletConnectOptions = {
bridge?: string
qrcodeModalOptions?: {
mobileLinks: string[]
},

}
} & (
| {
/**
Expand All @@ -36,6 +36,10 @@ export type WalletConnectOptions = {
* optional chains for the WalletConnect module
*/
requiredChains?: number[] | undefined
/**
* `undefined` by default, see https://docs.walletconnect.com/2.0/web3modal/options
*/
qrModalOptions?: Web3ModalConfig
}
)

Expand All @@ -48,7 +52,7 @@ export const isHexString = (value: string | number) => {
}

function walletConnect(options?: WalletConnectOptions): WalletInit {
const version = options && options.version || 1
const version = (options && options.version) || 1
return version === 1 ? v1(options) : v2(options)
}

Expand Down
123 changes: 63 additions & 60 deletions packages/walletconnect/src/v2.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { CoreTypes } from '@walletconnect/types'
import type { EthereumProvider } from '@walletconnect/ethereum-provider'
import type {
Chain,
ProviderAccounts,
Expand All @@ -19,13 +20,12 @@ const methods = [
]

function walletConnect(options?: WalletConnectOptions): WalletInit {
const projectId =
options && options.version === 2 ? options.projectId : undefined
if (!projectId) {
if (!options || options.version !== 2) {
throw new Error(
'WalletConnect requires a projectId. Please visit https://cloud.walletconnect.com to get one.'
)
}
const { projectId, handleUri, requiredChains, qrModalOptions } = options

return () => {
return {
Expand Down Expand Up @@ -65,29 +65,29 @@ function walletConnect(options?: WalletConnectOptions): WalletInit {
}

// default to mainnet
const requiredChains =
options &&
options.version === 2 &&
Array.isArray(options.requiredChains) &&
options.requiredChains.length &&
options.requiredChains.every(num => !isNaN(num) )
// @ts-ignore
const requiredChainsParsed =
Array.isArray(requiredChains) &&
requiredChains.length &&
requiredChains.every(num => !isNaN(num))
? // @ts-ignore
// Required as WC package does not support hex numbers
? options.requiredChains.map(chainID => parseInt(chainID))
requiredChains.map(chainID => parseInt(chainID))
: [1]

const connector = await EthereumProvider.init({
projectId,
chains: requiredChainsParsed, // default to mainnet
metadata: getMetaData(),
chains: requiredChains, // default to mainnet
showQrModal: true,
optionalChains: chains.map(({ id }) => parseInt(id, 16)),
optionalMethods: methods,
rpcMap: chains
.map(({ id, rpcUrl }) => ({ id, rpcUrl }))
.reduce((rpcMap: Record<number, string>, { id, rpcUrl }) => {
rpcMap[parseInt(id, 16)] = rpcUrl || ''
return rpcMap
}, {})
}, {}),
qrModalOptions: qrModalOptions
})

const emitter = new EventEmitter()
Expand Down Expand Up @@ -163,7 +163,7 @@ function walletConnect(options?: WalletConnectOptions): WalletInit {
if (this.connector.session) this.connector.disconnect()
}

if (options && options.handleUri) {
if (options && handleUri) {
// listen for uri event
fromEvent(
this.connector as JQueryStyleEventEmitter<any, string>,
Expand All @@ -173,20 +173,21 @@ function walletConnect(options?: WalletConnectOptions): WalletInit {
.pipe(takeUntil(this.disconnected$))
.subscribe(async uri => {
try {
options.handleUri && (await options.handleUri(uri))
handleUri && (await handleUri(uri))
} catch (error) {
throw `An error occurred when handling the URI. Error: ${error}`
}
})
}

;(() => {
const checkForSession = () => {
const session = this.connector.session
if (session) {
this.emit('accountsChanged', this.connector.accounts)
this.emit('chainChanged', this.connector.chainId)
}
})()
}
checkForSession()

this.request = async ({ method, params }) => {
if (method === 'eth_chainId') {
Expand All @@ -196,50 +197,52 @@ function walletConnect(options?: WalletConnectOptions): WalletInit {
}

if (method === 'eth_requestAccounts') {
return new Promise<ProviderAccounts>((resolve, reject) => {
// Check if connection is already established
if (!this.connector.session) {
// create new session
this.connector.connect().catch(err => {
console.error('err: ', err)
reject(
new ProviderRpcError({
code: 4001,
message: 'User rejected the request.'
})
)
})
} else {
// update ethereum provider to load accounts & chainId
const accounts = this.connector.accounts
const chainId = this.connector.chainId
const hexChainId = `0x${chainId.toString(16)}`
this.emit('chainChanged', hexChainId)
return resolve(accounts)
return new Promise<ProviderAccounts>(
async (resolve, reject) => {
// Subscribe to connection events
fromEvent(
this.connector as JQueryStyleEventEmitter<
any,
{ chainId: number }
>,
'connect',
(payload: { chainId: number | string }) => payload
)
.pipe(take(1))
.subscribe({
next: ({ chainId }) => {
this.emit('accountsChanged', this.connector.accounts)
const hexChainId = isHexString(chainId)
? chainId
: `0x${chainId.toString(16)}`
this.emit('chainChanged', hexChainId)
resolve(this.connector.accounts)
},
error: reject
})

// Check if connection is already established
if (!this.connector.session) {
// create new session
await this.connector.connect().catch(err => {
console.error('err creating new session: ', err)
reject(
new ProviderRpcError({
code: 4001,
message: 'User rejected the request.'
})
)
})
} else {
// update ethereum provider to load accounts & chainId
const accounts = this.connector.accounts
const chainId = this.connector.chainId
const hexChainId = `0x${chainId.toString(16)}`
this.emit('chainChanged', hexChainId)
return resolve(accounts)
}
}
// Subscribe to connection events
fromEvent(
this.connector as JQueryStyleEventEmitter<
any,
{ accounts: string[]; chainId: number }
>,
'connect',
(payload: { accounts: string[]; chainId: number }) =>
payload
)
.pipe(take(1))
.subscribe({
next: ({ accounts, chainId }) => {
this.emit('accountsChanged', accounts)
const hexChainId = isHexString(chainId)
? chainId
: `0x${chainId.toString(16)}`
this.emit('chainChanged', hexChainId)
resolve(accounts)
},
error: reject
})
})
)
}

if (method === 'eth_selectAccounts') {
Expand Down
Loading