Cocos Creator 3.8.3 and above versions are compatible with the viem library, you can use it directly.
Install the viem library
npm install viem --save
Create an EVM instance
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(), // http() is a public client, you can also use a wallet client by replacing it with custom(window.ethereum!)
})
// Get the current block height
const blockNumber = await client.getBlockNumber()
For more operations, please visit the directly.
Using WalletConnect's web3modal
The official web3modal is not compatible with Cocos Creator, so we have repackaged the library and it can now be used directly. Currently, version 5.1.6 is supported.
Install the WalletConnect library
npm i @cocos-labs/web3modal-ethers5
Create a WalletConnect instance
import { createWeb3Modal, useWeb3Modal } from '@cocos-labs/web3modal-ethers5'
// 1. Get projectId from https://cloud.walletconnect.com
const projectId = 'xxxxxxxxxxxxxxxxxxx'
// 2. Set chains
const mainnet = {
chainId: 1,
name: 'Ethereum',
currency: 'ETH',
explorerUrl: 'https://etherscan.io',
rpcUrl: 'https://rpc.ankr.com/eth'
}
const bnbchain = {
chainId: 56,
name: 'BNB Smart Chain Mainnet',
currency: 'BNB',
explorerUrl: 'https://bscscan.com/',
rpcUrl: 'https://bsc-dataseed4.ninicoin.io'
}
// 3. Create your application's metadata object
const metadata = {
name: 'My Website',
description: 'My Website description',
url: 'https://mywebsite.com', // url must match your domain & subdomain
icons: ['https://avatars.mywebsite.com/']
}
// 4. Create Ethers config
const ethersConfig = defaultConfig({
/*Required*/
metadata,
/*Optional*/
enableEIP6963: true, // true by default
enableInjected: true, // true by default
defaultChainId: 56
})
// 5. Create a AppKit instance
this.evmConnect = createWeb3Modal({
ethersConfig,
chains: [mainnet, bnbchain],
projectId,
enableAnalytics: false // Optional - defaults to your Cloud configuration
})
// 6. Open the modal
this.evmConnect.open({ view: 'Connect' })