liming 1 月之前
父节点
当前提交
fb88d26d74
共有 3 个文件被更改,包括 169 次插入104 次删除
  1. 144 0
      src/composables/useWalletAuth.js
  2. 25 3
      src/views/login/backupMnemonic/index.vue
  3. 0 101
      src/wallet/login.js

+ 144 - 0
src/composables/useWalletAuth.js

@@ -0,0 +1,144 @@
+import Web3 from 'web3'
+import CryptoJS from 'crypto-js'
+
+export function useWalletAuth() {
+  // 登录状态
+  const authState = reactive({
+    isAuthenticated: false, // 登录状态
+    account: null, // 账户
+    privateKey: null, // 私钥
+    encryptedKey: null, // 加密后的密钥
+    loading: false, // 加载状态
+    error: null, // 错误信息
+    chainId: null, // 链ID
+    balance: '0', // 账户余额(ETH)
+    rpcUrl: 'https://api.angeltokens.io' // 您的私有链RPC
+  })
+
+  // Web3实例
+  const web3 = ref(null)
+
+  // 初始化Web3
+  const initWeb3 = () => {
+    try {
+      web3.value = new Web3(authState.rpcUrl)
+      return web3.value
+    } catch (err) {
+      authState.error = '初始化区块链连接失败'
+      return null
+    }
+  }
+
+  // 获取账户余额
+  const getBalance = async () => {
+    if (!authState.account || !web3.value) return '0'
+    
+    try {
+      const weiBalance = await web3.value.eth.getBalance(authState.account)
+      const ethBalance = web3.value.utils.fromWei(weiBalance, 'ether')
+      authState.balance = ethBalance
+      return ethBalance
+    } catch (err) {
+      authState.error = '获取余额失败: ' + err.message
+      return '0'
+    }
+  }
+
+  // 通过私钥登录
+  const loginWithPrivateKey = async (privateKey, password = '') => {
+    authState.loading = true
+    authState.error = null
+
+    try {
+      const web3Instance = initWeb3()
+      if (!web3Instance) throw new Error('区块链连接失败')
+
+      // 验证私钥格式
+      if (!/^0x[0-9a-fA-F]{64}$/.test(privateKey)) {
+        throw new Error('私钥格式不正确')
+      }
+
+      // 加密存储私钥(如果提供了密码)
+      if (password) {
+        authState.encryptedKey = CryptoJS.AES.encrypt(
+          privateKey, 
+          password
+        ).toString()
+      }
+
+      // 从私钥获取账户
+      const account = web3Instance.eth.accounts.privateKeyToAccount(privateKey)
+      
+      // 验证账户有效性
+      const code = await web3Instance.eth.getCode(account.address)
+      if (code !== '0x') {
+        throw new Error('该地址是合约地址,不支持登录')
+      }
+
+      // 更新状态
+      authState.account = account.address
+      authState.privateKey = privateKey
+      authState.isAuthenticated = true
+      authState.chainId = await web3Instance.eth.getChainId()
+      
+      // 登录后自动获取余额
+      await getBalance()
+
+      return {
+        address: account.address,
+        chainId: authState.chainId,
+        balance: authState.balance
+      }
+    } catch (err) {
+      authState.error = err.message || '登录失败'
+      throw err
+    } finally {
+      authState.loading = false
+    }
+  }
+
+  // 通过加密存储登录(需密码)
+  const loginWithStorage = async (password) => {
+    if (!authState.encryptedKey) {
+      throw new Error('没有可用的加密钱包数据')
+    }
+
+    try {
+      // 解密私钥
+      const bytes = CryptoJS.AES.decrypt(authState.encryptedKey, password)
+      const privateKey = bytes.toString(CryptoJS.enc.Utf8)
+      
+      if (!privateKey) throw new Error('密码错误或数据损坏')
+      
+      return await loginWithPrivateKey(privateKey)
+    } catch (err) {
+      authState.error = err.message || '解密失败'
+      throw err
+    }
+  }
+
+  // 登出
+  const logout = () => {
+    authState.isAuthenticated = false
+    authState.account = null
+    authState.privateKey = null
+    authState.chainId = null
+    authState.balance = '0'
+    web3.value = null
+  }
+
+  // 检查本地是否有加密钱包数据
+  const hasStoredWallet = () => {
+    return !!authState.encryptedKey
+  }
+
+  return {
+    authState,
+    web3,
+    loginWithPrivateKey,
+    loginWithStorage,
+    logout,
+    hasStoredWallet,
+    getBalance
+  }
+}

+ 25 - 3
src/views/login/backupMnemonic/index.vue

@@ -9,7 +9,7 @@
      <div class="button-group"  >
 
       <a class="button-group-mnemonic  a-link" @click="copyText" > {{  $t('login.CopyMnemonic')  }}</a>
-      <van-button round block type="primary" native-type="submit">
+      <van-button round block type="primary" native-type="submit" @click="next">
         {{ $t("login.BackupComplete") }}
       </van-button>
     </div>
@@ -21,9 +21,31 @@
 import { Clipboard } from '@capacitor/clipboard';
 import { createAccent } from "@/api/path/login.api";
 import { useSystemStore } from "@/stores/modules/systemStore";
+import { useWalletAuth } from "@/composables/useWalletAuth";
 
 
 const systemStore = useSystemStore();
+const { 
+  authState, 
+  loginWithPrivateKey, 
+  loginWithStorage, 
+  logout, 
+  hasStoredWallet,
+  getBalance
+} = useWalletAuth()
+
+const walletData = ref({})
+
+const next = async () => {
+ 
+  // 登录
+  const data = await loginWithPrivateKey(systemStore.getWallet.privateKey.trim())
+  console.log("data=", data)
+  // 
+  const res = await getBalance()
+  console.log("res=", res)
+}
+
 
 const copyText = async () => {
   await Clipboard.write({
@@ -32,11 +54,11 @@ const copyText = async () => {
   $msg({type: 'success', message: $t("login.CopiedToClipboard")});
 };
 
-const walletData = ref({})
+
 
 onMounted(async () => {
   const { data } = await createAccent({});
-  walletData.value =   JSON.parse(atob(data.content) ) 
+  walletData.value =  JSON.parse(atob(data.content) ) 
   systemStore.setStateValue({
     key: "wallet",
     value: {

+ 0 - 101
src/wallet/login.js

@@ -1,101 +0,0 @@
-import Web3 from "web3";
-
-
-// web3-wallet.js
-class Web3Wallet {
-  constructor() {
-    this.web3 = null;
-    this.account = null;
-    this.chainId = null;
-    
-    // 绑定方法到当前实例
-    this.isWalletInstalled = this.isWalletInstalled.bind(this);
-    this.connectWallet = this.connectWallet.bind(this);
-    this.getAccount = this.getAccount.bind(this);
-    this.getChainId = this.getChainId.bind(this);
-    this.getWeb3 = this.getWeb3.bind(this);
-    this.onAccountsChanged = this.onAccountsChanged.bind(this);
-    this.onChainChanged = this.onChainChanged.bind(this);
-    this.disconnect = this.disconnect.bind(this);
-  }
-
-  // 检查是否安装了钱包
-  isWalletInstalled() {
-    return typeof window.ethereum !== "undefined";
-  }
-
-  // 连接钱包
-  async connectWallet() {
-    if (!this.isWalletInstalled()) {
-      throw new Error("未检测到钱包扩展,请安装MetaMask或其他兼容钱包");
-    }
-
-    try {
-      // 请求账户访问权限
-      const accounts = await window.ethereum.request({
-        method: "eth_requestAccounts",
-      });
-
-      // 获取当前链ID
-      const chainId = await window.ethereum.request({
-        method: "eth_chainId",
-      });
-
-      this.account = accounts[0];
-      this.chainId = parseInt(chainId, 16);
-      this.web3 = new Web3(window.ethereum);
-
-      return {
-        account: this.account,
-        chainId: this.chainId,
-        web3: this.web3,
-      };
-    } catch (error) {
-      console.error("连接钱包失败:", error);
-      throw error;
-    }
-  }
-
-  // 获取当前账户
-  getAccount() {
-    return this.account;
-  }
-
-  // 获取当前链ID
-  getChainId() {
-    return this.chainId;
-  }
-
-  // 获取Web3实例
-  getWeb3() {
-    return this.web3;
-  }
-
-  // 监听账户变化
-  onAccountsChanged(callback) {
-    if (!this.isWalletInstalled()) return;
-
-    window.ethereum.on("accountsChanged", callback);
-  }
-
-  // 监听链变化
-  onChainChanged(callback) {
-    if (!this.isWalletInstalled()) return;
-
-    window.ethereum.on("chainChanged", (chainId) => {
-      callback(parseInt(chainId, 16));
-    });
-  }
-
-  // 断开连接
-  disconnect() {
-    this.account = null;
-    this.chainId = null;
-    this.web3 = null;
-  }
-}
-
-// 创建单例实例
-const web3Wallet = new Web3Wallet();
-
-export default web3Wallet;