Skip to Content
dApp 接入

快速开始

读取密钥信息或请求签名前,先启用目标链。使用该链的账户编号、sequence、手续费和 RPC 端点;运行签名示例前,请替换其中的占位值。

了解如何检测、连接和与 Cosmos 链进行交互。


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

与 CosmJS 配合使用

获取离线签名器以配合 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' } )

从 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
最后更新于