### Development Setup and Commands Source: https://github.com/input-output-hk/nami/blob/main/README.md Instructions for setting up the development environment, managing secrets, and running build or test commands. ```bash # Update secrets file with your own keys cp secrets.testing.js secrets.development.js npm start # Update secrets file with your own keys cp secrets.testing.js secrets.production.js npm run build npm test ``` -------------------------------- ### Nami Injected API - Core Methods Source: https://github.com/input-output-hk/nami/blob/main/README.md Provides examples of core Nami API methods for retrieving wallet data. This includes fetching the user's balance, UTXOs, collateral, and addresses. ```javascript const balance = await cardano.getBalance(); console.log('Balance:', balance); const utxos = await cardano.getUtxos(); console.log('UTXOs:', utxos); const collateral = await cardano.getCollateral(); console.log('Collateral:', collateral); const usedAddresses = await cardano.getUsedAddresses(); console.log('Used Addresses:', usedAddresses); const unusedAddresses = await cardano.getUnusedAddresses(); console.log('Unused Addresses:', unusedAddresses); ``` -------------------------------- ### Nami Injected API - Basic Usage Source: https://github.com/input-output-hk/nami/blob/main/README.md Demonstrates the basic steps to detect and enable the Nami wallet provider in a web browser. It covers finding the provider, requesting access, and retrieving the user's account and network information. ```javascript if (window.cardano && window.cardano.nami) { const namiApi = await window.cardano.nami.enable(); const networkId = await namiApi.getNetworkId(); const usedAddresses = await namiApi.getUsedAddresses(); console.log('Network ID:', networkId); console.log('Used Addresses:', usedAddresses); } else { console.log('Nami wallet not detected.'); } ``` -------------------------------- ### Nami Experimental API - Event Handling Source: https://github.com/input-output-hk/nami/blob/main/README.md Shows how to register and deregister callbacks for events emitted by the Nami wallet's experimental API. This includes listening for account and network changes. ```javascript const accountChangeCallback = (addresses) => { console.log('Account changed:', addresses); }; // Register event listener window.cardano.nami.experimental.on('accountChange', accountChangeCallback); // To deregister // window.cardano.nami.experimental.off('accountChange', accountChangeCallback); ``` -------------------------------- ### Migration Script Structure Source: https://github.com/input-output-hk/nami/wiki/App-upgrade-and-Migration Defines the expected structure for migration scripts written in JavaScript. Each script includes versioning, upgrade/downgrade logic, descriptive information, and an optional password requirement. ```javascript const migration = { version: '1.0.0', up: (pwd) => { // Upgrade logic here }, down: (pwd) => { // Downgrade logic here }, info: [ { title: 'Feature #1', detail: 'This new feature allow the user to see the Feature #1', }, { title: 'Bug fix: Feature #2', detail: null }, ... ], pwdRequired: true, }; export default migration; ``` -------------------------------- ### Nami Experimental API - on/off Event Handling Source: https://github.com/input-output-hk/nami/blob/main/README.md Manages event subscriptions for the Nami wallet. Allows developers to register callbacks for specific events like account or network changes and to unregister them. ```APIDOC api.experimental.on(eventName, callback) - Parameters: - eventName: string - The name of the event to listen for (e.g., 'accountChange', 'networkChange'). - callback: function - The function to execute when the event is triggered. - accountChange: ((addresses : [BaseAddress]) => void) - networkChange: ((network : number) => void) - Description: Registers a callback function to be executed when a specified event occurs. api.experimental.off(eventName, callback) - Parameters: - eventName: string - The name of the event to stop listening to. - callback: function - The callback function to remove (can be an anonymous function if registered as such). - Description: Deregisters a previously registered event listener. ``` -------------------------------- ### Nami Injected API - Deprecated Basic Usage Source: https://github.com/input-output-hk/nami/blob/main/README.md Outlines the initial steps for interacting with the deprecated Nami API. It focuses on detecting the provider, checking wallet enablement status, and retrieving basic wallet information. ```javascript if (window.cardano) { const isEnabled = await cardano.isEnabled(); console.log('Wallet enabled:', isEnabled); const networkId = await cardano.getNetworkId(); console.log('Network ID:', networkId); } else { console.log('Cardano provider not detected.'); } ``` -------------------------------- ### Cardano Event Handling Source: https://github.com/input-output-hk/nami/blob/main/README.md Provides methods to subscribe to account and network changes within the Cardano wallet. ```APIDOC cardano.onAccountChange((addresses : [BaseAddress]) => void) Description: Registers a callback function to be executed when the account address changes. The callback receives an array of BaseAddresses (though Nami returns a single address). cardano.onNetworkChange((network : number) => void) Description: Registers a callback function to be executed when the network changes. The callback receives the network ID (0 for testnet, 1 for mainnet). ``` -------------------------------- ### Cardano Transaction Signing and Submission Source: https://github.com/input-output-hk/nami/blob/main/README.md Handles the signing of Cardano transactions and their subsequent submission to the network. ```APIDOC cardano.signTx(tx: Transaction, partialSign?: boolean) : TransactionWitnessSet Parameters: tx: A hex encoded cbor string representing the transaction. partialSign: Optional boolean. If true, the wallet may not provide all required signatures. Returns: TransactionWitnessSet (hex encoded cbor string) Description: Signs the provided transaction. If partialSign is false (default), all required signatures must be provided by the wallet. If partialSign is true, partial signatures are acceptable. cardano.submitTx(tx : Transaction) : hash32 Parameters: tx: A hex encoded cbor string representing the transaction. Returns: hash32 Description: Submits the transaction to the network. Returns the transaction hash on success, otherwise throws an error. ``` -------------------------------- ### Nami Deprecated API - getUtxos Source: https://github.com/input-output-hk/nami/blob/main/README.md Fetches the unspent transaction outputs (UTXOs) available in the user's wallet. Supports optional filtering by amount and pagination. ```APIDOC cardano.getUtxos(amount?: Value, paginate?: {page: number, limit: number}) - Parameters: - amount?: Value - Optional. Filters UTXOs to those matching the specified value. - paginate?: {page: number, limit: number} - Optional. Specifies pagination parameters for the UTXO list. - Returns: Promise<[TransactionUnspentOutput]> - Description: Retrieves a list of unspent transaction outputs for the wallet, with optional filtering and pagination. - TransactionUnspentOutput: A hex encoded bytes string representing an unspent transaction output. ``` -------------------------------- ### Migration Object Structure Source: https://github.com/input-output-hk/nami/wiki/App-upgrade-and-Migration Illustrates the structure of the migration object stored within the application's storage, indicating the current version and completed migrations. ```json { "migration": { "version": "CURRENT_VERSION (1.X.X)", "completed": [] } } ``` -------------------------------- ### Cardano Data Signing Source: https://github.com/input-output-hk/nami/blob/main/README.md Enables signing arbitrary data payloads using either a BaseAddress or RewardAddress, returning a CoseSign1 object with signature details. ```APIDOC cardano.signData(address: BaseAddress|RewardAddress, payload: string) : CoseSign1 Parameters: address: The BaseAddress or RewardAddress to sign with. payload: A hex encoded utf8 string representing the data to sign. Returns: CoseSign1 (hex encoded bytes string) Description: Signs the provided payload. The returned CoseSign1 object includes the payload, signature, and protected headers (key_id, address, algorithm_id). Refer to CIP-0008 for message signing details. ``` -------------------------------- ### Nami Deprecated API - enable/isEnabled Source: https://github.com/input-output-hk/nami/blob/main/README.md Handles the process of enabling wallet access for a website and checking if access has already been granted. These methods are part of the older Nami API specification. ```APIDOC cardano.enable() - Returns: Promise - Description: Requests user permission to access the wallet. Returns true if permission is granted, otherwise throws an error. If permission is already granted, it returns true. cardano.isEnabled() - Returns: Promise - Description: Checks if the wallet has already been granted access to the requested website. Returns true if access is granted, false otherwise. ``` -------------------------------- ### Nami Experimental API - getCollateral Source: https://github.com/input-output-hk/nami/blob/main/README.md Retrieves the collateral outputs associated with the user's wallet. This is crucial for certain transaction types on the Cardano network. ```APIDOC api.experimental.getCollateral() - Returns: [TransactionUnspentOutput] - Description: Retrieves the collateral outputs for the connected wallet. - TransactionUnspentOutput: A hex encoded bytes string representing an unspent transaction output. ``` -------------------------------- ### Nami Deprecated API - getBalance Source: https://github.com/input-output-hk/nami/blob/main/README.md Retrieves the total balance of the user's wallet. The balance is returned as a hex-encoded CBOR string. ```APIDOC cardano.getBalance() - Returns: Promise - Description: Fetches the total ADA balance of the user's wallet. - Value: A hex encoded CBOR string representing the wallet's balance. ``` -------------------------------- ### Cardano Address Management Source: https://github.com/input-output-hk/nami/blob/main/README.md Provides functions to retrieve the current change address, reward address, and network ID from the Cardano wallet. ```APIDOC cardano.getChangeAddress() Returns: BaseAddress Description: Returns the same address as the one in cardano.getUsedAddresses(). cardano.getRewardAddress() Returns: [RewardAddress] Description: Returns a hex encoded bytes string representing the reward address. This function always returns an array of length 1 with the same single address. cardano.getNetworkId() Returns: number Description: Returns 0 for testnet and 1 for mainnet. ``` -------------------------------- ### Nami Deprecated API - getCollateral Source: https://github.com/input-output-hk/nami/blob/main/README.md Retrieves the collateral outputs for the user's wallet. This is a deprecated method but serves a similar purpose to the experimental version. ```APIDOC cardano.getCollateral() - Returns: Promise<[TransactionUnspentOutput]> - Description: Fetches the collateral outputs associated with the user's wallet. - TransactionUnspentOutput: A hex encoded bytes string representing an unspent transaction output. ``` -------------------------------- ### Nami Deprecated API - getUnusedAddresses Source: https://github.com/input-output-hk/nami/blob/main/README.md Returns an empty array, as Nami does not utilize the concept of multiple unused addresses in the same way as some other wallets. This is to maintain compatibility with the proposed CIP. ```APIDOC cardano.getUnusedAddresses() - Returns: Promise<[BaseAddress]> - Description: Returns an empty array, adhering to CIP standards for unused addresses, though Nami primarily uses a single address. ``` -------------------------------- ### Nami Deprecated API - getUsedAddresses Source: https://github.com/input-output-hk/nami/blob/main/README.md Returns the list of used Cardano addresses associated with the Nami wallet. Note that Nami typically uses a single address, so this array will usually contain one element. ```APIDOC cardano.getUsedAddresses() - Returns: Promise<[BaseAddress]> - Description: Retrieves the list of used Cardano addresses. For Nami, this typically returns an array with a single address. - BaseAddress: A hex encoded bytes string representing a Cardano base address. ``` -------------------------------- ### Verify Cardano Message Signature Source: https://github.com/input-output-hk/nami/blob/main/MessageSigning.md Verifies a Cardano message signature using provided address, payload, and COSE Sign1 structure. It ensures the payload matches, the address is correctly derived from the public key, and the signature is valid for the signed data. ```javascript const S = require('@emurgo/cardano-serialization-lib-nodejs'); //serialization-lib: https://github.com/Emurgo/cardano-serialization-lib const MS = require('./message-signing/rust/pkg/emurgo_message_signing'); //message-signing: https://github.com/Emurgo/message-signing/blob/master/examples/rust/src/main.rs // Example runs in Node.js (to verify in a browser, the libraries need to be imported asynchronously) /** * * @param {string} address - hex encoded * @param {string} payload - hex encoded * @param {string} coseSign1Hex - hex encoded */ const verify = (address, payload, coseSign1Hex) => { const coseSign1 = MS.COSESign1.from_bytes(Buffer.from(coseSign1Hex, 'hex')); const payloadCose = coseSign1.payload(); if (verifyPayload(payload, payloadCose)) throw new Error('Payload does not match'); const protectedHeaders = coseSign1 .headers() .protected() .deserialized_headers(); const addressCose = S.Address.from_bytes( protectedHeaders.header(MS.Label.new_text('address')).as_bytes() ); // Commented out the below line in favor of CIP-30, only use if you are using the deprecated window.cardano.signedData(address, payload) //const publicKeyCose = S.PublicKey.from_bytes(protectedHeaders.key_id()); const key = MS.COSEKey.from_bytes( Buffer.from(coseKey, 'hex') ); const publicKeyBytes = key .header( MS.Label.new_int( MS.BigNum.new_negative( MS.BigNum.from_str('2') ) ) ) .as_bytes(); const publicKeyCose = APILoader.Cardano.PublicKey.from_bytes(publicKeyBytes); if (!verifyAddress(address, addressCose, publicKeyCose)) throw new Error('Could not verify because of address mismatch'); const signature = S.Ed25519Signature.from_bytes(coseSign1.signature()); const data = coseSign1.signed_data().to_bytes(); return publicKeyCose.verify(data, signature); }; const verifyPayload = (payload, payloadCose) => { return Buffer.from(payloadCose, 'hex').compare(Buffer.from(payload, 'hex')); }; const verifyAddress = (address, addressCose, publicKeyCose) => { const checkAddress = S.Address.from_bytes(Buffer.from(address, 'hex')); if (addressCose.to_bech32() !== checkAddress.to_bech32()) return false; // check if BaseAddress try { const baseAddress = S.BaseAddress.from_address(addressCose); //reconstruct address const paymentKeyHash = publicKeyCose.hash(); const stakeKeyHash = baseAddress.stake().as_pub_key(); const reconstructedAddress = S.BaseAddress.new( checkAddress.network_id(), S.Credential.new_pub_key(paymentKeyHash), S.Credential.new_pub_key(stakeKeyHash) ); if ( checkAddress.to_bech32() !== reconstructedAddress.to_address().to_bech32() ) return false; return true; } catch (e) {} // check if RewardAddress try { //reconstruct address const stakeKeyHash = publicKeyCose.hash(); const reconstructedAddress = S.RewardAddress.new( checkAddress.network_id(), S.Credential.new_pub_key(stakeKeyHash) ); if ( checkAddress.to_bech32() !== reconstructedAddress.to_address().to_bech32() ) return false; return true; } catch (e) {} return false; }; //test verify(
, , ) //: true or false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.