使用 Foundry 或 Hardhat 部署合約
用 Foundry 或 Hardhat 在 EVM 網路部署無建構參數的小合約:先設定私鑰與鏈 ID 並驗證鏈身分,再用 forge create 廣播交易,核對部署地址、交易哈希與鏈上狀態,並讀取合約方法的傳回值。
選擇網路
請依照目標鏈的整合指南(從支援的鏈進入)建立 network.mjs 並匯出 RPC_URL 與 CHAIN_ID。鏈指南會從 GET /v1/chains 讀取 chain ID 與方法策略,並說明 gas 代幣、是否需要另用可廣播的 RPC,以及各鏈專屬的部署設定。
選擇下方其中一種工具。兩者都會部署同一個不含建構子引數的小型合約。
為部署者提供所選網路的原生 gas 代幣。在本機環境中安全設定 DEPLOYER_PRIVATE_KEY,切勿提交。以下命令會廣播交易並花費 gas。
建立不含建構子引數的 Hello.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Hello {
event Ping(address indexed sender);
function ping() external { emit Ping(msg.sender); }
function hello() external pure returns (string memory) {
return "hello";
}
}Foundry
在已初始化的 Foundry 專案中,將合約放在 src/Hello.sol,並使用下列 foundry.toml:
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc_version = "0.8.24"
evm_version = "paris"
[rpc_endpoints]
target = "${RPC_URL}": "${RPC_URL:?Set RPC_URL}" "${CHAIN_ID:?Set CHAIN_ID}" "${DEPLOYER_PRIVATE_KEY:?Set deployer key}"
test "$(cast chain-id --rpc-url "$RPC_URL")" = "$CHAIN_ID" || exit 1
forge build
forge create src/Hello.sol:Hello --rpc-url target \
--chain "$CHAIN_ID" --private-key "$DEPLOYER_PRIVATE_KEY" --broadcast保留交易雜湊與部署地址。使用 cast receipt "$TX_HASH" --rpc-url "$RPC_URL" 檢查是否納入區塊與狀態,再以 cast call "$CONTRACT_ADDRESS" "hello()(string)" --rpc-url "$RPC_URL" 讀取合約。請從部署輸出設定這兩個變數。
Hardhat 2 與 ethers 6
在獨立的 CommonJS 專案(npm init -y)中,安裝 npm install --save-dev hardhat@2 @nomicfoundation/hardhat-ethers@3 ethers@6。將同一份合約放在 contracts/Hello.sol。將以下內容存為 hardhat.config.cjs:
require('@nomicfoundation/hardhat-ethers');
const { RPC_URL, CHAIN_ID, DEPLOYER_PRIVATE_KEY } = process.env;
if (!RPC_URL || !/^[1-9][0-9]*$/.test(CHAIN_ID ?? '') || !DEPLOYER_PRIVATE_KEY) {
throw new Error('Set RPC_URL, CHAIN_ID and DEPLOYER_PRIVATE_KEY');
}
module.exports = {
solidity: { version: '0.8.24', settings: { evmVersion: 'paris' } },
networks: {
target: { url: RPC_URL, chainId: Number(CHAIN_ID), accounts: [DEPLOYER_PRIVATE_KEY] },
},
};建立 scripts 目錄並存為 scripts/deploy.cjs:
const { ethers } = require('hardhat');
async function main() {
const contract = await ethers.deployContract('Hello');
console.log(contract.deploymentTransaction().hash);
await contract.waitForDeployment();
console.log(await contract.getAddress());
}
main().catch(error => { console.error(error); process.exitCode = 1; });npx hardhat compile
npx hardhat run scripts/deploy.cjs --network target網路的 chainId 會與 RPC 核對。請參閱 Hardhat 2 網路設定與 Foundry 設定(存取日期:2026-10-07)。
讀取事件
將 LOG_ADDRESS 設為部署地址。呼叫 ping() 後,依照目標鏈指南中的事件讀取方式(WebSocket 訂閱或 HTTP 分段輪詢,取決於該鏈在 /v1/chains 的 ws 欄位)讀取 Ping 事件。
最後更新: