以太坊生態應用案例實作完整指南:DeFi、質押、借貸與錢包交互

本文提供以太坊生態系統中最常見應用場景的完整實作範例,涵蓋去中心化金融操作、質押服務、智慧合約部署、錢包管理和跨鏈交互等多個維度。所有範例均基於 2026 年第一季度最新的協議版本,並包含可直接運行的程式碼和詳細的操作流程說明。

以太坊生態應用案例實作完整指南:DeFi、質押、借貸與錢包交互

概述

本文提供以太坊生態系統中最常見應用場景的完整實作範例,涵蓋去中心化金融操作、質押服務、智慧合約部署、錢包管理和跨鏈交互等多個維度。所有範例均基於 2026 年第一季度最新的協議版本,並包含可直接運行的程式碼和詳細的操作流程說明。

基礎設施準備

RPC 節點配置

在開始以太坊開發之前,需要配置可靠的 RPC 節點連接。以下是主流 RPC 服務提供商的比較和配置範例:

const { ethers } = require('ethers');

// 主流 RPC 服務商配置
const RPC_CONFIG = {
  // Alchemy
  alchemy: {
    url: 'https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY',
    name: 'Alchemy',
    freeTier: '300M compute units/month',
    priority: 'high'
  },
  // Infura
  infura: {
    url: 'https://mainnet.infura.io/v3/YOUR_PROJECT_ID',
    name: 'Infura',
    freeTier: '100K requests/day',
    priority: 'medium'
  },
  // QuickNode
  quicknode: {
    url: 'https://example-endpoint.quiknode.pro/YOUR_TOKEN/',
    name: 'QuickNode',
    freeTier: '50K requests/day',
    priority: 'high'
  },
  // Public RPC (僅用於測試)
  public: {
    url: 'https://eth.public-rpc.com',
    name: 'Public RPC',
    freeTier: 'Unlimited',
    priority: 'low'
  }
};

// 建立 Provider 實例
function createProvider(config = 'alchemy') {
  const { url } = RPC_CONFIG[config];
  return new ethers.JsonRpcProvider(url);
}

// 測試連接
async function testConnection(provider) {
  try {
    const network = await provider.getNetwork();
    const blockNumber = await provider.getBlockNumber();
    const feeData = await provider.getFeeData();
    
    console.log('連接成功!');
    console.log('網路:', network.name);
    console.log('區塊高度:', blockNumber);
    console.log('Gas Price:', ethers.formatUnits(feeData.gasPrice, 'gwei'), 'Gwei');
    
    return true;
  } catch (error) {
    console.error('連接失敗:', error.message);
    return false;
  }
}

// 批量請求優化
class BatchProvider {
  constructor(provider) {
    this.provider = provider;
    this.queue = [];
    this.processing = false;
  }

  async getBalance(address) {
    return new Promise((resolve, reject) => {
      this.queue.push({ 
        method: 'eth_getBalance', 
        params: [address, 'latest'],
        resolve, 
        reject 
      });
      this.processQueue();
    });
  }

  async getCode(address) {
    return new Promise((resolve, reject) => {
      this.queue.push({ 
        method: 'eth_getCode', 
        params: [address, 'latest'],
        resolve, 
        reject 
      });
      this.processQueue();
    });
  }

  async processQueue() {
    if (this.processing || this.queue.length === 0) return;
    this.processing = true;
    
    const batch = this.queue.splice(0, 100); // 每次處理100個請求
    const requests = batch.map(item => ({
      jsonrpc: '2.0',
      id: batch.indexOf(item) + 1,
      method: item.method,
      params: item.params
    }));
    
    try {
      const response = await fetch(this.provider.url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(requests)
      });
      
      const results = await response.json();
      results.forEach((result, index) => {
        if (result.error) {
          batch[index].reject(new Error(result.error.message));
        } else {
          batch[index].resolve(result.result);
        }
      });
    } catch (error) {
      batch.forEach(item => item.reject(error));
    }
    
    this.processing = false;
    if (this.queue.length > 0) this.processQueue();
  }
}

錢包管理與安全性

const { ethers } = require('ethers');
const { Wallet } = require('ethers');
const crypto = require('crypto');

// 錢包創建
function createWallet() {
  const wallet = Wallet.createRandom();
  return {
    address: wallet.address,
    privateKey: wallet.privateKey,
    mnemonic: wallet.mnemonic.phrase,
    publicKey: wallet.publicKey
  };
}

// 從助記詞恢復錢包
function fromMnemonic(mnemonic) {
  const wallet = Wallet.fromPhrase(mnemonic);
  return {
    address: wallet.address,
    privateKey: wallet.privateKey
  };
}

// 從私鑰創建錢包
function fromPrivateKey(privateKey) {
  const wallet = new Wallet(privateKey);
  return wallet;
}

// 硬體錢包支持 (Ledger/Trezor)
class HardwareWalletManager {
  constructor() {
    this.wallets = new Map();
  }

  // 連接 Ledger 設備
  async connectLedger(transport) {
    const { ethers } = require('ethers');
    const { LedgerSigner } = require('@anders-t/ethers-ledger');
    
    const ledger = new LedgerSigner(transport);
    const accounts = await ledger.getAccounts();
    
    return {
      signer: ledger,
      addresses: accounts,
      type: 'ledger'
    };
  }

  // 連接 Trezor 設備
  async connectTrezor(transport) {
    const { TrezorSigner } = require('@trezor/ethers-provider');
    
    const trezor = new TrezorSigner(transport);
    const accounts = await trezor.getAccounts();
    
    return {
      signer: trezor,
      addresses: accounts,
      type: 'trezor'
    };
  }

  // 多簽名錢包創建
  async createMultiSigWallet(owners, requiredConfirmations) {
    const { MultiSigWallet } = require('./abis/MultiSigWallet.json');
    
    // 這需要部署新的多簽名合約
    // 詳細實現參考 Gnosis Safe SDK
    console.log('多簽名錢包需要使用 Gnosis Safe SDK');
  }
}

// 交易安全性
class TransactionManager {
  constructor(wallet, provider) {
    this.wallet = wallet;
    this.provider = provider;
    this.nonce = null;
  }

  // 估計 Gas 費用
  async estimateGas(to, value, data = '0x') {
    const feeData = await this.provider.getFeeData();
    
    const estimate = await this.provider.estimateGas({
      to,
      value,
      data
    });
    
    return {
      gasLimit: estimate,
      maxFeePerGas: feeData.maxFeePerGas,
      maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
      estimatedCost: estimate * feeData.maxFeePerGas
    };
  }

  // 構建交易
  async buildTransaction(to, value, options = {}) {
    const feeData = await this.provider.getFeeData();
    
    const nonce = this.nonce ?? await this.provider.getTransactionCount(this.wallet.address);
    
    const tx = {
      to,
      value,
      nonce,
      gasLimit: options.gasLimit || await this.provider.estimateGas({
        to, value, data: options.data || '0x'
      }),
      maxFeePerGas: options.maxFeePerGas || feeData.maxFeePerGas,
      maxPriorityFeePerGas: options.maxPriorityFeePerGas || feeData.maxPriorityFeePerGas,
      chainId: (await this.provider.getNetwork()).chainId
    };
    
    return tx;
  }

  // 簽名並發送交易
  async sendTransaction(to, value, options = {}) {
    const tx = await this.buildTransaction(to, value, options);
    
    const signedTx = await this.wallet.signTransaction(tx);
    const response = await this.provider.broadcastTransaction(signedTx);
    
    // 更新 nonce
    this.nonce = tx.nonce + 1;
    
    return {
      hash: response.hash,
      tx,
      signedTx
    };
  }

  // 批量交易
  async sendBatchTransactions(transactions) {
    const results = [];
    
    for (const tx of transactions) {
      try {
        const result = await this.sendTransaction(tx.to, tx.value, tx.options);
        results.push({ success: true, ...result });
      } catch (error) {
        results.push({ success: false, error: error.message });
      }
    }
    
    return results;
  }
}

DeFi 實作:流動性提供與交易

Uniswap V3 流動性管理

const { ethers } = require('ethers');
const { BigNumber } = ethers;

// Uniswap V3 完整交互類別
class UniswapV3Manager {
  constructor(wallet) {
    this.wallet = wallet;
    this.provider = wallet.provider;
    this.poolFactory = '0x1F98431c8aD98523631AE4a59f267346ea31F984';
    this.swapRouter = '0xE592427A0AEce92De3Edee1F18E0157C05861564';
    this.positionManager = '0xC36442b4a4522E641399a4a9D693d2c4fB5a7dB4';
  }

  // 獲取池地址
  getPoolAddress(token0, token1, fee) {
    // Uniswap V3 池地址可通過工廠合約計算
    // 這裡使用 Create2 方法計算
    const salt = ethers.solidityPacked(
      ['address', 'address', 'uint24'],
      [token0 < token1 ? token0 : token1, token0 < token1 ? token1 : token0, fee]
    );
    
    return ethers.getCreate2Address(
      this.poolFactory,
      salt,
      '0xe34f199b19b2b4f47f68442619d555a7369615a4c3c2261b31b85d8bbcdd2a3d9'
    );
  }

  // 獲取代幣餘額
  async getTokenBalance(tokenAddress, owner) {
    const token = new ethers.Contract(
      tokenAddress,
      ['function balanceOf(address owner) view returns (uint256)'],
      this.provider
    );
    return await token.balanceOf(owner);
  }

  // 獲取報價
  async getQuote(tokenIn, tokenOut, amountIn, fee = 3000) {
    const quoter = new ethers.Contract(
      '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6',
      ['function quoteExactInputSingle((address,address,uint24,address,uint256,uint256,int256,uint160)) view returns (uint256,uint160,uint32,uint256)'],
      this.provider
    );
    
    const params = {
      tokenIn,
      tokenOut,
      fee,
      recipient: ethers.ZeroAddress,
      deadline: Math.floor(Date.now() / 1000) + 300,
      amountIn,
      amountOutMinimum: 0,
      sqrtPriceLimitX96: 0
    };
    
    return await quoter.quoteExactInputSingle(params);
  }

  // 執行交換
  async exactInputSingle(tokenIn, tokenOut, amountIn, amountOutMinimum, fee = 3000) {
    const router = new ethers.Contract(
      this.swapRouter,
      [
        'function exactInputSingle((address,address,uint24,address,uint256,uint256,uint160)) returns (uint256)'
      ],
      this.wallet
    );
    
    // 首先授權代幣
    const token = new ethers.Contract(
      tokenIn,
      ['function approve(address spender, uint256) returns (bool)'],
      this.wallet
    );
    
    const approveTx = await token.approve(this.swapRouter, amountIn);
    await approveTx.wait();
    
    // 執行交換
    const params = {
      tokenIn,
      tokenOut,
      fee,
      recipient: this.wallet.address,
      deadline: Math.floor(Date.now() / 1000) + 300,
      amountIn,
      amountOutMinimum
    };
    
    const tx = await router.exactInputSingle(params);
    const receipt = await tx.wait();
    
    return receipt;
  }

  // 添加流動性
  async addLiquidity(token0, token1, fee, tickLower, tickUpper, amount0Desired, amount1Desired, amount0Min, amount1Min) {
    const positionManager = new ethers.Contract(
      this.positionManager,
      [
        'function mint((address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline)) returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)'
      ],
      this.wallet
    );
    
    // 授權代幣
    const token0Contract = new ethers.Contract(token0, ['function approve(address, uint256)'], this.wallet);
    const token1Contract = new ethers.Contract(token1, ['function approve(address, uint256)'], this.wallet);
    
    await token0Contract.approve(this.positionManager, amount0Desired);
    await token1Contract.approve(this.positionManager, amount1Desired);
    
    const params = {
      token0,
      token1,
      fee,
      tickLower,
      tickUpper,
      amount0Desired,
      amount1Desired,
      amount0Min,
      amount1Min,
      recipient: this.wallet.address,
      deadline: Math.floor(Date.now() / 1000) + 600
    };
    
    const tx = await positionManager.mint(params);
    const receipt = await tx.wait();
    
    return receipt;
  }

  // 計算無常損失
  calculateImpermanentLoss(priceInitial, priceFinal) {
    const ratio = priceFinal / priceInitial;
    const il = 2 * Math.sqrt(ratio) / (1 + ratio) - 1;
    return il * 100; // 轉換為百分比
  }

  // 範例:計算 LP 收益
  calculateLPReturns(initialToken0, initialToken1, currentToken0, currentToken1, feeEarned) {
    const initialValue = initialToken0 * 3000 + initialToken1; // 假設 ETH 價格為 3000
    const currentValue = currentToken0 * 3000 + currentToken1;
    
    const valueChange = (currentValue + feeEarned - initialValue) / initialValue * 100;
    const il = this.calculateImpermanentLoss(
      initialToken0 / initialToken1,
      currentToken0 / currentToken1
    );
    
    return {
      totalReturn: valueChange,
      impermanentLoss: il,
      netReturn: valueChange + il,
      feeEarnedUSD: feeEarned * 3000
    };
  }
}

Aave V3 借貸操作

// Aave V3 借貸管理類別
class AaveV3Manager {
  constructor(wallet) {
    this.wallet = wallet;
    this.provider = wallet.provider;
    this.poolAddress = '0x87870Bca3F3f6335e32cdC4d59c9d6F3F0dDb9b8';
    this.pool = null;
  }

  async initialize() {
    const PoolABI = require('./abis/AaveV3Pool.json');
    this.pool = new ethers.Contract(this.poolAddress, PoolABI, this.wallet);
  }

  // 獲取帳戶健康狀態
  async getUserAccountData(userAddress) {
    const data = await this.pool.getUserAccountData(userAddress);
    
    return {
      totalCollateralBase: data.totalCollateralBase.toString(),
      totalDebtBase: data.totalDebtBase.toString(),
      availableBorrowsBase: data.availableBorrowsBase.toString(),
      currentLiquidationThreshold: data.currentLiquidationThreshold.toString(),
      ltv: data.ltv.toString(),
      healthFactor: ethers.formatUnits(data.healthFactor, 18)
    };
  }

  // 供應資產
  async supply(asset, amount, onBehalfOf = null) {
    const recipient = onBehalfOf || this.wallet.address;
    
    // 授權代幣
    const token = new ethers.Contract(
      asset,
      ['function approve(address spender, uint256) returns (bool)'],
      this.wallet
    );
    
    const approveTx = await token.approve(this.poolAddress, amount);
    await approveTx.wait();
    
    // 供應
    const tx = await this.pool.supply(asset, amount, recipient, 0);
    const receipt = await tx.wait();
    
    return receipt;
  }

  // 借款
  async borrow(asset, amount, interestRateMode = 2, referralCode = 0) {
    // interestRateMode: 1 = 穩定利率, 2 = 浮動利率
    
    const tx = await this.pool.borrow(
      asset,
      amount,
      interestRateMode,
      referralCode,
      this.wallet.address
    );
    
    return await tx.wait();
  }

  // 還款
  async repay(asset, amount, interestRateMode = 2, onBehalfOf = null) {
    const recipient = onBehalfOf || this.wallet.address;
    
    // 授權代幣
    const token = new ethers.Contract(
      asset,
      ['function approve(address spender, uint256) returns (bool)'],
      this.wallet
    );
    
    const approveTx = await token.approve(this.poolAddress, amount);
    await approveTx.wait();
    
    const tx = await this.pool.repay(asset, amount, interestRateMode, recipient);
    return await tx.wait();
  }

  // 提取
  async withdraw(asset, amount, to = null) {
    const recipient = to || this.wallet.address;
    
    const tx = await this.pool.withdraw(asset, amount, recipient);
    return await tx.wait();
  }

  // 獲取儲備數據
  async getReserveData(asset) {
    return await this.pool.getReserveData(asset);
  }

  // 清算
  async liquidate(user, collateralAsset, debtAsset, debtToCover) {
    const tx = await this.pool.liquidationCall(
      collateralAsset,
      debtAsset,
      user,
      debtToCover,
      false
    );
    
    return await tx.wait();
  }

  // 計算清算潛力
  async calculateLiquidationAmount(user, collateralAsset, debtAsset) {
    const userData = await this.getUserAccountData(user);
    const healthFactor = parseFloat(userData.healthFactor);
    
    if (healthFactor > 1) {
      return { canLiquidate: false, reason: '健康因子 > 1,無法清算' };
    }
    
    const reserveData = await this.getReserveData(debtAsset);
    const liquidationBonus = reserveData.liquidationBonus.toString();
    
    return {
      canLiquidate: true,
      healthFactor,
      maxLiquidationBonus: liquidationBonus,
      maxDebtToCover: userData.totalDebtBase
    };
  }

  // 閃電貸
  async executeFlashLoan(assets, amounts, modes, params) {
    const receiver = this.wallet.address; // 或者專門的閃電貸接收合約
    
    const tx = await this.pool.flashLoan(
      receiver,
      assets,
      amounts,
      modes,
      this.wallet.address,
      params,
      0
    );
    
    return await tx.wait();
  }

  // 槓桿策略範例
  async leverageStrategy(supplyAsset, borrowAsset, supplyAmount, targetLeverage = 2) {
    // 供應初始資產
    await this.supply(supplyAsset, supplyAmount);
    
    // 計算可借款額度
    const userData = await this.getUserAccountData(this.wallet.address);
    const borrowPower = userData.availableBorrowsBase;
    
    // 計算目標借款金額
    const targetBorrow = supplyAmount * (targetLeverage - 1);
    const actualBorrow = Math.min(targetBorrow, parseFloat(borrowPower));
    
    // 借款
    await this.borrow(borrowAsset, actualBorrow);
    
    // 循環供應借款(簡化版本)
    await this.supply(borrowAsset, actualBorrow);
    
    return {
      initialSupply: supplyAmount,
      totalBorrow: actualBorrow,
      totalExposure: supplyAmount + actualBorrow,
      leverageRatio: (supplyAmount + actualBorrow) / supplyAmount
    };
  }
}

質押操作實作

直接質押與質押池

// 以太坊質押管理類別
class StakingManager {
  constructor(wallet) {
    this.wallet = wallet;
    this.provider = wallet.provider;
    this.depositContract = '0x00000000219ab540356cBB839Cbe05303d7705Fa';
  }

  // 進行質押(需要 32 ETH)
  async stake(amount = 32000000000000000000n) {
    if (amount < 32000000000000000000n) {
      throw new Error('質押金額需要至少 32 ETH');
    }
    
    const tx = {
      to: this.depositContract,
      value: amount,
      data: this.getDepositData(this.wallet.address, this.wallet.address)
    };
    
    const response = await this.wallet.sendTransaction(tx);
    return await response.wait();
  }

  // 生成質押存款數據
  getDepositData(pubkey, withdrawalCredentials) {
    const { ethers } = require('ethers');
    
    // 打包存款數據
    const depositData = ethers.solidityPacked(
      ['bytes', 'bytes32', 'bytes32', 'bytes', 'bytes'],
      [
        // amount (64 bytes, converted to little-endian)
        ethers.zeroPadValue(ethers.toBeHex(32000000000n), 64),
        // pubkey (48 bytes)
        pubkey,
        // withdrawal credentials (32 bytes)
        withdrawalCredentials,
        // signature (96 bytes) - 預設為 0
        ethers.zeroPadValue('0x', 96),
        // deposit_data_root (32 bytes)
        '0x' + '0'.repeat(64)
      ]
    );
    
    return depositData;
  }

  // 驗證質押狀態(需要連接到Beacon Chain API)
  async getValidatorStatus(validatorPubkey) {
    const response = await fetch('https://mainnet Beacon Chain API');
    // 調用 Beacon Chain API 獲取驗證者狀態
    const data = await fetch(`https://Beacon Chain API/eth/v1/validator/${validatorPubkey}/status`);
    return await data.json();
  }

  // 質押收益計算
  async calculateStakingRewards(stakedAmount, days) {
    const provider = this.provider;
    
    // 獲取當前年化收益率(估算)
    const avgAPR = 0.038; // 3.8% APR
    const dailyRate = avgAPR / 365;
    
    const dailyRewards = stakedAmount * dailyRate;
    const totalRewards = dailyRewards * days;
    
    // 估算區塊獎勵(假設每天產出約 500 個區塊)
    const blocksPerDay = 225; // 平均 12 秒一個區塊
    const avgBlockReward = dailyRewards / BigInt(blocksPerDay);
    
    return {
      stakedAmount: ethers.formatEther(stakedAmount),
      dailyRewards: ethers.formatEther(dailyRewards),
      annualRewards: ethers.formatEther(dailyRewards * 365n),
      apr: (avgAPR * 100).toFixed(2) + '%',
      apy: ((Math.pow(1 + avgAPR / 12, 12) - 1) * 100).toFixed(2) + '%'
    };
  }
}

// 質押池管理 (Lido)
class LidoStakeManager {
  constructor(wallet) {
    this.wallet = wallet;
    this.provider = wallet.provider;
    this.lidoContract = '0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84';
    this.stETH = '0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84';
  }

  // 質押到 Lido
  async stake(amount) {
    const lido = new ethers.Contract(
      this.lidoContract,
      ['function submit(address referral) payable'],
      this.wallet
    );
    
    const tx = await this.lido.submit(this.wallet.address, {
      value: amount
    });
    
    return await tx.wait();
  }

  // 獲取 stETH 餘額
  async getStETHBalance(address) {
    const token = new ethers.Contract(
      this.stETH,
      ['function balanceOf(address) view returns (uint256)'],
      this.provider
    );
    
    return await token.balanceOf(address);
  }

  // 獲取質押獎勵
  async getStakingRewards(address) {
    const lido = new ethers.Contract(
      this.lidoContract,
      [
        'function balanceOf(address) view returns (uint256)',
        'function getTotalShares() view returns (uint256)',
        'function getTotalPooledEther() view returns (uint256)'
      ],
      this.provider
    );
    
    const shares = await lido.balanceOf(address);
    const totalShares = await lido.getTotalShares();
    const totalEther = await lido.getTotalPooledEther();
    
    // 計算 stETH 數量
    const stEthBalance = shares * totalEther / totalShares;
    
    return {
      shares: shares.toString(),
      stETH: ethers.formatEther(stEthBalance),
      sharesToETH: (totalEther / totalShares).toString()
    };
  }

  // 解除質押(需要等待期)
  async requestWithdrawal(amount) {
    const lido = new ethers.Contract(
      this.lidoContract,
      ['function requestWithdrawals(uint256[] amounts, address owner) returns (uint256[] requestIds)'],
      this.wallet
    );
    
    const amountInShares = await this.convertToShares(amount);
    const tx = await lido.requestWithdrawals([amountInShares], this.wallet.address);
    const receipt = await tx.wait();
    
    // 解析 requestId
    const requestId = receipt.logs[0].args.requestId;
    
    return {
      requestId,
      amount: ethers.formatEther(amount),
      // 預計解鎖時間(通常 1-3 天)
      estimatedUnlockTime: Date.now() + 2 * 24 * 60 * 60 * 1000
    };
  }

  async convertToShares(etherAmount) {
    const lido = new ethers.Contract(
      this.lidoContract,
      ['function getSharesByPooledEth(uint256) view returns (uint256)'],
      this.provider
    );
    
    return await lido.getSharesByPooledEth(etherAmount);
  }
}

智慧合約部署

部署流程與工具

const { ethers } = require('ethers');
const { Wallet, ContractFactory } = ethers;

// 編譯後的合約 ABI 和 Bytecode
const contractArtifacts = require('./artifacts/contracts/MyToken.json');

class ContractDeployer {
  constructor(wallet) {
    this.wallet = wallet;
    this.provider = wallet.provider;
  }

  // 部署 ERC-20 代幣
  async deployToken(name, symbol, totalSupply) {
    const factory = new ContractFactory(
      contractArtifacts.abi,
      contractArtifacts.bytecode,
      this.wallet
    );
    
    const contract = await factory.deploy(
      name,
      symbol,
      ethers.parseEther(totalSupply.toString())
    );
    
    const receipt = await contract.deploymentTransaction().wait();
    
    return {
      address: receipt.contractAddress,
      transactionHash: receipt.hash,
      deployer: this.wallet.address
    };
  }

  // 部署可升級合約(使用代理模式)
  async deployUpgradeable(implementationBytecode, proxyBytecode, initializationData) {
    // 部署實現合約
    const implementationFactory = new ContractFactory(
      implementationArtifacts.abi,
      implementationArtifacts.bytecode,
      this.wallet
    );
    
    const implementation = await implementationFactory.deploy();
    await implementation.deploymentTransaction().wait();
    
    // 部署代理合約
    const proxyFactory = new ContractFactory(
      proxyArtifacts.abi,
      proxyArtifacts.bytecode,
      this.wallet
    );
    
    const proxy = await proxyFactory.deploy(
      implementation.address,
      initializationData
    );
    
    return {
      implementation: implementation.address,
      proxy: proxy.address
    };
  }

  // 部署工廠合約(批量創建)
  async deployFactory(factoryBytecode, factoryAbi) {
    const factory = new ContractFactory(factoryAbi, factoryBytecode, this.wallet);
    const contract = await factory.deploy();
    await contract.deploymentTransaction().wait();
    
    return contract.address;
  }

  // 估算部署 Gas
  async estimateGas(artifact, constructorArgs = []) {
    const factory = new ContractFactory(
      artifact.abi,
      artifact.bytecode,
      this.wallet
    );
    
    // 獲取部署數據
    const deployData = factory.getDeployTransaction(...constructorArgs);
    
    // 估算 Gas
    return await this.provider.estimateGas(deployData);
  }

  // 驗證合約
  async verifyContract(address, constructorArgs) {
    // 使用 Etherscan API 驗證
    const apiKey = process.env.ETHERSCAN_API_KEY;
    const response = await fetch(`https://api.etherscan.io/api?module=contract&action=verifysourcecode`, {
      method: 'POST',
      body: JSON.stringify({
        apikey: apiKey,
        sourceCode: contractSourceCode,
        contractAddress: address,
        compilerVersion: 'v0.8.19+commit.7dd6d404',
        constructorArguments: constructorArgs
      })
    });
    
    return await response.json();
  }
}

// 合約交互範例
class ContractInteractor {
  constructor(contractAddress, abi, wallet) {
    this.contract = new ethers.Contract(contractAddress, abi, wallet);
    this.wallet = wallet;
  }

  // 讀取狀態變數
  async read(methodName, ...args) {
    return await this.contract[methodName](...args);
  }

  // 寫入狀態
  async write(methodName, ...args) {
    const tx = await this.contract[methodName](...args);
    return await tx.wait();
  }

  // 監控事件
  async watchEvents(eventName, callback) {
    this.contract.on(eventName, (...args) => {
      const event = args[args.length - 1];
      callback({
        blockNumber: event.blockNumber,
        transactionHash: event.transactionHash,
        args: args.slice(0, -1)
      });
    });
  }

  // 估算函數 Gas
  async estimateGas(methodName, ...args) {
    return await this.contract[methodName].estimateGas(...args);
  }
}

結論

本文提供了以太坊生態系統中最常見應用場景的完整實作範例,涵蓋基礎設施配置、DeFi 協議交互、質押操作和智慧合約部署等多個維度。這些程式碼範例可直接應用於實際開發專案,開發者可以根據具體需求進行調整和擴展。

在實際應用中,請始終注意以下安全要點:私鑰的安全存儲、交易的 Gas 優化、智慧合約的安全審計,以及正確處理異常情況。隨著以太坊生態系統的持續發展,建議開發者定期關注官方文檔和社群動態,以獲取最新的技術更新和最佳實踐。

延伸閱讀與來源

這篇文章對您有幫助嗎?

評論

發表評論

注意:由於這是靜態網站,您的評論將儲存在本地瀏覽器中,不會公開顯示。

目前尚無評論,成為第一個發表評論的人吧!