Skip to Content

Cardano

使用 OneKey 的 CIP-30 兼容 Provider 集成 Cardano 区块链。通过 window.cardano.onekey 或 window.cardano.nami 访问。

OneKey 通过 CIP-30(Cardano dApp Connector)提供本文列出的操作,并提供 Nami 钱包兼容接口。


快速链接


Provider 检测

// OneKey provides both onekey and nami interfaces const onekey = window.cardano?.onekey const nami = window.cardano?.nami // Check availability if (!onekey) { throw new Error('OneKey Cardano provider not detected') } // Get wallet info console.log('Name:', onekey.name) // 'OneKey' console.log('API Version:', onekey.apiVersion) // '0.1.0' console.log('Icon:', onekey.icon)

快速开始

启用钱包

// Request wallet access const api = await window.cardano.onekey.enable() // Now you can use the full API const networkId = await api.getNetworkId() console.log('Network:', networkId === 1 ? 'Mainnet' : 'Testnet')

检查是否已启用

const isEnabled = await window.cardano.onekey.isEnabled() if (isEnabled) { const api = await window.cardano.onekey.enable() // Use API... }

账户信息

获取网络 ID

const api = await window.cardano.onekey.enable() const networkId = await api.getNetworkId() // 0 = Testnet, 1 = Mainnet console.log('Network:', networkId)

获取余额

const balance = await api.getBalance() // Returns CBOR-encoded value (hex string) console.log('Balance (CBOR):', balance) // Decode using cardano-serialization-lib import { Value, BigNum } from '@emurgo/cardano-serialization-lib-browser' const value = Value.from_bytes(Buffer.from(balance, 'hex')) const lovelace = value.coin().to_str() console.log('Balance in lovelace:', lovelace) // Keep the exact integer string.

获取地址

// Get used addresses (addresses with transaction history) const usedAddresses = await api.getUsedAddresses() console.log('Used addresses:', usedAddresses) // Get unused addresses (fresh addresses) const unusedAddresses = await api.getUnusedAddresses() console.log('Unused addresses:', unusedAddresses) // Get change address const changeAddress = await api.getChangeAddress() console.log('Change address:', changeAddress) // Get reward/staking addresses const rewardAddresses = await api.getRewardAddresses() console.log('Reward addresses:', rewardAddresses)

获取 UTxOs

// Get all UTxOs const utxos = await api.getUtxos() console.log('UTxOs:', utxos) // Get UTxOs with minimum amount const utxosWithAmount = await api.getUtxos( Buffer.from(Value.new(BigNum.from_str('1000000')).to_bytes()).toString('hex') // CBOR-encoded Value for 1 ADA; import Value and BigNum from the serialization SDK. ) // With pagination const paginatedUtxos = await api.getUtxos(undefined, { page: 0, limit: 10, })

交易

签名交易

// transaction should be CBOR-encoded hex string const witnessSetCbor = await api.signTx(transactionCbor, partialSign) // partialSign: boolean // - false: reject if the wallet cannot provide every required signature // - true: return the signatures the wallet can provide console.log('Witness set:', witnessSetCbor)

提交交易

// Submit signed transaction const txHash = await api.submitTx(signedTransactionCbor) console.log('Transaction hash:', txHash)

构建、签名并提交

signTx 返回 witness set,不是完整的已签名交易。使用 Cardano 交易库构建未签名交易,将返回的 witness 与原有 witness set 合并,再提交合并后的完整交易。

// `unsignedTransactionCbor` is a complete transaction built with current // protocol parameters, selected inputs, outputs, fees, and change. const witnessSetCbor = await api.signTx(unsignedTransactionCbor, false) // Merge witnessSetCbor into the original transaction using your Cardano SDK. // Preserve existing witnesses, scripts, datums, redeemers, and auxiliary data. // Submit the serialized complete transaction, never witnessSetCbor alone. const txHash = await api.submitTx(completeSignedTransactionCbor)

如果应用尚未实现交易构建和 witness 合并,可使用下方 Lucid 或 Mesh 流程。SDK 示例与版本有关,请以所安装版本的文档为准。


数据签名

签名数据 (CIP-8)

签名任意数据用于身份验证:

const api = await window.cardano.onekey.enable() const addresses = await api.getUsedAddresses() const address = addresses[0] // Message to sign const payload = Buffer.from('Hello Cardano!').toString('hex') const signature = await api.signData(address, payload) console.log({ signature: signature.signature, // COSE_Sign1 signature key: signature.key, // COSE_Key public key })

验证签名

import { COSESign1, COSEKey } from '@emurgo/cardano-message-signing-browser' const coseSign1 = COSESign1.from_bytes( Buffer.from(signature.signature, 'hex') ) const coseKey = COSEKey.from_bytes( Buffer.from(signature.key, 'hex') ) // Get the signed payload const signedPayload = coseSign1.payload() // Verify signature // Parsing COSE is not verification. Use a CIP-8 verifier to check the // protected headers, signing structure, payload, signature, and address binding.

事件处理

监听账户变化

const api = await window.cardano.onekey.enable() // Nami-compatible event API api.experimental.on('accountChange', (addresses) => { console.log('Account changed:', addresses) })

API 参考

钱包接口 (CIP-30)

属性/方法说明
name钱包名称 (‘OneKey’)
icon钱包图标 URL
apiVersionAPI 版本
isEnabled()检查是否已启用
enable()请求钱包访问权限

dApp API(启用后)

方法说明
getNetworkId()获取网络(0 为测试网,1 为主网)
getBalance()获取总余额(CBOR)
getUtxos(amount?, paginate?)获取 UTxO
getUsedAddresses()获取已使用的地址
getUnusedAddresses()获取未使用的地址
getChangeAddress()获取找零地址
getRewardAddresses()获取质押奖励地址
signTx(tx, partialSign?)返回 witness set 中已签名的部分
signData(addr, payload)签署数据(CIP-8)
submitTx(tx)提交交易

实验性 API

方法说明
experimental.getCollateral()获取抵押 UTxOs
experimental.on(event, cb)订阅事件
experimental.off()取消订阅

类型

type Cbor = string // Hex-encoded CBOR interface Paginate { page: number limit: number } interface Cip30DataSignature { signature: string // COSE_Sign1 hex key: string // COSE_Key hex } type NetworkId = 0 | 1 // 0=testnet, 1=mainnet

事件

事件说明
accountChange账户已变更

错误处理

try { const api = await window.cardano.onekey.enable() } catch (error) { if (error.code === -3) { console.log('The wallet refused the request') } else if (error.code === -4) { console.log('The account changed; reconnect and retry') } else { console.error('Error:', error.message) } }

常见错误

错误码说明
-1请求无效
-2内部错误
-3请求被拒绝
-4账户已变更

使用 Lucid

Lucid  提供了更简单的 API:

npm install lucid-cardano
import { Lucid, Blockfrost } from 'lucid-cardano' // Initialize Lucid with OneKey const lucid = await Lucid.new( new Blockfrost('https://cardano-mainnet.blockfrost.io/api', 'your-api-key'), 'Mainnet' ) // Connect OneKey const api = await window.cardano.onekey.enable() lucid.selectWallet(api) // Send ADA const tx = await lucid .newTx() .payToAddress('addr1...', { lovelace: 5000000n }) .complete() const signedTx = await tx.sign().complete() const txHash = await signedTx.submit() console.log('TX Hash:', txHash)

使用 Mesh

Mesh  是另一个流行的 Cardano SDK:

npm install @meshsdk/core
import { BrowserWallet, Transaction } from '@meshsdk/core' // Connect to OneKey const wallet = await BrowserWallet.enable('onekey') // Get wallet info const balance = await wallet.getBalance() const addresses = await wallet.getUsedAddresses() // Build and send transaction const tx = new Transaction({ initiator: wallet }) .sendLovelace('addr1...', '5000000') const unsignedTx = await tx.build() const signedTx = await wallet.signTx(unsignedTx) const txHash = await wallet.submitTx(signedTx)

Nami 兼容性

兼容别名可能属于其他扩展。请使用 window.cardano.onekey 明确选择 OneKey。

// Access via Nami interface const nami = window.cardano.nami const api = await nami.enable() // Same API as OneKey const balance = await api.getBalance()
最后更新于