基于React Native和Ethers.js的电子钱包(三):Ethers.js
在Medium上找到了一篇文章或許能幫助理解
文章列出了六條Ethers.js的特點(diǎn),但與Web3最主要的區(qū)別在于兩點(diǎn):
1. ENS names are first-class citizens
2. Separation of concerns---key management and state
ENS是Ethereum Name Service的縮寫,通常我們?cè)谝蕴簧线M(jìn)行交易的時(shí)候需要輸入對(duì)方的交易地址,這個(gè)地址是一串16進(jìn)制的哈希值,又長(zhǎng)又難記,毫無(wú)規(guī)律,但有了ENS就簡(jiǎn)單多了,地址不再是冰冷的數(shù)字和字母,而是一個(gè)簡(jiǎn)單的、可讀性強(qiáng)的字符串,類似jack.mywallet.eth,沒(méi)錯(cuò),jack.mywallet.eth就是一個(gè)實(shí)實(shí)在在以太坊地址
所以在Ethers.js中將ENS作為“一等公民”對(duì)待,對(duì)于實(shí)際用戶,目的是想弱化“地址”的概念;對(duì)于開(kāi)發(fā)者來(lái)說(shuō),可以不管實(shí)際合約地址的更新,直接調(diào)用解析器獲取ENS地址
針對(duì)Ethers.js的第二個(gè)特點(diǎn),簡(jiǎn)單來(lái)說(shuō)就是提供了跟賬戶和錢包相關(guān)的API
下面通過(guò)示例講講如何在React Native中使用Ethers.js
開(kāi)始前,可以先在本地裝一個(gè)以太坊的錢包測(cè)試用,這里我選擇MetaMask
接著就是安裝Ethers.js
npm install -save ethers復(fù)制代碼然后在需要使用Ethers.js的地方引入該模塊:
import { ethers } from 'ethers';復(fù)制代碼1. 通過(guò)助記詞生成錢包地址
let newMnemonic = ethers.utils.HDNode.entropyToMnemonic(ethers.utils.randomBytes(16));復(fù)制代碼ethers.utils.HDNode.entropyToMnemonic():
通過(guò)傳入一個(gè)隨機(jī)的16字節(jié)參數(shù)來(lái)生成一個(gè)隨機(jī)的、有效的助記詞
ethers.utils.randomBytes():
生成一個(gè)16字節(jié)的,即12個(gè)英文單詞長(zhǎng)度的助記詞
Tip: 可以通過(guò)ehters.utils.HDNode.entropyToMnemonic(ethers.utils.randomBytes(16), ethers.wordlists.zh_ch)生成中文的助記詞哦
根據(jù)助記詞和BIP-039+BIP-044協(xié)議生成錢包對(duì)象:
let wallet = ethers.Wallet.fromMnemonic(newMnemonic, 'm/44\'/60\'/0\'/0/');復(fù)制代碼獲取以太坊測(cè)試網(wǎng)絡(luò)ropsten,并將wallet連接到該網(wǎng)絡(luò):
provider = ethers.getDefaultProvider('ropsten'); let activeWallet = wallet.connect(this.provider);復(fù)制代碼啟動(dòng)RN,可以看到和MetaMask生成了相同地址的賬戶:
這說(shuō)明連接以太坊測(cè)試網(wǎng)絡(luò)成功
2. 獲取賬戶余額以及發(fā)送交易
//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)}) }復(fù)制代碼點(diǎn)擊Refresh獲取當(dāng)前賬戶的余額及交易次數(shù):
發(fā)送交易:
交易成功:
賬戶余額發(fā)生變化:
相關(guān)鏈接:
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…
轉(zhuǎn)載于:https://juejin.im/post/5cf385acf265da1bb003a7b7
總結(jié)
以上是生活随笔為你收集整理的基于React Native和Ethers.js的电子钱包(三):Ethers.js的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: if,elif,else的关系 inpu
- 下一篇: Android初级开发笔记-- acti