Skip to Content
dAppsCardano

Cardano

OneKey の CIP-30 互換プロバイダーで Cardano ブロックチェーンを統合します。アクセス先: window.cardano.onekey または window.cardano.nami.

OneKey は、ここで説明する操作について CIP-30 (Cardano dApp Connector) を実装しています。Nami ウォレットとの互換性も提供します。



プロバイダーの検出

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

UTxO を取得

// 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 は完全な署名済みトランザクションではなく、ウィットネスセットを返します。Cardano トランザクションライブラリで未署名トランザクションを構築し、返されたウィットネスを既存のウィットネスセットにマージして、完成したトランザクションを送信してください。

// `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)

アプリケーションにトランザクションの構築とウィットネスのマージが未実装の場合は、以下の 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?)ウィットネスセットの署名済み部分を返す
signData(addr, payload)データに署名 (CIP-8)
submitTx(tx)トランザクションを送信

実験的 API

メソッド説明
experimental.getCollateral()担保 UTxO を取得
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()
最終更新日