跳转到内容

消息签名

请求用户在 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 一致。

原始消息通过两项校验;改动任意一个字符后校验失败。