You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.5 KiB
63 lines
1.5 KiB
/**
|
|
* @fileoverview 客户端工厂(共享)
|
|
* @description 创建公共客户端和钱包客户端的统一工厂函数
|
|
*/
|
|
|
|
import { createPublicClient, createWalletClient, http, type Address, type PublicClient, type WalletClient } from 'viem'
|
|
import { privateKeyToAccount } from 'viem/accounts'
|
|
import { hardhat } from 'viem/chains'
|
|
|
|
/**
|
|
* 创建公共客户端
|
|
*/
|
|
export function createPublicClientInstance(rpcUrl: string): PublicClient {
|
|
return createPublicClient({
|
|
chain: hardhat,
|
|
transport: http(rpcUrl)
|
|
})
|
|
}
|
|
|
|
/**
|
|
* 创建钱包客户端
|
|
*/
|
|
export function createWalletClientInstance(
|
|
rpcUrl: string,
|
|
privateKey: string
|
|
): WalletClient {
|
|
const account = privateKeyToAccount(privateKey as `0x${string}`)
|
|
return createWalletClient({
|
|
chain: hardhat,
|
|
transport: http(rpcUrl),
|
|
account
|
|
})
|
|
}
|
|
|
|
/**
|
|
* 验证必要的环境变量
|
|
*/
|
|
export function validateEnvVars(): {
|
|
rpcUrl: string
|
|
privateKey: string
|
|
contractAddress: Address
|
|
mainContractAddress: Address
|
|
} {
|
|
const rpcUrl = process.env.RPC_URL || 'http://127.0.0.1:8545'
|
|
const privateKey = process.env.PRIVATE_KEY || ''
|
|
const contractAddress = (process.env.CONTRACT_ADDRESS ||
|
|
'0xdd9956F9e228bA1fa891105d9AC449f2614bd8A2') as Address
|
|
const mainContractAddress = (process.env.MAIN_CONTRACT_ADDRESS ||
|
|
'0xd7fa5C79BeFf459dDD95E0F82c54A75a48eb88ae') as Address
|
|
|
|
if (!privateKey) {
|
|
throw new Error('错误: 未设置PRIVATE_KEY环境变量')
|
|
}
|
|
|
|
return {
|
|
rpcUrl,
|
|
privateKey,
|
|
contractAddress,
|
|
mainContractAddress
|
|
}
|
|
}
|
|
|