在Cocos Creator中使用EVM
使用viem库
Cocos creator 3.8.3以上版本兼容viem库, 直接使用既可
安装viem库
npm install viem --save
创建一个EVM实例
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(), //http()是公共client,也可以使用 wallet client换成 custom(window.ethereum!)
})
// 获取当前区块高度
const blockNumber = await client.getBlockNumber()
更多操作请直接访问viem官网
使用WalletConnect 的 web3modal
官方的web3modal不兼容cocos creator, 我们对web3modal库做了重新打包, 现在可以直接使用,目前兼容的是 5.1.6版本
安装WalletConnect库
npm i @cocos-labs/web3modal-ethers5
创建一个WalletConnect实例
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' })
更多操作请直接访问web3modal
社区交流 Telegram: https://t.me/CocosStudioCommunity
最后更新于