walletStore.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import { defineStore } from "pinia";
  2. import Web3 from "web3";
  3. import CryptoJS from "crypto-js";
  4. export const useWalletStore = defineStore("useWalletStore", {
  5. state: () => ({
  6. id: "", // name + @ + account
  7. isAuthenticated: false, // 登录状态
  8. account: null, // 钱包地址
  9. privateKey: null, // 私钥
  10. encryptedKey: localStorage.getItem("encryptedKey") || null, // 加密后的密钥
  11. loading: false, // 加载状态
  12. error: null, // 错误信息
  13. chainId: null, // 链ID
  14. balance: "0", // 账户余额(ETH)
  15. rpcUrl: "", // 您的私有链RPC
  16. username: "", // 用户名
  17. accountName: "", //网络昵称
  18. accountIcon: "", // 网络头像
  19. accountPassword: null, // 密码
  20. accountHint: "", // 提示词
  21. words: "", // 助记词
  22. walletList: [], // 钱包列表
  23. }),
  24. persist: true,
  25. getters: {
  26. getWalletList() {
  27. return this.walletList;
  28. },
  29. },
  30. actions: {
  31. async initWeb3() {
  32. try {
  33. window.$web3 = new Web3(this.rpcUrl);
  34. return window.$web3
  35. } catch (err) {
  36. console.log(err);
  37. this.error = "初始化区块链连接失败";
  38. return null;
  39. }
  40. },
  41. async getBalance() {
  42. if (!this.account || !window.$web3) {
  43. await this.initWeb3()
  44. }
  45. try {
  46. const weiBalance = await window.$web3.eth.getBalance(this.account);
  47. this.balance = await window.$web3.utils.fromWei(weiBalance, "ether");
  48. return this.balance;
  49. } catch (err) {
  50. this.error = "获取余额失败";
  51. return "0";
  52. }
  53. },
  54. async loginWithPrivateKey(password = "") {
  55. this.loading = true;
  56. this.error = null;
  57. try {
  58. const web3 = window.$web3 || (await this.initWeb3());
  59. if (!web3) throw new Error("区块链连接失败");
  60. if (!/^0x[0-9a-fA-F]{64}$/.test(this.privateKey)) {
  61. throw new Error("私钥格式不正确");
  62. }
  63. // if (password) {
  64. // this.encryptedKey = CryptoJS.AES.encrypt(
  65. // privateKey,
  66. // password
  67. // ).toString();
  68. // localStorage.setItem("encryptedKey", this.encryptedKey);
  69. // }
  70. const account = await web3.eth.accounts.privateKeyToAccount(this.privateKey);
  71. const code = await web3.eth.getCode(account.address);
  72. if (code !== "0x") throw new Error("该地址是合约地址,不支持登录");
  73. this.account = account.address;
  74. this.isAuthenticated = true;
  75. this.chainId = `${await web3.eth.getChainId()}n`;
  76. await this.getBalance();
  77. return {
  78. address: account.address,
  79. chainId: this.chainId,
  80. balance: this.balance,
  81. };
  82. } catch (err) {
  83. console.log("登录失败");
  84. this.error = err.message || "登录失败";
  85. throw err;
  86. }finally {
  87. this.$persist();
  88. this.loading = false;
  89. }
  90. },
  91. },
  92. });