Article directory
-
- 1. Project preparation
- 2. Wallet-related concepts
- 3. Randomly create a wallet
- 4. Import the wallet according to the mnemonic
- 5. Import wallet according to keystore
- 6. Signature transfer
1. Project preparation
- Install ether.js
npm install --save ethers
Three ways to introduce ether.js:
- es3:
var ethers = require('ethers');
- es5/es6
const ethers = require('ethers');
- javascript/typescript-es6
import ethers from 'ethers';
2. Wallet-related concepts
The default here is that you already understand the relationship between address, password, private key, mnemonic, and Keystore, so I won’t introduce too much, just list the relationship between them:
address = bank card number password = bank card password Private key = bank card number + password Mnemonic phrase = bank card number + password Keystore = encrypted private key Keystore + password = private key
3. Randomly create a wallet
The Wallet class of ethers used:
ethers.Wallet.createRandom()
createRandom returns a new wallet with a random private key, generated from a cryptographically secure source of entropy. An error is thrown if the current environment does not have a safe source of entropy.
Wallets created using this method will have the mnemonic phrase
createNewWallet() {<!-- --> let walletRandom = ethers. Wallet. createRandom() // wallet mnemonic object let mnemonic = walletRandom.mnemonic //Wallet mnemonic words let phrase = mnemonic. phrase //path: "m/44'/60'/0'/0/0", let path = mnemonic.path // wallet address let address = walletRandom.address //Wallet public key let publicKey = walletRandom. publicKey //Wallet private key let privateKey = walletRandom. privateKey //Generate the keystore file through the password set by the user let password = "123456" walletRandom.encrypt(password).then((keystory_string) => {<!-- --> let keystory_json = JSON. parse(keystory_string) //The keystore string of the wallet this.keystory = keystory_string console.log(keystory_json) }) \t //The mnemonic of the wallet can be encrypted and stored locally through AES symmetric encryption let encryptPassword = "1234qwer" let encryptedPhrase = encryption(phrase, encryptPassword) console.log('encrypted mnemonic:', encryptedPhrase) let decryptedPhrase = decryption(encryptedPhrase, encryptPassword) console.log('decrypted mnemonic:', decryptedPhrase) }
import * as CryptoJS from 'crypto-js' //Data symmetric encryption function encryption(data, password) {<!-- --> let encrypted = CryptoJS.AES.encrypt(data, password); return encrypted. toString() } //Data decryption function decryption(encrypted, password) {<!-- --> let decrypted = CryptoJS.AES.decrypt(encrypted, password); return decrypted.toString(CryptoJS.enc.Utf8); }
4. Import the wallet according to the mnemonic
ethers.Wallet.fromMnemonic( mnemonic [ , path , [ wordlist ] ] ) ? Wallet
Create an instance from a mnemonic phrase.
If no path is specified, the default path of Ethereum (such as m/44’/60’/0’/0/0) will be used.
If wordlist is not specified, English Wordlist is used.
async createWalletByPhrase() {<!-- --> //default path let path = ethers.utils.defaultPath //Wallet mnemonic words to be imported let phrase = 'able fee damage express distress visit fine claim similar attract awkward market' let mnemonic = ethers.Wallet.fromMnemonic(phrase) //Wallet private key let privateKey = mnemonic. privateKey \t //Create a wallet instance through the wallet private key let wallet = new ethers. Wallet(privateKey) //Wallet public key let publicKey = wallet. publicKey // wallet address let address = wallet.address //Generate the keystore file through the password set by the user let password = "123456" wallet.encrypt(password).then((keystory_string) => {<!-- --> let keystory_json = JSON. parse(keystory_string) let keystory = keystory_string console.log(keystory_json) }) }
5. Import wallet according to keystore
ethers.Wallet.fromEncryptedJson( json , password [ , progress ] ) ? Promise< Wallet >source
Create an instance from an encrypted JSON wallet.
If progress is provided, it will be called during decryption with a value between 0 and 1, indicating a completed progress.
createWalletByKeystory() {<!-- --> \t //Wallet keystore to be imported let keystory = '{"address":"df9e902814baba3ddc6b4a1ac9db11bc79eda07f","id":"60db3db5-ef64-400a-b25e-3615a9bdfa24","version":3,"crypto":{ "cipher":"aes-128-ctr","cipherparams":{"iv":"f4c7ece791d112dc408537203aa2bb10"},"ciphertext":"acba3333e3d7078e2186ebd561c28bf0e4a8c105e4b1eec40bec20616441cc31"," kdf":"scrypt","kdfparams":{"salt":"f1e8acd43868559c1ecda1c9b31489efd12f6c7c9302710b957a3b779dd6ec54","n":131072,"dklen":32,"p" :1,"r":8},"mac":"e466473ae761f98b1f26354e27305ce23e41b5d5c8a5674b65675bdfbf848718"},"x-ethers":{"client":"ethers.js"," gethFilename":"UTC--2023-03-25T03-36-38.0Z--df9e902814baba3ddc6b4a1ac9db11bc79eda07f","mnemonicCounter":"e4482220566b9a9f9d821c1352d1708f","mnemonicCiphertext":"7357682acae64479641611e17e1c6473",\ "path":"m/44'/60'/0'/0/0","locale":"en","version":"0.1" }}' //Change the password used when the keystore was created let password = "123456" ethers.Wallet.fromEncryptedJson(keystory, password).then((wallet) => {<!-- --> console.log('wallet instance:', wallet) // wallet address let address = wallet.address //Wallet public key let publicKey = wallet. publicKey //Wallet private key let privateKey = wallet. privateKey // default path let path = ethers.utils.defaultPath }) }
6. Signature transfer
async sendTransaction() {<!-- --> //ETH // let network = 'goerli' // let contractAddress = '' //Polygon // let network = 'maticmum' // let contractAddress = '' //BSC // let network = 'https://bsc-dataseed.binance.org/' let network = 'https://data-seed-prebsc-1-s1.binance.org:8545/' let contractAddress = '' //Use Infura as RPC //let projectId = '' // let provider = new ethers.providers.InfuraProvider(network, projectId) let provider = new ethers.providers.JsonRpcProvider(network); let privateKey = '0x0fb9146e20a3bd3497b47de967316c8aa7f83818ddc62429a24774f0df1f8065' let wallet = new ethers. Wallet(privateKey, provider) // let balance = await wallet. getBalance('latest') // console.log('balance:', balance) // console.log('balance:', ethers.utils.formatEther(balance)) // console.log(await wallet.getChainId()) // return /** //ETH transfer let tx = { to: '', value: ethers.utils.parseEther('0.001'), chainId: ethers.BigNumber.from('5').toHexString() } let res = await wallet. sendTransaction(tx) console. log(res) */ /** * //Use signers for ERC20 transfer let contract = new ethers.Contract(contractAddress, GBK.abi, wallet) console. log(contract) let balance = await contract.balanceOf(wallet.address) balance = ethers.utils.formatEther(balance) console. log(balance) let res = await contract. transfer('', ethers. utils. parseUnits('1')) console. log(res) */ }