123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- import { defineStore } from "pinia";
- import Web3 from "web3";
- import CryptoJS from "crypto-js";
- export const useWalletStore = defineStore("useWalletStore", {
- state: () => ({
- id: "", // name + @ + account
- isAuthenticated: false, // 登录状态
- account: null, // 钱包地址
- privateKey: null, // 私钥
- encryptedKey: localStorage.getItem("encryptedKey") || null, // 加密后的密钥
- loading: false, // 加载状态
- error: null, // 错误信息
- chainId: null, // 链ID
- balance: "0", // 账户余额(ETH)
- rpcUrl: "", // 您的私有链RPC
- username: "", // 用户名
- accountName: "", //网络昵称
- accountIcon: "", // 网络头像
- accountPassword: null, // 密码
- accountHint: "", // 提示词
- words: "", // 助记词
- walletList: [], // 钱包列表
- }),
- persist: true,
- getters: {
- getWalletList() {
- return this.walletList;
- },
- },
- actions: {
- async initWeb3() {
- try {
- window.$web3 = new Web3(this.rpcUrl);
- return window.$web3
- } catch (err) {
- console.log(err);
- this.error = "初始化区块链连接失败";
- return null;
- }
- },
-
- async getBalance() {
- if (!this.account || !window.$web3) {
- await this.initWeb3()
- }
- try {
- const weiBalance = await window.$web3.eth.getBalance(this.account);
- this.balance = await window.$web3.utils.fromWei(weiBalance, "ether");
- return this.balance;
- } catch (err) {
- this.error = "获取余额失败";
- return "0";
- }
- },
- async loginWithPrivateKey(password = "") {
- this.loading = true;
- this.error = null;
- try {
- const web3 = window.$web3 || (await this.initWeb3());
- if (!web3) throw new Error("区块链连接失败");
- if (!/^0x[0-9a-fA-F]{64}$/.test(this.privateKey)) {
- throw new Error("私钥格式不正确");
- }
-
- // if (password) {
- // this.encryptedKey = CryptoJS.AES.encrypt(
- // privateKey,
- // password
- // ).toString();
- // localStorage.setItem("encryptedKey", this.encryptedKey);
- // }
- const account = await web3.eth.accounts.privateKeyToAccount(this.privateKey);
- const code = await web3.eth.getCode(account.address);
-
- if (code !== "0x") throw new Error("该地址是合约地址,不支持登录");
- this.account = account.address;
- this.isAuthenticated = true;
- this.chainId = `${await web3.eth.getChainId()}n`;
- await this.getBalance();
- return {
- address: account.address,
- chainId: this.chainId,
- balance: this.balance,
- };
- } catch (err) {
- console.log("登录失败");
- this.error = err.message || "登录失败";
- throw err;
- }finally {
- this.$persist();
- this.loading = false;
- }
- },
- },
- });
|