快速上手
这里演示如何检测 UKey Wallet Polkadot Provider、启用扩展、读取 Substrate 账户,并配合 Polkadot.js API 发起交易。
ℹ️
UKey Wallet 实现 Polkadot.js 扩展接口,可被兼容 Substrate 扩展的钱包工具和 DApp 识别。
找 Provider
// UKey Wallet 会注册成 Polkadot.js 扩展
const provider = window.$ukey?.polkadot;
// 或者使用标准 web3Enable API
import { web3Enable, web3Accounts } from "@polkadot/extension-dapp";
启用扩展
// 直接调用 UKey Wallet provider
const enabled = await provider.web3Enable("UKey Wallet Demo");
if (enabled) {
const accounts = await provider.web3Accounts();
console.log("当前账户信息:", accounts);
}
使用 Polkadot.js Extension API(优先采用)
import { web3Enable, web3Accounts } from "@polkadot/extension-dapp";
// 打开全部扩展(含 UKey Wallet)
const extensions = await web3Enable("UKey Wallet Demo");
if (extensions.length === 0) {
throw new Error("未找到扩展");
}
// 读取所有账户
const allAccounts = await web3Accounts();
console.log("当前账户信息:", allAccounts);
读取账户
const accounts = await provider.web3Accounts();
accounts.forEach((account) => {
console.log({
address: account.address, // Substrate 账户地址
name: account.name, // 账户显示名
type: account.type, // one of 'sr25519' | 'ed25519' | 'ecdsa'
genesisHash: account.genesisHash, // 可选传入的链创世哈希
});
});
订阅账户变更
const unsubscribe = provider.web3AccountsSubscribe((accounts) => {
console.log("当前账户已切换为:", accounts);
});
// 用完后记得执行 unsubscribe()
与 Polkadot.js API 配合使用
部署
npm install @polkadot/api @polkadot/extension-dapp
连接并签交易
import { ApiPromise, WsProvider } from "@polkadot/api";
import {
web3Enable,
web3FromAddress,
web3Accounts,
} from "@polkadot/extension-dapp";
// 先启用扩展
await web3Enable("UKey Wallet Demo");
// 读取账户
const accounts = await web3Accounts();
const account = accounts[0];
// 建立连接到链
const wsProvider = new WsProvider("wss:/rpc.polkadot.io");
const api = await ApiPromise.create({ provider: wsProvider });
// 读取注入器
const injector = await web3FromAddress(account.address);
// 构建并签署交易
const tx = api.tx.balances.transfer(
recipientAddress,
1000000000000, // equals 1 DOT in planck units
);
// 签名后直接发出
const hash = await tx.signAndSend(account.address, { signer: injector.signer });
console.log("交易哈希值:", hash.toHex());