iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 11
0
Blockchain

有什麼新鮮事發生在 Ethereum系列 第 11

Day11 - 介紹 Ether.js

web3.js 一直詬病的問題的問題就是 API 不太友善,如果同樣需求的程式,改用 Ether.js 模組的話,就會簡潔很多。

web3.js 範例

<script>
  ethers.onready = function() {
    startApp();
  };
</script>

ether.js 範例

<script>
  // https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md
  window.addEventListener("load", function() {
    // 檢查瀏覽器是否有安裝 Mist / MetaMask。
    if (typeof web3 !== "undefined") {
      // 如果有安裝的話,就直接使用 Mist / MetaMask 的 provider
      web3js = new Web3(web3.currentProvider);
    } else {
      web3js = new Web3(
        new Web3.providers.HttpProvider("http://localhost:8545")
      );
    }

    startApp();
  });
</script>

支援 TypeScript

import { ethers } from "ethers";

錢包相關的 API

用私密的方式的載入錢包

let privateKey =
  "0x0123456789012345678901234567890123456789012345678901234567890123";
let wallet = new ethers.Wallet(privateKey);

let provider = ethers.getDefaultProvider();
let walletWithProvider = new ethers.Wallet(privateKey, provider);

建立隨機帳號

let randomWallet = ethers.Wallet.createRandom();

用助憶詞 (mnemonic phrase) 的方式載入錢包

let mnemonic =
  "radar blur cabbage chef fix engine embark joy scheme fiction master release";
let mnemonicWallet = ethers.Wallet.fromMnemonic(mnemonic);

// Load the second account from a mnemonic
let path = "m/44'/60'/1'/0/0";
let secondMnemonicWallet = ethers.Wallet.fromMnemonic(mnemonic, path);

// Load using a non-english locale wordlist (the path "null" will use the default)
let secondMnemonicWallet = ethers.Wallet.fromMnemonic(
  mnemonic,
  null,
  ethers.wordlists.ko
);

https://docs.ethers.io/ethers.js/html/api-wallet.html#wallet

資料來源


上一篇
Day10 - Remix IDE 部署和執行
下一篇
Day12 - 以太坊開發者大會 (Devcon)
系列文
有什麼新鮮事發生在 Ethereum30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言