Appearance
账户
作者 崔棉大师 X:@MasterCui Youtube: 崔棉大师
知识点
本章节将学会在本地目录安装@solana/web3.js
依赖包,通过 js 脚本创建账号的过程,并且保存账号私钥用于后面的开发过程
课程
1.安装
在本地系统中创建一个项目目录,之后安装 spl-token 的依赖,确保你的系统中已经安装好了nodejs
sh
npm init -y
npm install @solana/web3.js @solana/spl-token
2.配置节点
在你的脚本中你可以自定义节点地址,或者使用默认的开发网 devnet
js
import { Connection, clusterApiUrl } from "@solana/web3.js";
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
3.创建密钥对
js
import { Keypair } from "@solana/web3.js";
let keypair = Keypair.generate();
4.领取空投
js
import {
Keypair,
Connection,
clusterApiUrl,
LAMPORTS_PER_SOL,
} from "@solana/web3.js";
let payer = Keypair.generate();
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
const airdropSignature = await connection.requestAirdrop(
payer.publicKey,
LAMPORTS_PER_SOL
);
await connection.confirmTransaction(airdropSignature);
4.保存私钥
5.恢复密钥
恢复密钥可以有两种形式,有的密钥保存为数组形式:
js
const keypair = Keypair.fromSecretKey(
Uint8Array.from([
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56,
222, 53, 138, 189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246,
15, 185, 186, 82, 177, 240, 148, 69, 241, 227, 167, 80, 141, 89, 240, 121,
121, 35, 172, 247, 68, 251, 226, 218, 48, 63, 176, 109, 168, 89, 238, 135,
])
);
有的密钥保存为 Base58 形式:
js
const keypair = Keypair.fromSecretKey(
bs58.decode(
"5MaiiCavjCmn9Hs1o3eznqDEhRwxo7pXiAYez7keQUviUkauRiTMD8DrESdrNjN8zd9mTmVhRvBJeg5vhyvgrAhG"
)
);
6.生成助记词
助记词属于 BIP39 协议,是在大多数区块链中通用的,同一套助记词可以用于比特币,以太坊以及 Solana,其根本原理是通过将随机数转换为英文单词的形式保存私钥
js
const mnemonic = bip39.generateMnemonic();
7.恢复助记词
js
const mnemonic =
"pill tomorrow foster begin walnut borrow virtual kick shift mutual shoe scatter";
const seed = bip39.mnemonicToSeedSync(mnemonic, ""); // (mnemonic, password)
const keypair = Keypair.fromSeed(seed.slice(0, 32));
挑战
- 生成HD钱包
- 生成自定义地址前缀