Skip to content

Commit

Permalink
feat: support ethers v6
Browse files Browse the repository at this point in the history
  • Loading branch information
johnson86tw committed Jul 25, 2023
1 parent 6ab78e4 commit d3563f6
Show file tree
Hide file tree
Showing 17 changed files with 97 additions and 55 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ app.use(VueDapp, {
autoConnect: true, // Automatically connect MetaMask wallet when the page is loaded
networks: {
80001: {
chainId: ethers.utils.hexValue(80001),
chainId: ethers.toQuantity(80001),
blockExplorerUrls: ['https://mumbai.polygonscan.com/'],
chainName: 'Mumbai',
rpcUrls: ['https://rpc-mumbai.maticvigil.com/'],
Expand Down
4 changes: 2 additions & 2 deletions demo/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,12 @@ const supportedChainId = Object.keys(availableNetworks.value).map((key) =>
const selectedChainId = ref(0)
onActivated(() => {
selectedChainId.value = chainId.value as number
selectedChainId.value = Number(chainId.value)
})
const isChainChanged = ref(false)
onChanged(() => {
selectedChainId.value = chainId.value as number
selectedChainId.value = Number(chainId.value)
isChainChanged.value = true
})
Expand Down
6 changes: 3 additions & 3 deletions demo/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ app.use(VueDapp, {
dumb: false,
networks: {
137: {
chainId: ethers.utils.hexValue(137),
chainId: ethers.toQuantity(137),
blockExplorerUrls: ['https://polygonscan.com'],
chainName: 'Polygon',
rpcUrls: ['https://rpc-mainnet.maticvigil.com'],
Expand All @@ -23,7 +23,7 @@ app.use(VueDapp, {
},
},
80001: {
chainId: ethers.utils.hexValue(80001),
chainId: ethers.toQuantity(80001),
blockExplorerUrls: ['https://mumbai.polygonscan.com/'],
chainName: 'Mumbai',
rpcUrls: ['https://rpc-mumbai.maticvigil.com/'],
Expand All @@ -34,7 +34,7 @@ app.use(VueDapp, {
},
},
42161: {
chainId: ethers.utils.hexValue(42161),
chainId: ethers.toQuantity(42161),
blockExplorerUrls: ['https://arbiscan.io'],
chainName: 'Arbitrum One',
rpcUrls: ['https://arb1.arbitrum.io/rpc'],
Expand Down
4 changes: 2 additions & 2 deletions docs/api/plugin-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ app.use(VueDapp, {
autoConnect: true,
networks: {
80001: {
chainId: ethers.utils.hexValue(80001),
chainId: ethers.toQuantity(80001),
blockExplorerUrls: ['https://mumbai.polygonscan.com/'],
chainName: 'Mumbai',
rpcUrls: ['https://rpc-mumbai.maticvigil.com/'],
Expand All @@ -42,7 +42,7 @@ app.use(VueDapp, {
},
},
42161: {
chainId: ethers.utils.hexValue(42161),
chainId: ethers.toQuantity(42161),
blockExplorerUrls: ['https://arbiscan.io'],
chainName: 'Arbitrum One',
rpcUrls: ['https://arb1.arbitrum.io/rpc'],
Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ app.use(VueDapp, {
autoConnect: true, // Automatically connect MetaMask wallet when the page is loaded
networks: {
80001: {
chainId: ethers.utils.hexValue(80001),
chainId: ethers.toQuantity(80001),
blockExplorerUrls: ['https://mumbai.polygonscan.com/'],
chainName: 'Mumbai',
rpcUrls: ['https://rpc-mumbai.maticvigil.com/'],
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "vue-dapp",
"version": "0.9.1",
"version": "0.10.0",
"description": "Vue 3 library for building Dapps on Ethereum",
"repository": "https://github.com/vu3th/vue-dapp",
"bugs": {
Expand Down Expand Up @@ -44,7 +44,7 @@
"@walletconnect/ethereum-provider": "^2.7.7",
"@walletconnect/modal": "^2.4.5",
"@web3modal/standalone": "^2.4.1",
"ethers": ">=5.6.8",
"ethers": ">=6.6.3",
"vue": ">=3.2.0"
},
"peerDependenciesMeta": {
Expand Down Expand Up @@ -91,6 +91,7 @@
"eslint": "^8.29.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"ethers": "^6.6.3",
"husky": "^8.0.1",
"jsdom": "^20.0.3",
"lint-staged": "^12.4.2",
Expand Down
43 changes: 19 additions & 24 deletions src/composables/useEthers.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import { computed, markRaw, ref, Ref } from 'vue'
import {
Web3Provider,
Network,
ExternalProvider,
} from '@ethersproject/providers'
import { BigNumber, Signer } from 'ethers'
import { Web3Provider } from '@ethersproject/providers'
import { BrowserProvider, Eip1193Provider, Signer, Network } from 'ethers'
import { NETWORK_DETAILS } from '../constants'
import { ActivateEthersError, AddEthereumChainParameter } from '../connectors'

export type { Web3Provider, Signer, Network }

const isActivated = ref(false)
const provider = ref<Web3Provider | null>(null)
const provider = ref<BrowserProvider | null>(null)
const signer = ref<Signer | null>(null)
const network = ref<Network | null>(null)
const address = ref('')
Expand All @@ -34,18 +30,19 @@ const deactivate = () => {
balance.value = BigInt(0)
}

async function activate(externalProvider: ExternalProvider) {
async function activate(externalProvider: Eip1193Provider) {
if (!externalProvider) throw new ActivateEthersError('provider not found')

const _provider = new Web3Provider(externalProvider)
const _signer = _provider.getSigner()
const _provider = new BrowserProvider(externalProvider)
const _signer = await _provider.getSigner()

let _network: any = null
let _network: Network | null = null
let _address = ''
let _balance = BigNumber.from(0)
let _balance = BigInt(0)

const data = await getData()
;[_network, _address, _balance] = data!
;[_network, _address] = data!
_balance = await _provider.getBalance(_address)

/**
* @issue #27
Expand All @@ -56,11 +53,7 @@ async function activate(externalProvider: ExternalProvider) {
*/
async function getData(timeout = 5000) {
return Promise.race([
Promise.all([
_provider.getNetwork(),
_signer.getAddress(),
_signer.getBalance(),
]),
Promise.all([_provider.getNetwork(), _signer.getAddress()]),
new Promise<void>((resolve, reject) =>
setTimeout(() => {
reject(new ActivateEthersError('Operation timed out'))
Expand All @@ -79,14 +72,14 @@ async function activate(externalProvider: ExternalProvider) {

provider.value = markRaw(_provider)
signer.value = markRaw(_signer)
network.value = _network
network.value = markRaw(_network)
address.value = _address
balance.value = _balance.toBigInt()
balance.value = _balance

// Put it outside the timer as the lookup method can occasionally take longer than 5000ms
// Question: what if people don't need this variable but it lead to more connecting time?
try {
dnsAlias.value = await lookupDNS(_network?.chainId, _address)
dnsAlias.value = await lookupDNS(Number(_network?.chainId), _address)
} catch (err: any) {
throw new ActivateEthersError('Failed to look up DNS')
}
Expand All @@ -98,8 +91,10 @@ async function activate(externalProvider: ExternalProvider) {
updateBalanceInterval = setInterval(async () => {
if (!signer.value) return
try {
const _balance = await signer?.value.getBalance()
balance.value = _balance.toBigInt()
const _balance = await provider.value?.getBalance(address.value)
if (typeof _balance === 'bigint') {
balance.value = _balance
}
} catch (error: any) {
console.warn('Failed to update balance')
}
Expand Down Expand Up @@ -149,7 +144,7 @@ export function useEthers() {
isActivated,
provider: provider as Ref<Web3Provider | null>, // for fixing index.d.ts compiled error, see issue/10:
signer: signer as Ref<Signer | null>,
network,
network: network as Ref<Network | null>,
address,
dnsAlias,
balance,
Expand Down
3 changes: 1 addition & 2 deletions src/composables/useEthersHooks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { ref, watch } from 'vue'
import { Signer } from '@ethersproject/abstract-signer'
import { Network } from '@ethersproject/networks'
import { Signer, Network } from 'ethers'
import { useEthers, Web3Provider } from './useEthers'

export type EthersHooksContext = {
Expand Down
8 changes: 4 additions & 4 deletions src/composables/useMulticall.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { ref } from 'vue'
import { Contract, ContractInterface } from '@ethersproject/contracts'
import { Contract, ContractInterface, Provider } from 'ethers'
import { MULTICALL2_ABI, MULTICALL2_ADDRESS } from '../constants'
import { Multicall2 } from '../types/multicall2/Multicall2'
import { Web3Provider, JsonRpcProvider } from '@ethersproject/providers'
import { Result, Interface } from '@ethersproject/abi'

export type ContractCall = {
Expand All @@ -12,15 +11,15 @@ export type ContractCall = {
args?: any[]
}

export function useMulticall(provider: Web3Provider | JsonRpcProvider) {
export function useMulticall(provider: Provider) {
const results = ref<Result[]>([])
const blockNumber = ref(0)

const multicall = new Contract(
MULTICALL2_ADDRESS,
MULTICALL2_ABI,
provider,
) as Multicall2
) as unknown as Multicall2

interface Call {
target: string
Expand Down Expand Up @@ -69,5 +68,6 @@ function getInterface(contractInterface: ContractInterface): Interface {
if (Interface.isInterface(contractInterface)) {
return contractInterface
}
// @ts-ignore
return new Interface(contractInterface)
}
4 changes: 2 additions & 2 deletions src/composables/useWallet.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ref, reactive, markRaw } from 'vue'
import { providers } from 'ethers'
import { ethers } from 'ethers'
import {
AutoConnectError,
ConnectError,
Expand All @@ -15,7 +15,7 @@ export type ConnectionStatus = 'none' | 'connecting' | 'loading' | 'connected'

const wallet = reactive({
connector: null as Connector | null,
provider: null as providers.ExternalProvider | null,
provider: null as ethers.Eip1193Provider | null,
error: '',
status: 'none' as ConnectionStatus,
})
Expand Down
4 changes: 2 additions & 2 deletions src/connectors/coinbaseWallet.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Connector } from './connector'
import type { CoinbaseWalletProvider } from '@coinbase/wallet-sdk'
import type { CoinbaseWalletSDKOptions } from '@coinbase/wallet-sdk/dist/CoinbaseWalletSDK'
import { getAddress, hexValue } from 'ethers/lib/utils'
import { ethers, getAddress } from 'ethers'
import {
AddChainError,
ProviderNotFoundError,
Expand Down Expand Up @@ -118,7 +118,7 @@ export class CoinbaseWalletConnector extends Connector<
async switchChain(chainId: number) {
if (!this.#provider) throw new ProviderNotFoundError()
const provider = this.#provider
const id = hexValue(chainId)
const id = ethers.toQuantity(chainId)

try {
await provider.request({
Expand Down
4 changes: 2 additions & 2 deletions src/connectors/connector.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type { CoinbaseWalletProvider } from '@coinbase/wallet-sdk'
import { providers } from 'ethers'
import { ethers } from 'ethers'

export type ConnectorData<Provider = any> = {
account: string
provider: Provider
}

export abstract class Connector<
Provider = providers.ExternalProvider | CoinbaseWalletProvider,
Provider = ethers.Eip1193Provider | CoinbaseWalletProvider,
Options = any,
> {
// Connector name
Expand Down
4 changes: 2 additions & 2 deletions src/connectors/metaMask.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { hexValue } from 'ethers/lib/utils'
import { ethers } from 'ethers'
import type { NETWORK_DETAILS } from '../constants'
import { Connector } from './connector'
import {
Expand Down Expand Up @@ -211,7 +211,7 @@ export class MetaMaskConnector extends Connector<

async switchChain(chainId: number) {
if (!this.#provider) throw new ProviderNotFoundError()
const id = hexValue(chainId)
const id = ethers.toQuantity(chainId)
const { availableNetworks } = useEthers() as any
const _availableNetworks = JSON.parse(
JSON.stringify(availableNetworks.value),
Expand Down
2 changes: 1 addition & 1 deletion src/connectors/safe.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { SafeAppProvider } from '@gnosis.pm/safe-apps-provider'
import type { Opts as SafeOpts, SafeInfo } from '@gnosis.pm/safe-apps-sdk'
import type SafeAppsSDK from '@gnosis.pm/safe-apps-sdk'
import { getAddress } from 'ethers/lib/utils'
import { getAddress } from 'ethers'
import { normalizeChainId } from '../utils'
import { Connector } from './connector'
import {
Expand Down
4 changes: 2 additions & 2 deletions src/connectors/walletConnect.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Connector } from './connector'
import { getAddress, hexValue } from 'ethers/lib/utils'
import { getAddress, ethers } from 'ethers'
import {
ProviderNotFoundError,
ProviderRpcError,
Expand Down Expand Up @@ -120,7 +120,7 @@ export class WalletConnectConnector extends Connector<
throw new SwitchChainNotSupportedError()
}

const id = hexValue(chainId)
const id = ethers.toQuantity(chainId)

try {
await this.#provider.request({
Expand Down
5 changes: 2 additions & 3 deletions src/utils/format.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { BigNumber } from 'ethers'
import { formatEther, isAddress } from 'ethers/lib/utils'
import { formatEther, isAddress, BigNumberish } from 'ethers'
import { checkChainId } from './check'
import { useEthers } from '../composables'

Expand All @@ -11,7 +10,7 @@ export function shortenAddress(address: string): string {
}
}

export function displayEther(balance: BigNumber | bigint, fixed = 2) {
export function displayEther(balance: BigNumberish | bigint, fixed = 2) {
return (+formatEther(balance)).toFixed(fixed)
}

Expand Down
Loading

0 comments on commit d3563f6

Please sign in to comment.