RPC 驗證
在讀取鏈上狀態或請求簽署前,先確認 RPC 端點連線的是 D9 主網,再產生強型別 PAPI 3 描述檔。
前置條件: 已完成環境設定中的 src/config.ts。
1. 驗證創世雜湊
Section titled “1. 驗證創世雜湊”使用任意 RPC 端點前,先驗證創世雜湊:
import { d9Config } from "./config";
const socket = new WebSocket(d9Config.rpcUrl);
socket.onopen = () => { // 創世雜湊 socket.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "chain_getBlockHash", params: [0] })); // 代幣符號與精度 socket.send(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "system_properties", params: [] }));};
socket.onmessage = ({ data }) => { const response = JSON.parse(String(data)); if (response.id === 1) { if (response.result !== d9Config.expectedGenesisHash) { console.error("Genesis mismatch, rejecting RPC:", response.result); socket.close(); return; } console.log("Verified genesis hash:", response.result); } else if (response.id === 2) { console.log("Chain properties:", response.result); }};驗證: 主控台輸出 Verified genesis hash: 以及你設定的創世雜湊。
每次發起交易簽署請求前,請再次比對創世雜湊。
2. 以同一個最終確認區塊讀取
Section titled “2. 以同一個最終確認區塊讀取”- 呼叫
chain_getFinalizedHead取得最新最終確認區塊雜湊。 - 將該雜湊作為
at參數傳入所有相互關聯的state_getStorage與state_call請求。
若未固定區塊,報價、儲備量與手續費估算可能來自不同區塊,導致狀態不一致。
3. 產生 PAPI 3 描述檔
Section titled “3. 產生 PAPI 3 描述檔”-
在 Shell 中匯出已驗證的 RPC 位址(PAPI CLI 不會自動讀取 Vite 的
.env檔案):終端機視窗 export VITE_D9_RPC_URL=wss://rpc-hermes.d9network.com # 第 1 步驗證過的位址 -
在 DApp 專案目錄下執行:
終端機視窗 npm install --save-exact polkadot-api@3.3.0 @d9-network/dapp-connector@0.2.0 effect@4.0.5: "${VITE_D9_RPC_URL:?Export the verified VITE_D9_RPC_URL first}"npx papi add d9 -w "$VITE_D9_RPC_URL"npx papi generate -
將產生的
.papi設定與中繼資料提交至版本控制。 -
每次完成審核的 Runtime 升級後,請重新執行
npx papi generate,並確保程式碼產生與執行時期使用相同版本的polkadot-api。
驗證: 本機產生 @polkadot-api/descriptors 套件,並正常匯出 d9 與 getMetadata。
| 錯誤訊息 | 處理方式 |
|---|---|
Genesis mismatch, rejecting RPC |
改用主網端點中的其他 RPC,並核對 VITE_D9_GENESIS_HASH。 |
Export the verified VITE_D9_RPC_URL first |
在同一個 Shell 工作階段中先執行第 3.1 步的 export 指令。 |
