欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

基于React Native和Ethers.js的电子钱包(三):Ethers.js

发布时间:2025/4/16 编程问答 93 豆豆
生活随笔 收集整理的这篇文章主要介绍了 基于React Native和Ethers.js的电子钱包(三):Ethers.js 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
之前在学Solidity的时候知道了以太坊提供了一个JavaScript API——Web3.js——对以太坊进行API调用的工具包。但最近做RN的时候又发现了另外一种API——Ethers.js


在Medium上找到了一篇文章或许能帮助理解

文章列出了六条Ethers.js的特点,但与Web3最主要的区别在于两点:

1. ENS names are first-class citizens

2. Separation of concerns---key management and state

ENS是Ethereum Name Service的缩写,通常我们在以太坊上进行交易的时候需要输入对方的交易地址,这个地址是一串16进制的哈希值,又长又难记,毫无规律,但有了ENS就简单多了,地址不再是冰冷的数字和字母,而是一个简单的、可读性强的字符串,类似jack.mywallet.eth,没错,jack.mywallet.eth就是一个实实在在以太坊地址

所以在Ethers.js中将ENS作为“一等公民”对待,对于实际用户,目的是想弱化“地址”的概念;对于开发者来说,可以不管实际合约地址的更新,直接调用解析器获取ENS地址

针对Ethers.js的第二个特点,简单来说就是提供了跟账户和钱包相关的API


下面通过示例讲讲如何在React Native中使用Ethers.js

开始前,可以先在本地装一个以太坊的钱包测试用,这里我选择MetaMask


接着就是安装Ethers.js

npm install -save ethers复制代码


然后在需要使用Ethers.js的地方引入该模块:

import { ethers } from 'ethers';复制代码


1. 通过助记词生成钱包地址

let newMnemonic = ethers.utils.HDNode.entropyToMnemonic(ethers.utils.randomBytes(16));复制代码

ethers.utils.HDNode.entropyToMnemonic():

通过传入一个随机的16字节参数来生成一个随机的、有效的助记词

ethers.utils.randomBytes():

生成一个16字节的,即12个英文单词长度的助记词

Tip: 可以通过ehters.utils.HDNode.entropyToMnemonic(ethers.utils.randomBytes(16), ethers.wordlists.zh_ch)生成中文的助记词哦

根据助记词和BIP-039+BIP-044协议生成钱包对象:

let wallet = ethers.Wallet.fromMnemonic(newMnemonic, 'm/44\'/60\'/0\'/0/');复制代码

获取以太坊测试网络ropsten,并将wallet连接到该网络:

provider = ethers.getDefaultProvider('ropsten'); let activeWallet = wallet.connect(this.provider);复制代码


启动RN,可以看到和MetaMask生成了相同地址的账户:




这说明连接以太坊测试网络成功


2. 获取账户余额以及发送交易

//get address balance activeWallet.getBalance('pending').then((balance) => {this.setState({etherString: ethers.utils.formatEther(balance, {commify: true})}) }, (error) => {console.log(error) });//get address transaction count activeWallet.getTransactionCount('pending').then((transactionCount) => {this.setState({transaction: transactionCount.toString()}) }, (error) => {console.log(error) });emitTransaction(wallet) {let activeWallet = wallet.connect(this.provider)activeWallet.sendTransaction({to: ethers.utils.getAddress(this.props.addresses[this.state.pickerValue]),value: ethers.utils.parseEther(this.state.etherVal)}).then((tx) => {console.log(tx)}, (error) => {console.log(error)}) }复制代码


点击Refresh获取当前账户的余额及交易次数:



发送交易:



交易成功:



账户余额发生变化:



相关链接:

Ether Scan is here: ropsten.etherscan.io/address/0x2…

Here are the links:

Ethers.js: docs.ethers.io/ethers.js/h…

ENS: docs.ens.domains/en/latest/i…

Announcing ethers.js --- a web3 alternative: medium.com/l4-media/an…


转载于:https://juejin.im/post/5cf385acf265da1bb003a7b7

总结

以上是生活随笔为你收集整理的基于React Native和Ethers.js的电子钱包(三):Ethers.js的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。