# 写给人类的Ethers.js入门教程 **Published by:** [AeroXi](https://paragraph.com/@aeroxi-2/) **Published on:** 2022-06-15 **URL:** https://paragraph.com/@aeroxi-2/ethers-js ## Content 以前一直用web3.js,听说ethers好用,但官方文档难以理解,参考了别的文章后发现确实很好用,于是打算写一篇中文入门教程(更新中) 本文参考了 https://dev.to/hideckies/ethers-js-cheat-sheet-1h5j安装Import// ES Modules import { ethers } from 'ethers'; // CommonJS const { ethers } = require('ethers'); Provider要与区块链交互,需要Provider,可以使用你的节点rpc,也可以使用用户钱包的节点自定义节点rpcconst provider = new ethers.provider.JsonRpcProvider(`url`); url填写你的节点rpc url即可,如果是websocket则需要换成WebSocketProvider使用MetaMask钱包const provider = new ethers.provider.Web3Provider(window.ethereum); Signer发出交易前需要用signer进行签名,signer需拥有私钥代码中签名用私钥初始化Wallet对象const wallet = new ethers.Wallet(privateKey) const signer = wallet.connect(provider) 使用钱包签名当provider是钱包时,可直接获得signerconst signer = provider.getSigner(); 合约交互只读读取合约只需要provider,不发交易改变链上状态const contract = new ethers.Contract(`address`, `abi`, `provider`); 其中abi如果是etherscan上已开源的可以通过api获取读写写合约需要signer,因此第三个参数改为signer即可以对应钱包去发交易const contract = new ethers.Contract(`address`, `abi`, `signer`); 然后用contract.METHOD_NAME可以调用合约相应的方法Event监听监听Pending交易provider.on("pending", (tx) => { console.log(tx) }); 按log过滤监听,可监听指定地址filter = { address: "vitalik.eth", topics: [] } provider.on(filter, (log, event) => { console.log(log) }) 单位转换Ether => Weiconst wei = ethers.utils.parseEther(`ETH`); Wei => Etherconst ether = ethers.utils.formatEther(`wei`); https://embed.0xecho.com.ipns.page?color-theme=auto&desc=&has-h-padding=true&has-v-padding=true&modules=comment%2Clike%2Ctip&receiver=aeroxi.eth&target_uri=https%3A%2F%2Fmirror.xyz%2Faeroxi.eth%2FNsHlKipNwhutSoEZMv_LCFsPUCk0zziksfUFODafQbc&height=800&display=iframe ## Publication Information - [AeroXi](https://paragraph.com/@aeroxi-2/): Publication homepage - [All Posts](https://paragraph.com/@aeroxi-2/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@aeroxi-2): Subscribe to updates