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

3,468 阅读2分钟
之前在学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…