Day 17【ethers.js】ETHER. ETHER EVERYWHERE.

1iaqng.jpg

【前言】
这两天来记录 ethers.js 我觉得蛮重要的一些学习笔记,今天主要聚焦在一些常见名词,还有连动的基本设定。省略了大部分的东西因为篇幅还有时间有限!

【ethers.js】
ethers.js 是一个完整的 JavaScript 套装 library,是专门使用於与以太坊区块链和相关生态系连动。此套件原本是特别设计在使用 ethers.io上,最後扩展至更全面性的套件。

Ethers.io is an collection of Libraries, Web Tools, Command-Line Utilities and Server Components to assist in the development, deployment, hosting and sharing of Ethereum applications.

What is Ethers? - ethers.io 0.0.1 documentation

下载套件:

npm install --save ethers

导入套件:

// Node.js
const { ethers } = require("ethers");
import { ethers } from "ethers";

常见术语:

  • Provider: (在 ethers 之中)Provider 是一个类别,抽象地说他可以被用来连结以太坊的网路,并且提供一个唯读的条件来查看区块链及其状态。
  • Signer: (在 ethers 之中)Signer 是一个类别,通常会使用一些方法直接地或间接地存取私钥,可以被用於签核资讯及交易,并授权给网络来呈现不同需求。
  • Contract: 此处的 Contract 代表与以太坊网路上特定合约的连结,因此这些应用可以像是普通 JavaScript 物件一样被普遍的使用。

【Connection】

Connecting to Ethereum: Metamask

如果要开始体验或开发以太坊,最快又最简单的方式就是使用 MetaMask。

  • 连接以太坊网路 (Provider)
  • 持有使用者的私钥并以此签核 (Signer)
// A Web3Provider wraps a standard Web3 provider, which is
// what Metamask injects as window.ethereum into each page
const provider = new ethers.providers.Web3Provider(window.ethereum)

// The Metamask plugin also allows signing transactions to
// send ether and pay to change state within the blockchain.
// For this, you need the account signer...
const signer = provider.getSigner()

Connecting to Ethereum: RPC
另外一个着名连动以太坊的方法就是使用 JSON-RPC API,其也可以实作在任何主要的以太坊节点应用 (e.g. Geth and Parity) ,以及许多第三方网页服务上 (e.g. INFURA)。

  • 连接以太坊网路 (Provider)
  • 持有使用者的私钥并以此签核 (Signer)
// If you don't specify a //url//, Ethers connects to the default 
// (i.e. ``http:/\/localhost:8545``)
const provider = new ethers.providers.JsonRpcProvider();

// The provider also allows signing transactions to
// send ether and pay to change state within the blockchain.
// For this, we need the account signer...
const signer = provider.getSigner()

【Provider API - Etherscan Provider】

Provider API Keys:

当我们使用某些可作为 Provider 的 API service (例如 AlchemyEtherscan or INFURA),我们将会需要 API KEY 来允许每一个用来追踪各种目标的服务。

此外,ethers.js 对於每个服务都提供预设的 API keys,因此每个 Provider 都是开箱即用的。 这些 API keys 被提供用来作为社会资源,像是低流量企划或仍在草创期的企划。当然因为他们被所有使用者共用,所以如果被越频繁的使用就会使 response 更慢。

The ethers 强烈建议使用者针对每个服务都申请一个免费的 API keys,因为每个免费的 API keys 都有免付费额度,而其有以下优点:

  • 更多的额度以及同时使用 API 的用量上限
  • 更快速的 responses ,拥有更小的延迟
  • 更有效的追踪方法,让使用者可以去分析顾客的行为
  • 可以使用更进阶的 APIs,像是使用更高阶的函式和索取某些资料

Etherscan:

Etherscan.io 是一个以太坊区块的观察者。是所有用来建设区块和 debug 的开发者工具里面最有用的,并提供额外的 API 终端来连动以太坊区块链。

Sign up for a free API key on Etherscan

【Application Binary Interface】

Application Binary Interface (ABI) 是一个统合介面,专门用来描述如何与智能合约里面元件连动。也就是 Fragments 的统合介面,有 Error, Events, Function 和 Constructor。大部分开发者并不会使用这个比较低阶 (encoding 和 decoding) 的介面来处理网路上的二进位资料,更多的是会使用智能合约里面原本就定义好的介面。

【Contract】

Contract 是一段以太坊区块链中的程序码。Contract 物件使链上的合约可以像普通的 JavaScript 物件一样被使用 ( with the methods mapped to encoding and decoding data )。这个概念有点像资料库里面的 Object Relational Mapper (ORM)。

为了要与链上的智能合约连动,这个被称为 Contract 的类别需要知道在智能合约里面有什麽方法可以被 encode 和 decode 成 data,也就是 ABI 所提供的功能。此外我们在使用 Contract 物件的时候,也可以忽视智能合约里面我们不需要的方法,或称函式。也就是说我们可以把这个 Contract 物件当作 ABI 的子集合。

通常 ABI 都是来自於 Solidity 或 Vyper 的编译器,但使用者可以在程序码里面使用 Human-Readable ABI,像是以下的例子:

// You can also use an ENS name for the contract address
const daiAddress = "dai.tokens.ethers.eth";

// The ERC-20 Contract ABI, which is a common contract interface
// for tokens (this is the Human-Readable ABI format)
const daiAbi = [
  // Some details about the token
  "function name() view returns (string)",
  "function symbol() view returns (string)",

  // Get the account balance
  "function balanceOf(address) view returns (uint)",

  // Send some of your tokens to someone else
  "function transfer(address to, uint amount)",

  // An event triggered whenever anyone transfers to someone else
  "event Transfer(address indexed from, address indexed to, uint amount)"
];

// The Contract object
const daiContract = new ethers.Contract(daiAddress, daiAbi, provider);

4nou9vfuod271.jpg

【ethers.erc20】

所谓的 meta-class 是一个在 run-time 时就被定义的类别。而 Contract 则是被 Application Binary Interface (ABI) 宣告其应该拥有的方法和事件。这些宣告也是在 run-time 时就被创造并加入的。所以我们可以说 Contract 物件是一个属於 meta-class 的类别。

Connecting to a Contract

利用现有的智能合约的地址,并创造一个新的 Contract 物件来与其连接,其 ABI 通常为  Provider 或 Signer。如果是使用 Provider 的话,这些智能合约就会在唯读的情况下被读取,如果是 Signer 则可存取或使用其他更进阶的方法。

// A Human-Readable ABI; for interacting with the contract, we
// must include any fragment we wish to use
const abi = [
    // Read-Only Functions
    "function balanceOf(address owner) view returns (uint256)",
    "function decimals() view returns (uint8)",
    "function symbol() view returns (string)",

    // Authenticated Functions
    "function transfer(address to, uint amount) returns (bool)",

    // Events
    "event Transfer(address indexed from, address indexed to, uint amount)"
];

// This can be an address or an ENS name
const address = "0x4f3b15e4421902c09895fB12c8e0B8821134eA39";

// Read-Only; By connecting to a Provider, allows:
// - Any constant function
// - Querying Filters
// - Populating Unsigned Transactions for non-constant methods
// - Estimating Gas for non-constant (as an anonymous sender)
// - Static Calling non-constant methods (as anonymous sender)
const erc20 = new ethers.Contract(address, abi, provider);

// Read-Write; By connecting to a Signer, allows:
// - Everything from Read-Only (except as Signer, not anonymous)
// - Sending transactions for non-constant functions
const erc20_rw = new ethers.Contract(address, abi, signer);

这边我印象最深刻的函式是 erc20.balanceOf ( owner [ , overrides ] )

⇒ Promise< BigNumber >;其会 Return 这个 owner 所持有的 ERC-20 token 数量。

await erc20.balanceOf(signer.getAddress())
// { BigNumber: "100000000000000000000" }

【小结】
今天感觉篇幅有点短哈哈哈哈哈哈哈哈,反正东西多到永远学不完,重点就是!大家在使用的时候要记得不要在网站里面乱 call Private Key 喔!

f27d9778b62826005ea18939e05d4942.jfif

【参考资料】
Documentation
ethereum(Docker)


<<:  DAY 17- 杂凑函数 HASH

>>:  [2021铁人赛 Day14] General Skills 11

Day40. 范例:假期规划 (建造者模式)

本文同步更新於blog 情境:目前提供旅游行程的方式 <?php namespace Ap...

Day 4 | 游戏角色介绍

昨天我们提到这个游戏共有五个关卡,接下来今天要依照关卡分别介绍我们的角色故事 肥遗 某一个村庄莫名闹...

[Day 26] - React 前端串後端 - 串接登入

经过一整天的奋斗,终於跟React稍微熟了一点 首先建一个apiUtil.js 我打算把跟後端相关的...

用 Python 畅玩 Line bot - 17:Template message

Line bot API 中有一种只有 line bot 专属的讯息种类,叫做 Template m...

23.移转 Aras PLM大小事-流程签核动态指派(2)

设定好角色栏位後,接下来就是大量同步BPM角色名单的签核主管 因此下方程序执行的步骤 1.读取BPM...