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>
import { ethers } from "ethers";
用私密的方式的載入錢包
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