Skip to Content

Cosmos

使用 OneKey 的 Keplr 兼容 Provider 集成 Cosmos 生态系统链。通过 window.$onekey.cosmos 访问。

OneKey 提供 Keplr 兼容方法。请在目标钱包版本中验证应用需要的方法和链。


快速链接


Provider 检测

// Detect OneKey Cosmos provider const provider = window.$onekey?.cosmos if (!provider) { throw new Error('OneKey Cosmos provider not detected') } // Check if it's OneKey console.log('Provider:', provider.isOneKey ? 'OneKey' : 'Unknown')

快速开始

连接到链

const chainId = 'cosmoshub-4' // Request access to the chain. Read key information separately with getKey(). await provider.enable(chainId) // Or enable multiple chains at once await provider.enable(['cosmoshub-4', 'osmosis-1', 'juno-1'])

获取账户信息

const chainId = 'cosmoshub-4' const key = await provider.getKey(chainId) console.log({ name: key.name, // Account name algo: key.algo, // Signing algorithm (secp256k1) pubKey: key.pubKey, // Public key (Uint8Array) address: key.address, // Raw address bytes bech32Address: key.bech32Address, // Bech32 formatted address isNanoLedger: key.isNanoLedger, // Ledger compatibility flag })

链管理

添加自定义链

使用 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()

消息签名

Sign Amino (传统方式)

用于传统 Amino 编码的交易:

const chainId = 'cosmoshub-4' const signer = 'cosmos1...' const signDoc = { chain_id: chainId, account_number: '0', sequence: '0', fee: { amount: [{ denom: 'uatom', amount: '5000' }], gas: '200000', }, msgs: [{ type: 'cosmos-sdk/MsgSend', value: { from_address: signer, to_address: 'cosmos1...', amount: [{ denom: 'uatom', amount: '1000000' }], }, }], memo: '', } const result = await provider.signAmino(chainId, signer, signDoc) console.log({ signed: result.signed, // Signed document signature: result.signature, // { pub_key, signature } })

Sign Direct (Protobuf)

用于现代 Protobuf 编码的交易:

import { makeSignDoc } from '@cosmjs/proto-signing' const chainId = 'cosmoshub-4' const signer = 'cosmos1...' const signDoc = makeSignDoc( bodyBytes, // Transaction body authInfoBytes, // Auth info with fee chainId, accountNumber ) const result = await provider.signDirect(chainId, signer, signDoc) console.log({ signed: result.signed, signature: result.signature, })

签名任意数据

用于签名任意消息(适用于身份验证):

const chainId = 'cosmoshub-4' const signer = 'cosmos1...' const data = 'Login to MyApp at 2024-01-01T00:00:00Z' const signature = await provider.signArbitrary(chainId, signer, data) // Verify the signature const isValid = await provider.verifyArbitrary(chainId, signer, data, signature) console.log('Signature valid:', isValid)

发送交易

广播交易

const chainId = 'cosmoshub-4' // `txBytes` is the complete signed transaction as a Uint8Array. // Broadcast modes: 'block', 'sync', 'async' const result = await provider.sendTx(chainId, txBytes, 'sync') console.log('TX Hash:', result)

离线签名器

获取用于 CosmJS 的离线签名器:

import { SigningStargateClient } from '@cosmjs/stargate' const chainId = 'cosmoshub-4' // Auto-detect best signer type const offlineSigner = await provider.getOfflineSignerAuto(chainId) // Or use specific signer types const aminoSigner = provider.getOfflineSignerOnlyAmino(chainId) const directSigner = provider.getOfflineSigner(chainId) // Use with CosmJS const client = await SigningStargateClient.connectWithSigner( 'https://rpc.cosmos.network', offlineSigner ) // Send tokens const result = await client.sendTokens( senderAddress, recipientAddress, [{ denom: 'uatom', amount: '1000000' }], { amount: [{ denom: 'uatom', amount: '5000' }], gas: '200000' } )

API 参考

方法

方法说明
enable(chainIds)请求访问指定链;成功时不返回值
disable(chainIds)停用指定链
disconnect()断开与所有链的连接
getKey(chainId)获取指定链的账户密钥信息
signAmino(chainId, signer, signDoc)签署 Amino 编码的交易
signDirect(chainId, signer, signDoc)签署 Protobuf 编码的交易
sendTx(chainId, tx, mode)广播已签名交易
signArbitrary(chainId, signer, data)签署消息
verifyArbitrary(chainId, signer, data, signature)验证签名
experimentalSuggestChain(chainInfo)请求添加自定义链
getOfflineSigner(chainId)获取 Direct 离线签名器
getOfflineSignerOnlyAmino(chainId)获取仅支持 Amino 的离线签名器
getOfflineSignerAuto(chainId)自动选择签名器类型

Key 接口

interface Key { name: string // Human-readable name algo: string // Signing algorithm pubKey: Uint8Array // Public key bytes address: Uint8Array // Address bytes bech32Address: string // Bech32 formatted address isNanoLedger: boolean // Ledger compatibility flag isKeystone: boolean // True if Keystone hardware }

支持的链

链Chain ID钱包可用性
Cosmos Hubcosmoshub-4在目标钱包中验证
Osmosisosmosis-1在目标钱包中验证
Junojuno-1在目标钱包中验证
Stargazestargaze-1在目标钱包中验证
Akashakashnet-2在目标钱包中验证
Secret Networksecret-4在目标钱包中验证
自定义链由链定义通过 experimentalSuggestChain 请求添加;不保证钱包接受

错误处理

try { await provider.enable('cosmoshub-4') } catch (error) { if (error.code === 4001) { console.log('User rejected the request') } else if (error.message.includes('not supported')) { console.log('Chain not supported, try experimentalSuggestChain') } else { console.error('Connection failed:', error) } }

从 Keplr 迁移

OneKey 的 Cosmos provider 兼容 Keplr。只需更改 provider 检测代码:

// Before (Keplr only) const provider = window.keplr // After (OneKey with Keplr fallback) const provider = window.$onekey?.cosmos || window.keplr
最后更新于