技术选型:以太坊+侧链(Arbitrum L2)+Hardhat+Vue3.0
步骤 1:准备 Vue 和 Hardhat
如果你还没有 Vue 和 Hardhat 项目,先创建它们。
创建 Vue 项目
npm create vue@latest my-vue-dapp
cd my-vue-dapp
npm install
如果你使用 Vue 2:
vue create my-vue-dapp
创建 Hardhat 项目
mkdir hardhat-backend
cd hardhat-backend
npx hardhat
选择 "Create a basic sample project" 并安装依赖:
npm install
步骤 2:编写智能合约
进入 hardhat-backend/contracts
目录,创建 MyContract.sol
:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyContract {
uint public value;
function setValue(uint _value) public {
value = _value;
}
}
编译合约
npx hardhat compile
步骤 3:部署合约
在 hardhat-backend/scripts/deploy.js
添加:
const hre = require("hardhat");
async function main() {
const MyContract = await hre.ethers.getContractFactory("MyContract");
const myContract = await MyContract.deploy();
await myContract.deployed();
console.log("Contract deployed to:", myContract.address);
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
启动本地 Hardhat 节点
npx hardhat node
用 Hardhat 部署到本地
npx hardhat run scripts/deploy.js --network localhost
成功后会输出:
Contract deployed to: 0x123...abc
记住这个合约地址,后面 Vue 需要用它来交互。
步骤 4:在 Vue 中集成 Web3
安装 ethers.js
在 Vue 项目目录运行:
npm install ethers
在 Vue 组件里连接合约
在 src/components/Contract.vue
里写:
<template>
<div>
<h2>智能合约 Demo</h2>
<p>当前值: {{ value }}</p>
<input type="number" v-model="newValue" />
<button @click="setValue">更新值</button>
</div>
</template>
<script>
import { ethers } from "ethers";
export default {
data() {
return {
value: 0,
newValue: 0,
contractAddress: "0x123...abc", // 替换为你的合约地址
contractABI: [
// 你的合约 ABI(在 hardhat-backend/artifacts/contracts/MyContract.json 里)
{
"inputs": [],
"name": "value",
"outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [{ "internalType": "uint256", "name": "_value", "type": "uint256" }],
"name": "setValue",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
],
};
},
methods: {
async loadContract() {
if (!window.ethereum) {
alert("请安装 MetaMask");
return;
}
const provider = new ethers.providers.Web3Provider(window.ethereum);
const contract = new ethers.Contract(this.contractAddress, this.contractABI, provider);
this.value = await contract.value();
},
async setValue() {
if (!window.ethereum) return;
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(this.contractAddress, this.contractABI, signer);
await contract.setValue(this.newValue);
this.value = await contract.value();
}
},
mounted() {
this.loadContract();
}
};
</script>
步骤 5:运行 Vue 项目
在 Vue 目录运行:
npm run dev
打开浏览器,连接 MetaMask,即可交互合约!
总结
✔ Hardhat 负责部署合约,Vue 作为前端进行交互。
✔ Vue 通过 ethers.js
连接 MetaMask 并调用智能合约。
✔ 智能合约部署后,Vue 需要用合约地址和 ABI 进行交互。
这样,你就完成了 Vue + Hardhat 的完整 Web3 dApp 开发!
此外:
如果你的目标是:
- 仅在 Arbitrum L2 读取数据,不需要额外操作。
- 希望 L1 也能读取数据,需要使用 Arbitrum Outbox 或 部署 L1 合约同步数据。
- 确保数据完全存储在 L1,建议直接在 L1 部署智能合约(但成本更高)。