快速开始
1. 准备
- 在桌面版 Chrome 安装 CubWallet 扩展。
- 在钱包里创建或导入一个带私钥的账户(观察账户不能签名)。
- 用 https 或 http://localhost / http://127.0.0.1 打开你的页面。不要用
file://。
2. 检测并连接
把下面这段代码放到页面里。先判断 window.bitshares 是否已经存在,再监听 bitshares#initialized,避免扩展注入完成前就判定“没有钱包”。
function getProvider() {
if (window.bitshares) return Promise.resolve(window.bitshares);
return new Promise((resolve, reject) => {
const onInit = () => {
window.removeEventListener('bitshares#initialized', onInit);
window.bitshares ? resolve(window.bitshares) : reject(new Error('未检测到 CubWallet'));
};
window.addEventListener('bitshares#initialized', onInit, { once: true });
setTimeout(() => {
window.removeEventListener('bitshares#initialized', onInit);
reject(new Error('未检测到 CubWallet。请安装扩展,并用 https 或 http://localhost 打开本页。'));
}, 3000);
});
}
async function connect() {
const bts = await getProvider();
if (!bts.isCubWallet) {
console.warn('检测到 window.bitshares,但不是 CubWallet');
}
const { chainId, network } = await bts.request({ method: 'bts_chainId' });
const accounts = await bts.request({ method: 'bts_requestAccounts' });
// accounts: [{ id: '1.2.xxx', name: 'your-name' }, ...]
return { bts, chainId, network, accounts };
}bts_requestAccounts 会打开钱包的连接确认窗口。用户选择账户并确认后,Promise 才会 resolve。如果该站点在当前网络上已经授权过,且钱包是解锁状态,会直接返回已授权账户,不再弹窗。
3. 发起一笔“只签名、不广播”的转账
金额必须是按资产精度换算后的整数字符串。主网 BTS 的精度是 5,所以 0.00001 BTS 应写成 "1"。不要自己填手续费、引用区块或交易过期时间,这些由钱包补全。
async function signTransfer(bts, from, toAccountId) {
const result = await bts.request({
method: 'bts_signTransaction', // 只签名,不广播
params: {
operations: [
['transfer', {
from,
to: toAccountId, // 例如 '1.2.17',必须是账户 id
amount: { amount: '1', asset_id: '1.3.0' },
memo: 'hello from my dApp', // 可选;明文,由钱包加密
extensions: [],
}],
],
},
});
// result.broadcasted === false
// result.txid、result.signed_transaction
return result;
}调用会打开钱包确认窗口。用户看到的内容来自钱包对交易字节的解码,而不是你传入的 JSON 原文。用户拒绝或关闭窗口时,Promise 会 reject,错误信息为 用户拒绝了请求 或 用户关闭了确认窗口。
只有在用户明确要点击“上链”时,才改用 bts_signAndBroadcast。不要在页面加载时自动发起签名或广播。
4. 监听网络和锁定
bts.on('chainChanged', ({ chainId, network }) => {
// 网络是用户在钱包里切换的,dApp 不能改。
// 授权是按“站点 + 网络”分开存的,切换后请重新调用 bts_accounts。
console.log('network', network, chainId);
});
bts.on('lock', () => {
// 锁定后 bts_accounts 会返回 []
});
bts.on('unlock', async () => {
const accounts = await bts.request({ method: 'bts_accounts' });
});
CubWallet