name: midnight-dapp:wallet-integration description: 在设置Lace钱包连接、处理多个用户账户、在测试网和主网之间切换、排查钱包问题或从MetaMask/Web3模式迁移时使用。
钱包集成
将Lace钱包连接到您的Midnight DApp,以实现用户身份验证、账户管理和交易签名。
使用场景
- 首次设置钱包连接
- 处理多个用户账户
- 在测试网和主网之间切换
- 排查钱包连接问题
- 从MetaMask/Web3模式迁移
核心概念
浏览器钱包模式
Lace钱包是一个Chrome扩展,它将window.midnight.mnLace注入到网页中。这类似于MetaMask的window.ethereum,但提供了Midnight特定的API。
连接流程
- 检查可用性 - 验证Lace扩展是否已安装
- 请求授权 - 用户批准DApp访问
- 获取钱包状态 - 检索地址、公钥
- 配置提供者 - 设置索引器和证明服务器连接
地址格式
Midnight使用Bech32m地址(例如,addr_test1qz...),而不是以太坊的十六进制格式(0x…)。
参考文档
| 文档 | 描述 |
|---|---|
| lace-connection.md | 钱包连接生命周期和错误处理 |
| account-management.md | 多账户和地址显示 |
| network-switching.md | 测试网与主网配置 |
| web3-comparison.md | MetaMask到Lace迁移指南 |
示例
| 示例 | 描述 |
|---|---|
| connect-button/ | 基础钱包连接按钮组件 |
| account-switcher/ | 多账户选择UI |
| network-selector/ | 网络选择下拉菜单 |
快速开始
1. 检查钱包可用性
const wallet = window.midnight?.mnLace;
if (!wallet) {
// 显示“安装Lace钱包”提示
throw new Error('Lace钱包未安装');
}
2. 请求授权
const walletAPI = await wallet.enable();
// 用户在Lace中看到批准弹窗
3. 获取钱包状态
const state = await walletAPI.state();
console.log('地址:', state.address);
console.log('代币公钥:', state.coinPublicKey);
4. 获取服务URL
const uris = await wallet.serviceUriConfig();
// { indexerUri, indexerWsUri, proverServerUri }
常见模式
连接状态钩子
function useMidnightWallet() {
const [connected, setConnected] = useState(false);
const [address, setAddress] = useState<string | null>(null);
const [error, setError] = useState<Error | null>(null);
const connect = async () => {
try {
const wallet = window.midnight?.mnLace;
if (!wallet) throw new Error('Lace未安装');
const api = await wallet.enable();
const state = await api.state();
setAddress(state.address);
setConnected(true);
} catch (e) {
setError(e as Error);
}
};
return { connected, address, error, connect };
}
显示地址
function formatAddress(address: string): string {
// Bech32m地址很长 - 为显示而截断
if (address.length <= 20) return address;
return `${address.slice(0, 12)}...${address.slice(-8)}`;
}
相关技能
proof-handling- 钱包连接后的交易签名流程transaction-flows- 通过钱包提交交易error-handling- 钱包错误消息和恢复
相关命令
/dapp-check- 验证钱包提供者配置/dapp-debug wallet- 诊断钱包连接问题