You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需MetaMask在Chrome实现以太坊投票系统及Gas支付的方法问询

Can I Vote & Pay Gas Without MetaMask in Chrome?

Yes, you absolutely can! MetaMask is just one of many tools to interact with Ethereum in the browser. Below are practical, secure methods to implement voting and gas payments without relying on the MetaMask extension, tailored for your existing web-based voting system:

WalletConnect lets users connect your web app to their mobile Ethereum wallets (like Trust Wallet, Coinbase Wallet, Rainbow) via a QR code—no browser extension required. This is a popular, non-custodial option that keeps users in control of their funds.

Implementation Steps:

  1. Install the required libraries:
    npm install @walletconnect/client @walletconnect/qrcode-modal
    
  2. Initialize the connector and handle session setup in your frontend:
    import WalletConnect from "@walletconnect/client";
    import QRCodeModal from "@walletconnect/qrcode-modal";
    
    // Initialize WalletConnect connector
    const connector = new WalletConnect({
      bridge: "https://bridge.walletconnect.org", // Default trusted bridge
      qrcodeModal: QRCodeModal,
    });
    
    // Check for existing connection, or create a new session
    if (!connector.connected) {
      connector.createSession();
    }
    
    // Listen for successful connection
    connector.on("connect", (error, payload) => {
      if (error) throw error;
      const { accounts, chainId } = payload.params[0];
      console.log("Connected wallet address:", accounts[0]);
      // Use this account to interact with your voting contract
    });
    
    // Handle disconnection
    connector.on("disconnect", (error) => {
      if (error) console.error("Disconnection error:", error);
      // Reset your app's connection state here
    });
    
  3. Modify your existing voting function to use the WalletConnect provider:
    import { ethers } from "ethers";
    
    async function castVote(candidateId) {
      try {
        // Create Ethers provider from WalletConnect
        const provider = new ethers.providers.Web3Provider(connector);
        const signer = provider.getSigner();
        
        // Initialize your voting contract (use your existing address/ABI)
        const votingContract = new ethers.Contract(
          YOUR_CONTRACT_ADDRESS,
          YOUR_CONTRACT_ABI,
          signer
        );
    
        // Send vote transaction
        const tx = await votingContract.vote(candidateId);
        await tx.wait();
        console.log("Vote confirmed! Transaction hash:", tx.hash);
      } catch (error) {
        console.error("Vote failed:", error.message);
      }
    }
    

Notes:

  • Users need a mobile Ethereum wallet installed to scan the QR code.
  • Gas fees are paid directly from the connected mobile wallet's ETH balance.

Method 2: Embedded Custodial Wallets

Custodial providers like Magic.link or Coinbase Wallet offer embedded wallet solutions that let users create or log into wallets directly in your web app. This provides a seamless in-browser experience without extensions.

  1. Sign up for the service to get your API key.
  2. Install the SDK:
    npm install magic-sdk @magic-sdk/ethers
    
  3. Initialize the wallet and handle user login:
    import { Magic } from "magic-sdk";
    import { MagicEthersProvider } from "@magic-sdk/ethers";
    
    const magic = new Magic("YOUR_API_KEY", {
      network: {
        rpcUrl: "https://mainnet.infura.io/v3/YOUR_INFURA_KEY", // Use your preferred RPC endpoint
        chainId: 1, // Adjust for testnets (e.g., 5 for Goerli)
      },
    });
    
    // Log users in via email magic link
    async function loginWithEmail(email) {
      await magic.auth.loginWithMagicLink({ email });
      const provider = new MagicEthersProvider(magic);
      const signer = provider.getSigner();
      const userAddress = await signer.getAddress();
      console.log("User wallet address:", userAddress);
    }
    
  4. Update your voting function to use the Magic signer:
    async function castVote(candidateId) {
      try {
        const provider = new MagicEthersProvider(magic);
        const signer = provider.getSigner();
        const votingContract = new ethers.Contract(
          YOUR_CONTRACT_ADDRESS,
          YOUR_CONTRACT_ABI,
          signer
        );
    
        const tx = await votingContract.vote(candidateId);
        await tx.wait();
        console.log("Vote successful!");
      } catch (error) {
        console.error("Vote failed:", error);
      }
    }
    

Notes:

  • Custodial wallets manage user private keys (convenient but requires trusting the provider).
  • You can optionally sponsor gas fees for users using services like the Gas Station Network (GSN) to improve UX.

Method 3: Direct Private Key Integration (Testing Only!)

You could technically use a user's private key to sign transactions directly in the frontend, but this is extremely insecure—exposing private keys in client-side code risks theft. This should only be used for local testing, never production.

Example (For Testing Purposes):

import { ethers } from "ethers";

// NEVER hardcode private keys in production!
const userPrivateKey = "USER_TEST_PRIVATE_KEY";
const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_ENDPOINT");
const wallet = new ethers.Wallet(userPrivateKey, provider);

async function castVote(candidateId) {
  try {
    const votingContract = new ethers.Contract(
      YOUR_CONTRACT_ADDRESS,
      YOUR_CONTRACT_ABI,
      wallet
    );
    const tx = await votingContract.vote(candidateId);
    await tx.wait();
    console.log("Test vote confirmed!");
  } catch (error) {
    console.error("Test vote failed:", error);
  }
}

Critical Warning:

  • Never expose private keys in frontend code. This method is only for local testing with throwaway testnet accounts.

Key Considerations

  • Security: Prioritize non-custodial options like WalletConnect for production to keep users in control of their funds.
  • User Experience: Embedded wallets offer the most seamless flow, while WalletConnect requires a mobile app but is more decentralized.
  • Gas Fees: All methods require the user (or your app via sponsorship) to have sufficient ETH to cover transaction costs.

内容的提问来源于stack exchange,提问作者이선아

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:32:41