4. 发送ETH
signer 签名类
Web3.js
认为用户会在本地部署以太坊节点,私钥和网络连接状态由这个节点管理(实际并不是这样);而在ethers.js
中,Provider
提供器类管理网络连接状态,Signer
签名者类或Wallet
钱包类管理密钥,安全且灵活。
wallet 钱包类
Wallet
类继承了Signer
类,并且开发者可以像包含私钥的外部拥有帐户(EOA
)一样,用它对交易和消息进行签名
创建 wallet 钱包实例
创建钱包实例的方法有三种,创建随机钱包(新建钱包)、使用私钥创建钱包、从助记词创建钱包
- 方法1. 创建随机的wallet对象(新建钱包)
可以利用ethers.Wallet.createRandom()
函数创建带有随机私钥的Wallet
对象。该私钥由加密安全的熵源生成,如果当前环境没有安全的熵源,则会引发错误(没法在在线平台playcode
使用此方法)。
// 创建随机的wallet对象
const wallet1 = new ethers.Wallet.createRandom()
- 方法2. 用私钥创建wallet对象(恢复钱包)
我们已知私钥的情况下,可以利用ethers.Wallet()
函数创建Wallet
对象。
// 利用私钥和provider创建wallet对象
const privateKey = '0x227dbb8586117d55284e26620bc76534dfbd2394be34cf4a09cb775d593b6f2b'
const wallet2 = new ethers.Wallet(privateKey, provider)
- 方法3. 使用助记词创建钱包实例(恢复钱包)
我们已知助记词的情况下,可以利用ethers.Wallet.fromMnemonic()
函数创建Wallet
对象
// 从助记词创建wallet对象
const wallet3 = new ethers.Wallet.fromMnemonic(mnemonic.phrase)
发送 ETH
Wallet
实例来发送ETH
。首先,我们要构造一个交易请求,在里面声明接收地址to
和发送的ETH
数额value
// 创建交易请求,参数:to为接收地址,value为ETH数额
const tx = {
to: address1,
value: ethers.utils.parseEther("0.001")
}
利用Wallet
类的sendTransaction
来发送交易,等待交易上链,并获得交易的收据,非常简单。
//发送交易,获得收据
const receipt = await wallet2.sendTransaction(tx)
await receipt.wait() // 等待链上确认交易
console.log(receipt) // 打印交易详情
代码部分
- 创建 provider
// 1. provider 实例
const providerTest = new ethers.providers.JsonRpcProvider(testNetWork)
// 2. 创建钱包实例
// 2.1 创建随机钱包实例(新建) 单机
const wallet1 = ethers.Wallet.createRandom()
const walletProvider = wallet1.connect(providerTest)
const walletKey = walletProvider.privateKey
const balance = await walletProvider.getBalance()
console.log('wallet1 发送前的钱包余额', balance.toNumber())
// 2.2 通过私钥创建实例
const wallet2Key = '5e34716a60a0926d67c629fae8752cdc9fbe742095a093d40e5b1a2834cc981e'
const wallet2 = new ethers.Wallet(wallet2Key,providerTest)
const wallet2Address = await wallet2.getAddress()
const balance2 = await wallet2.getBalance()
console.log('wallet2 发送前的钱包余额', ethers.utils.formatEther(balance2))
// console.log('wallet2Address',wallet2Address)
// 2.3 通过助记词来创建实例
// console.log('walletProvider.mnemonic',walletProvider.mnemonic.phrase)
// const mnemonic = walletProvider.mnemonic.phrase
// const wallet3 = new ethers.Wallet.fromMnemonic(mnemonic)
// console.log('wallet1 和 wallet3 地址是否一样', await walletProvider.getAddress() === await wallet3.getAddress())
// 3 发送ETH
const wallet1Address = await walletProvider.getAddress()
console.log('wallet1Address',wallet1Address)
const tx = {
to: wallet1Address,
value: ethers.utils.parseEther('0.01')
}
const receipt = await wallet2.sendTransaction(tx)
// 等待链上交易确认
const result = await receipt.wait()
console.log('result',result)
const resultBalace = await walletProvider.getBalance()
console.log('发送后 wallet1 的余额', ethers.utils.formatEther(resultBalace))