快速开始
了解如何检测、连接和与 Cosmos 链进行交互。
Provider 检测
// 检测 OneKey Cosmos provider
const provider = window.$onekey?.cosmos
if (!provider) {
throw new Error('未检测到 OneKey Cosmos provider')
}
// 检查是否为 OneKey
console.log('Provider:', provider.isOneKey ? 'OneKey' : '未知')连接到链
const chainId = 'cosmoshub-4'
// 启用链 - 返回密钥信息
const key = await provider.enable(chainId)
// 或一次启用多条链
await provider.enable(['cosmoshub-4', 'osmosis-1', 'juno-1'])获取账户信息
const chainId = 'cosmoshub-4'
const key = await provider.getKey(chainId)
console.log({
name: key.name, // 账户名称
algo: key.algo, // 签名算法 (secp256k1)
pubKey: key.pubKey, // 公钥 (Uint8Array)
address: key.address, // 地址 (Uint8Array)
bech32Address: key.bech32Address, // Bech32 格式地址
isNanoLedger: key.isNanoLedger, // 是否为硬件钱包
})添加自定义链
使用 experimentalSuggestChain 添加原生不支持的链:
await provider.experimentalSuggestChain({
chainId: 'my-chain-1',
chainName: 'My Custom Chain',
rpc: 'https://rpc.mychain.io',
rest: 'https://lcd.mychain.io',
bip44: { coinType: 118 },
bech32Config: {
bech32PrefixAccAddr: 'mychain',
bech32PrefixAccPub: 'mychainpub',
bech32PrefixValAddr: 'mychainvaloper',
bech32PrefixValPub: 'mychainvaloperpub',
bech32PrefixConsAddr: 'mychainvalcons',
bech32PrefixConsPub: 'mychainvalconspub',
},
currencies: [{
coinDenom: 'TOKEN',
coinMinimalDenom: 'utoken',
coinDecimals: 6,
}],
feeCurrencies: [{
coinDenom: 'TOKEN',
coinMinimalDenom: 'utoken',
coinDecimals: 6,
gasPriceStep: { low: 0.01, average: 0.025, high: 0.04 },
}],
stakeCurrency: {
coinDenom: 'TOKEN',
coinMinimalDenom: 'utoken',
coinDecimals: 6,
},
})断开连接
await provider.disconnect()与 CosmJS 配合使用
获取离线签名器以配合 CosmJS 使用:
import { SigningStargateClient } from '@cosmjs/stargate'
const chainId = 'cosmoshub-4'
// 自动检测最佳签名器类型
const offlineSigner = await provider.getOfflineSignerAuto(chainId)
// 或使用特定的签名器类型
const aminoSigner = provider.getOfflineSignerOnlyAmino(chainId)
const directSigner = provider.getOfflineSigner(chainId)
// 与 CosmJS 配合使用
const client = await SigningStargateClient.connectWithSigner(
'https://rpc.cosmos.network',
offlineSigner
)
// 发送代币
const result = await client.sendTokens(
senderAddress,
recipientAddress,
[{ denom: 'uatom', amount: '1000000' }],
{ amount: [{ denom: 'uatom', amount: '5000' }], gas: '200000' }
)从 Keplr 迁移
OneKey 的 Cosmos provider 与 Keplr 兼容。只需更改您的 provider 检测方式:
// 之前 (仅 Keplr)
const provider = window.keplr
// 之后 (OneKey 优先,Keplr 作为备选)
const provider = window.$onekey?.cosmos || window.keplrLast updated on