Skip to Content
dAppsCardano

Cardano

Intégrez la blockchain Cardano à l’aide du fournisseur OneKey compatible CIP-30. Accès via window.cardano.onekey ou window.cardano.nami.

OneKey implémente CIP-30 (Cardano dApp Connector) pour les opérations documentées ici. Il assure aussi la compatibilité avec le portefeuille Nami.



Détection du fournisseur

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

Démarrage rapide

Activer le portefeuille

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

Vérifier l’activation

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

Informations du compte

Obtenir l’ID du réseau

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

Obtenir le solde

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.

Obtenir les adresses

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

Obtenir les 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, })

Transactions

Signer une transaction

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

Soumettre une transaction

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

Construire, signer et soumettre

signTx renvoie un ensemble de témoins, pas une transaction signée complète. Construisez la transaction non signée avec une bibliothèque de transactions Cardano, fusionnez les témoins renvoyés avec son ensemble de témoins existant, puis soumettez la transaction complète obtenue.

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

Utilisez le processus Lucid ou Mesh ci-dessous si votre application n’implémente pas déjà la construction de transactions et la fusion des témoins. Ces exemples de SDK sont propres à certaines versions ; suivez leur documentation pour la version installée.


Signature de données

Signer des données (CIP-8)

Signer des données arbitraires pour l’authentification :

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

Vérifier la signature

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.

Gestion des événements

Écouter les changements de compte

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

Référence de l’API

Interface du portefeuille (CIP-30)

Propriété/MéthodeDescription
nameNom du portefeuille (‘OneKey’)
iconURL de l’icône du portefeuille
apiVersionVersion de l’API
isEnabled()Vérifier l’activation
enable()Demander l’accès au portefeuille

API dApp (après activation)

MéthodeDescription
getNetworkId()Obtenir le réseau (0=testnet, 1=mainnet)
getBalance()Obtenir le solde total (CBOR)
getUtxos(amount?, paginate?)Obtenir les UTxO
getUsedAddresses()Obtenir les adresses utilisées
getUnusedAddresses()Obtenir les adresses inutilisées
getChangeAddress()Obtenir l’adresse de monnaie rendue
getRewardAddresses()Obtenir les adresses de staking
signTx(tx, partialSign?)Renvoyer les parties signées d’un ensemble de témoins
signData(addr, payload)Signer des données (CIP-8)
submitTx(tx)Soumettre une transaction

API expérimentale

MéthodeDescription
experimental.getCollateral()Obtenir les UTxO de garantie
experimental.on(event, cb)S’abonner aux événements
experimental.off()Se désabonner

Types

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

Événements

ÉvénementDescription
accountChangeCompte modifié

Gestion des erreurs

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

Erreurs courantes

CodeDescription
-1Requête non valide
-2Erreur interne
-3Requête refusée
-4Compte modifié

Utilisation avec Lucid

Lucid  fournit une API plus simple :

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)

Utilisation avec Mesh

Mesh  est un autre SDK Cardano populaire :

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)

Compatibilité Nami

L’alias de compatibilité peut appartenir à une autre extension. Utilisez window.cardano.onekey pour sélectionner explicitement OneKey.

// Access via Nami interface const nami = window.cardano.nami const api = await nami.enable() // Same API as OneKey const balance = await api.getBalance()
Dernière mise à jour le