跳到內容

訊息簽署

請求使用者在 D9 錢包中對任意訊息進行鏈下簽署,並在伺服器端驗證簽章有效性。訊息簽署不上鏈,也不會產生任何手續費。

前置條件: 已完成快速上手中的 walletRuntime 設定,且已連線錢包帳戶。

向 connector.signMessage 傳入簽署帳戶位址與訊息文字:

import { Effect } from "effect";
import { D9DAppConnector } from "@d9-network/dapp-connector";
import { walletRuntime } from "./wallet";
export async function signTermsAcknowledgement(userAddress: string) {
return walletRuntime.runPromise(
Effect.gen(function* () {
const connector = yield* D9DAppConnector;
return yield* connector.signMessage({
address: userAddress,
message: "I acknowledge and accept the Terms of Service for My D9 DApp.",
});
}),
);
}

回傳欄位如下:

欄位 說明
transport 'papi' | 'walletconnect'
address 執行簽署的 SS58 位址
message 原始訊息文字
signature 十六進位編碼簽章
messageHex 實際參與簽署的位元組內容

若需直接呼叫底層 WalletConnect 通道控制代碼,請先將 UTF-8 文字轉換為十六進位位元組:

import type { D9WalletConnectTransportHandle } from "@d9-network/dapp-connector";
import {
utf8ToHex,
type D9AccountId,
} from "@d9-network/dapp-connector/protocol";
import { walletRuntime } from "./wallet";
export async function requestRawHexSignature(
handle: D9WalletConnectTransportHandle,
accountId: D9AccountId,
rawUtf8String: string,
) {
return walletRuntime.runPromise(
handle.requestMessage({
account: accountId,
message: utf8ToHex(rawUtf8String),
}),
);
}

將 address、messageHex 與 signature 送交後端,並執行以下兩項驗證:

  1. 對包裹為 <Bytes>...</Bytes> 的訊息內容驗證 sr25519 / ed25519 簽章(錢包簽署的是 Substrate 標準包裹後的位元組,而非原始文字)。
  2. 確認對應公鑰依 SS58 前綴 9 編碼後與聲稱的 address 一致。

原始訊息通過兩項驗證;修改任一字元後驗證失敗。