API Reference

@hydra-sdk/core - Utilities

Comprehensive collection of utility functions for Cardano blockchain data, WASM operations, and common development tasks

Hydra SDK provides a comprehensive collection of utility functions for working with Cardano blockchain data, WASM operations, and common development tasks.

Overview

Utilities are organized into multiple categories:

  • - Create and manage cryptographic keys
  • - Convert between data formats
  • - Work with Plutus data structures
  • - Build Plutus script redeemers
  • - Validate addresses and transaction outputs
  • - Manage minting policies
  • - Convert transaction metadata
  • - Calculate slots and time
  • - Abstract blockchain data providers
  • - Low-level blockchain operations

Import

All utilities are exported as namespaced modules for better organization:

import {
    Serializer,
    Deserializer,
    Resolver,
    Converter,
    BuildKeys,
    ParserUtils,
    TimeUtils,
    DatumUtils,
    RedeemerUtils,
    ValidationUtils,
    PolicyUtils,
    MetadataUtils,
    ProviderUtils,
    CostModels,
    KeysUtils,
    SLOT_CONFIG_NETWORK
} from '@hydra-sdk/core'

Keys Utilities 1.1.5+

KeysUtils.cardanoCliKeygen() → { sk: CardanoCLiSkey; vk: CardanoCLiVkey }

Generate an ed25519 key pair compatible with Cardano CLI.

Description: Generate signing and verification keys compatible with Cardano CLI format.

Example:

import { KeysUtils } from '@hydra-sdk/core'

const cardanoKeys = KeysUtils.cardanoCliKeygen()
console.log({
    skey: cardanoKeys.sk.cborHex, // PaymentSigningKeyShelley_ed25519
    vkey: cardanoKeys.vk.cborHex // PaymentVerificationKeyShelley_ed25519
})

Returns: { sk: CardanoCLiSkey; vk: CardanoCLiVkey }

{
  sk: CardanoCLiSkey,
  vk: CardanoCLiVkey,
}

KeysUtils.hydraCliKeygen() → { sk: HydraCliSkey; vk: HydraCliVkey }

Generate an ed25519 key pair compatible with Hydra.

Description: Generate signing and verification keys compatible with Hydra CLI format.

Example:

import { KeysUtils } from '@hydra-sdk/core'

const hydraKeys = KeysUtils.hydraCliKeygen()
console.log({
    skey: hydraKeys.sk.cborHex, // HydraSigningKey_ed25519
    vkey: hydraKeys.vk.cborHex // HydraVerificationKey_ed25519
})

Returns: { sk: HydraCliSkey; vk: HydraCliVkey }

{
  sk: HydraCliSkey,
  vk: HydraCliVkey,
}

KeysUtils.genVkey(skey: CardanoCLiSkey | HydraCliSkey) → CardanoCLiVkey | HydraCliVkey

Generate a verification key from a signing key.

Parameters:

  • skey (CardanoCLiSkey | HydraCliSkey): Source signing key

Example:

import { KeysUtils } from '@hydra-sdk/core'

const skey = KeysUtils.cardanoCliKeygen().sk
const vkey = KeysUtils.genVkey(skey)
console.log('Verification Key:', vkey.cborHex)

Returns: CardanoCLiVkey | HydraCliVkey Corresponding verification key


KeysUtils.mnemonicToCliKey(mnemonic: string[], accountIndex?: number, keyIndex?: number)

{ sk: CardanoCLiSkey; vk: CardanoCLiVkey } 1.1.6+

Convert a BIP-39 mnemonic phrase to Cardano CLI compatible key pair.

Description: Derives payment keys from a mnemonic phrase using BIP-44 derivation path (m/1852'/1815'/account'/0/keyIndex). This allows you to generate keys that are compatible with Cardano wallets and CLI tools.

Parameters:

  • mnemonic (string): BIP-39 mnemonic words (12 or 24 words)
  • accountIndex (number, optional): Account index in derivation path (default: 0)
  • keyIndex (number, optional): Key index in derivation path (default: 0)

Example:

import { KeysUtils, AppWallet } from '@hydra-sdk/core'

// Generate a random mnemonic
const mnemonic = AppWallet.brew()

// Convert to CLI keys with default indexes
const keys = KeysUtils.mnemonicToCliKey(mnemonic)
console.log({
    skey: keys.sk.cborHex,
    vkey: keys.vk.cborHex
})

// Use specific account index (for multiple accounts)
const account1Keys = KeysUtils.mnemonicToCliKey(mnemonic, 1)

// Use specific key index (for multiple addresses)
const addressKeys = KeysUtils.mnemonicToCliKey(mnemonic, 0, 5)

Returns: { sk: CardanoCLiSkey; vk: CardanoCLiVkey }

{
  sk: CardanoCLiSkey,  // PaymentSigningKeyShelley_ed25519
  vk: CardanoCLiVkey   // PaymentVerificationKeyShelley_ed25519
}

Important Notes:

  • Uses BIP-44 derivation path: m/1852'/1815'/accountIndex'/0/keyIndex
  • Different accountIndex values create different accounts from the same mnemonic
  • Different keyIndex values create different payment addresses for the same account
  • Keys are deterministic - same mnemonic + indexes always produce the same keys
  • Compatible with Cardano CLI and most Cardano wallets

Data Parsing

ParserUtils.bytesToHex(bytes: ArrayBuffer | Uint8Array | Buffer) → string

Convert bytes to hex string.

Parameters:

  • bytes (ArrayBuffer | Uint8Array | Buffer): Bytes data to convert

Example:

import { ParserUtils } from '@hydra-sdk/core'

const bytes = new Uint8Array([72, 101, 108, 108, 111])
const hex = ParserUtils.bytesToHex(bytes)
console.log(hex) // "48656c6c6f"

Returns: string Hex string


ParserUtils.hexToBytes(hex: string) → Buffer

Convert hex string to bytes.

Parameters:

  • hex (string): Hex string to convert

Example:

import { ParserUtils } from '@hydra-sdk/core'

const bytes = ParserUtils.hexToBytes('48656c6c6f')
console.log(bytes) // <Buffer 48 65 6c 6c 6f>

Returns: Buffer Bytes data


ParserUtils.stringToHex(str: string) → string

Convert UTF-8 string to hex.

Parameters:

  • str (string): UTF-8 string

Example:

import { ParserUtils } from '@hydra-sdk/core'

const hex = ParserUtils.stringToHex('Hello World')
console.log(hex) // "48656c6c6f20576f726c64"

Returns: string Hex string


ParserUtils.hexToString(hex: string) → string

Convert hex string to UTF-8.

Parameters:

  • hex (string): Hex string to convert

Example:

import { ParserUtils } from '@hydra-sdk/core'

const str = ParserUtils.hexToString('48656c6c6f20576f726c64')
console.log(str) // "Hello World"

Returns: string UTF-8 string


ParserUtils.toBytes(strOrHex: string) → Uint8Array

Convert string or hex to bytes.

Parameters:

  • strOrHex (string): String or hex string

Example:

import { ParserUtils } from '@hydra-sdk/core'

const bytes1 = ParserUtils.toBytes('Hello World')
const bytes2 = ParserUtils.toBytes('48656c6c6f')
console.log(bytes1, bytes2)

Returns: Uint8Array Bytes data


ParserUtils.fromUTF8(str: string) → string

Convert UTF-8 string to hex (alias).

Parameters:

  • str (string): UTF-8 string

Example:

import { ParserUtils } from '@hydra-sdk/core'

const hex = ParserUtils.fromUTF8('Hello')
console.log(hex) // "48656c6c6f"

Returns: string Hex string


ParserUtils.toUTF8(hex: string) → string

Convert hex string to UTF-8 (alias).

Parameters:

  • hex (string): Hex string

Example:

import { ParserUtils } from '@hydra-sdk/core'

const str = ParserUtils.toUTF8('48656c6c6f')
console.log(str) // "Hello"

Returns: string UTF-8 string


Datum Utilities

DatumUtils.mkInt(n: string | number | bigint) → PlutusData

Create an integer datum.

Parameters:

  • n (string | number | bigint): Integer value

Example:

import { DatumUtils } from '@hydra-sdk/core'

const intDatum = DatumUtils.mkInt(42)
const bigIntDatum = DatumUtils.mkInt(9007199254740991n)
console.log(intDatum.to_hex())

Returns: PlutusData Integer datum


DatumUtils.mkBytes(hex: string) → PlutusData

Create a bytes datum from hex string.

Parameters:

  • hex (string): Hex string of bytes data

Example:

import { DatumUtils } from '@hydra-sdk/core'

const bytesDatum = DatumUtils.mkBytes('deadbeef')
console.log(bytesDatum.to_hex())

Returns: PlutusData Bytes datum


DatumUtils.mkConstr(alt: number, fields: PlutusData[]) → PlutusData

Create a constructor datum.

Parameters:

  • alt (number): Constructor index (0-based)
  • fields (PlutusData): Array of Plutus data fields

Example:

import { DatumUtils } from '@hydra-sdk/core'

const constrDatum = DatumUtils.mkConstr(0, [
    DatumUtils.mkInt(42),
    DatumUtils.mkBytes('deadbeef')
])
console.log(constrDatum.to_hex())

Returns: PlutusData Constructor datum


DatumUtils.mkMap(entries: Array<[PlutusData, PlutusMapValues]>) → PlutusData

Create a map datum.

Parameters:

  • entries (Array<PlutusData, PlutusMapValues>): Array of key-value pairs

Example:

import { DatumUtils } from '@hydra-sdk/core'

const mapDatum = DatumUtils.mkMap([
    [DatumUtils.mkInt(1), DatumUtils.mkBytes('value1')],
    [DatumUtils.mkInt(2), DatumUtils.mkBytes('value2')]
])
console.log(mapDatum.to_hex())

Returns: PlutusData Map datum


DatumUtils.mkList(elements: PlutusData[]) → PlutusData

Create a list datum from an array of Plutus data elements.

Example:

import { DatumUtils } from '@hydra-sdk/core'

const listDatum = DatumUtils.mkList([DatumUtils.mkInt(1), DatumUtils.mkInt(2)])
console.log(listDatum.to_hex())

Returns: PlutusData


DatumUtils.mkBool(value: boolean) → PlutusData

Create a boolean datum. Encoded as Constr(0, []) for false and Constr(1, []) for true.

Example:

import { DatumUtils } from '@hydra-sdk/core'

const trueDatum = DatumUtils.mkBool(true)
console.log(trueDatum.to_hex())

Returns: PlutusData


DatumUtils.mkOption(value?: PlutusData | null) → PlutusData

Create an optional datum. Some is Constr(0, [value]); None (no/null value) is Constr(1, []).

Example:

import { DatumUtils } from '@hydra-sdk/core'

const some = DatumUtils.mkOption(DatumUtils.mkInt(42))
const none = DatumUtils.mkOption()

Returns: PlutusData


DatumUtils.mkBytesList(items: Array<string | Uint8Array>) → PlutusData

Create a list datum from an array of byte strings (hex) or Uint8Array values.

Example:

import { DatumUtils } from '@hydra-sdk/core'

const bytesList = DatumUtils.mkBytesList(['deadbeef', new Uint8Array([1, 2, 3])])

Returns: PlutusData


DatumUtils.mkIntList(items: Array<string | number | bigint>) → PlutusData

Create a list datum from an array of integer values.

Example:

import { DatumUtils } from '@hydra-sdk/core'

const intList = DatumUtils.mkIntList([1, 2, 9007199254740991n])

Returns: PlutusData


DatumUtils.mkOutputRef(ref: { txHash: string; index: number | bigint }) → PlutusData

Create an output reference datum, encoded as Constr(0, [Bytes(txHash), Int(index)]).

Example:

import { DatumUtils } from '@hydra-sdk/core'

const outputRef = DatumUtils.mkOutputRef({
    txHash: '1d2e5b97f1cad7bea2b06144abc4974012fa786c9e7e5faddd03243b967a03f6',
    index: 0
})

Returns: PlutusData


DatumUtils.mkAddress(bech32: string) → PlutusData

Encode a bech32 Cardano address into its Plutus data representation.

Example:

import { DatumUtils } from '@hydra-sdk/core'

const addrDatum = DatumUtils.mkAddress('addr1qx2fxv2umyhttkxyxp8x0...')

Returns: PlutusData


DatumUtils.parseAddress(data: PlutusData, networkId?: number) → string

Decode Plutus address data back into a bech32 address string.

Parameters:

  • data (PlutusData): Plutus address data
  • networkId (number, optional): Network ID for the resulting address (default: MAINNET)

Example:

import { DatumUtils, NETWORK_ID } from '@hydra-sdk/core'

const bech32 = DatumUtils.parseAddress(addrDatum, NETWORK_ID.PREPROD)

Returns: string Bech32 address


Redeemer Utilities 1.4.0+

Build Plutus script redeemers. Import: import { RedeemerUtils } from '@hydra-sdk/core'.

RedeemerUtils.mkRedeemer(data: PlutusData, options?: BuildRedeemerOptions) → Redeemer

Wrap Plutus data into a Redeemer.

Parameters:

  • data (PlutusData): Redeemer data
  • options (BuildRedeemerOptions, optional):
    • tag ('spend' | 'mint' | 'reward' | 'cert' | 'vote' | 'voting_proposal', case-insensitive): Redeemer tag. Default: 'spend'
    • index (string | number | bigint): Redeemer index. Default: 0
    • exUnits ({ mem, steps }): Execution unit budget. Default: RedeemerUtils.DEFAULT_EX_UNITS

Example:

import { RedeemerUtils, DatumUtils } from '@hydra-sdk/core'

const data = DatumUtils.mkConstr(1, [])
const redeemer = RedeemerUtils.mkRedeemer(data, { tag: 'spend', index: 0 })

Returns: Redeemer


RedeemerUtils.mkSpendRedeemer(data: PlutusData, options?) → Redeemer

Build a redeemer with the tag preset to spend.

Example:

import { RedeemerUtils, DatumUtils } from '@hydra-sdk/core'

const redeemer = RedeemerUtils.mkSpendRedeemer(DatumUtils.mkConstr(0, []))

Returns: Redeemer


RedeemerUtils.mkMintRedeemer(data: PlutusData, options?) → Redeemer

Build a redeemer with the tag preset to mint.

Example:

import { RedeemerUtils, DatumUtils } from '@hydra-sdk/core'

const redeemer = RedeemerUtils.mkMintRedeemer(DatumUtils.mkConstr(0, []))

Returns: Redeemer


RedeemerUtils.mkUnitRedeemer(options?) → Redeemer

Build the Unit redeemer Constr(0, []) — the "no argument" redeemer.

Example:

import { RedeemerUtils } from '@hydra-sdk/core'

const redeemer = RedeemerUtils.mkUnitRedeemer()

Returns: Redeemer


RedeemerUtils.mkExUnits({ mem, steps }) → ExUnits

Build an ExUnits execution budget. RedeemerUtils.DEFAULT_EX_UNITS is { mem: '5000000', steps: '2000000000' } (a placeholder budget — evaluate scripts for production).

Example:

import { RedeemerUtils } from '@hydra-sdk/core'

const exUnits = RedeemerUtils.mkExUnits({ mem: '5000000', steps: '2000000000' })

Returns: ExUnits


Validation Utilities 1.4.0+

ValidationUtils.isValidTxOutput(output: TxOutput) → boolean

Check whether a transaction output is valid. Import: import { ValidationUtils } from '@hydra-sdk/core'.

Parameters:

  • output (TxOutput): Transaction output to verify

Example:

import { ValidationUtils } from '@hydra-sdk/core'

const isValid = ValidationUtils.isValidTxOutput(txOutput)
console.log('Output valid:', isValid)

Returns: boolean


Policy Utilities

PolicyUtils.buildPolicyScriptFromPubkey(pubkeyScript: PubkeyScript) → string

Build a policy script from public key.

Parameters:

  • pubkeyScript (PubkeyScript):
    • type: 'sig'
    • keyHash (string): Public key hash

Example:

import { PolicyUtils } from '@hydra-sdk/core'

const policyScript = PolicyUtils.buildPolicyScriptFromPubkey({
    type: 'sig',
    keyHash: 'abc123def456...'
})
console.log('Policy Script:', policyScript)

Returns: string Native script in JSON format


PolicyUtils.buildMintingPolicyScriptFromAddress(addressBech32: string) → string

Build a minting policy script from an address.

Parameters:

  • addressBech32 (string): Cardano address (bech32)

Example:

import { PolicyUtils } from '@hydra-sdk/core'

const mintingScript = PolicyUtils.buildMintingPolicyScriptFromAddress(
    'addr1qx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp'
)
console.log('Minting Script:', mintingScript)

Returns: string Script in JSON format


PolicyUtils.buildMintingPolicyScriptFromKeyHash(keyHash: string) → string

Build a minting policy script from key hash.

Parameters:

  • keyHash (string): Public key hash (hex)

Example:

import { PolicyUtils } from '@hydra-sdk/core'

const mintingScript =
    PolicyUtils.buildMintingPolicyScriptFromKeyHash('abc123...')
console.log('Minting Script:', mintingScript)

Returns: string Script in JSON format


PolicyUtils.policyIdFromNativeScript(nativeScript: string) → string

Extract Policy ID from native script.

Parameters:

  • nativeScript (string): Native script in JSON string format

Example:

import { PolicyUtils } from '@hydra-sdk/core'

const policyId = PolicyUtils.policyIdFromNativeScript(policyScript)
console.log('Policy ID:', policyId)

Returns: string Policy ID (hex hash)


Metadata Utilities

MetadataUtils.metadataObjToMetadatum(metadata: any) → TransactionMetadatum

Convert various data types to Cardano transaction metadata.

Parameters:

  • metadata (any): Data to convert (string, number, bigint, Uint8Array, array, object, Map)

Example:

import { MetadataUtils } from '@hydra-sdk/core'

// Convert string
const stringMetadata = MetadataUtils.metadataObjToMetadatum('Hello World')

// Convert number
const numberMetadata = MetadataUtils.metadataObjToMetadatum(42)

// Convert bigint
const bigintMetadata = MetadataUtils.metadataObjToMetadatum(9007199254740991n)

// Convert bytes
const bytesMetadata = MetadataUtils.metadataObjToMetadatum(
    new Uint8Array([1, 2, 3, 4])
)

// Convert array
const arrayMetadata = MetadataUtils.metadataObjToMetadatum([
    'item1',
    42,
    new Uint8Array([5, 6])
])

// Convert object to map
const objectMetadata = MetadataUtils.metadataObjToMetadatum({
    name: 'NFT Name',
    image: 'ipfs://...',
    attributes: ['trait1', 'trait2']
})

// Convert Map
const mapMetadata = MetadataUtils.metadataObjToMetadatum(
    new Map([
        ['key1', 'value1'],
        ['key2', 42]
    ])
)

Returns: TransactionMetadatum Cardano formatted metadata

Important Notes:

  • Maximum metadata bytes size: 64 bytes
  • Maximum metadata text size: 64 characters
  • Arrays and Maps are processed recursively, pay attention to total metadata size

Time Utilities

TimeUtils.slotToBeginUnixTime(slot: number, slotConfig: SlotConfig) → number

Convert slot to Unix timestamp.

Parameters:

  • slot (number): Slot number
  • slotConfig (SlotConfig): Slot configuration (PREPROD, MAINNET, etc.)

Example:

import { TimeUtils, SLOT_CONFIG_NETWORK } from '@hydra-sdk/core'

const timestamp = TimeUtils.slotToBeginUnixTime(
    1000,
    SLOT_CONFIG_NETWORK.PREPROD
)
const date = new Date(timestamp * 1000)
console.log('Slot start time:', date.toLocaleString())

Returns: number Unix timestamp (seconds)


TimeUtils.unixTimeToEnclosingSlot(unixTime: number, slotConfig: SlotConfig) → number

Convert Unix timestamp to slot.

Parameters:

  • unixTime (number): Unix timestamp (seconds)
  • slotConfig (SlotConfig): Slot configuration

Example:

import { TimeUtils, SLOT_CONFIG_NETWORK } from '@hydra-sdk/core'

const slot = TimeUtils.unixTimeToEnclosingSlot(
    Math.floor(Date.now() / 1000),
    SLOT_CONFIG_NETWORK.PREPROD
)
console.log('Current slot:', slot)

Returns: number Slot number


TimeUtils.resolveSlotNo(network: Network, milliseconds?: number) → string

Determine slot number for a network at a given time.

Parameters:

  • network (Network): Target network ('MAINNET' | 'PREPROD' | 'PREVIEW')
  • milliseconds (number, optional): Timestamp in milliseconds (default: Date.now())

Example:

import { TimeUtils } from '@hydra-sdk/core'

const slotNo = TimeUtils.resolveSlotNo('PREPROD')
console.log('Current slot:', slotNo)

Returns: string Slot number as string


TimeUtils.resolveEpochNo(network: Network, milliseconds?: number) → number

Determine epoch number for a network at a given time.

Parameters:

  • network (Network): Target network ('MAINNET' | 'PREPROD' | 'PREVIEW')
  • milliseconds (number, optional): Timestamp in milliseconds (default: Date.now())

Example:

import { TimeUtils } from '@hydra-sdk/core'

const epochNo = TimeUtils.resolveEpochNo('PREPROD')
console.log('Current epoch:', epochNo)

Returns: number Epoch number


TimeUtils.buildHydraSlotConfig(startTimestamp: number, options?: object) → SlotConfig

Build Hydra slot configuration anchored at a Head start timestamp.

Parameters:

  • startTimestamp (number): Head start timestamp in milliseconds (required)
  • options (object, optional): Overrides for zeroSlot, slotLength, startEpoch, and epochLength

Example:

import { TimeUtils } from '@hydra-sdk/core'

const slotConfig = TimeUtils.buildHydraSlotConfig(Date.now())
console.log('Hydra Slot Config:', {
    zeroTime: slotConfig.zeroTime,
    zeroSlot: slotConfig.zeroSlot,
    slotLength: slotConfig.slotLength
})

Returns: SlotConfig Slot configuration


Provider Utilities

ProviderUtils.BlockfrostProvider(config: BlockfrostProviderConfig) → BlockfrostProvider

Create a Blockfrost provider to query and submit transactions to the Cardano blockchain.

Description: BlockfrostProvider is a wallet provider that connects to Blockfrost API for fetching UTxOs and submitting transactions. It extends BaseWalletProvider and provides both fetcher and submitter functionality.

Parameters:

  • config (BlockfrostProviderConfig):
    • apiKey (string): Your Blockfrost Project ID from Blockfrost Dashboard
    • network (BlockfrostSupportedNetworks): Network to connect to ('mainnet', 'preprod', or 'preview')
    • apiVersion (number, optional): Blockfrost API version (default: 0)
    • baseURL (string, optional): Override the default Blockfrost endpoint URL. Useful for Blockfrost-compatible APIs such as Demeter.
    • cachingOptions (object, optional): Caching configuration
      • enabled (boolean): Enable response caching (default: false)
      • maxSize (number): Maximum cache items (default: 100)
      • ttl (number): Time to live in milliseconds (default: 300000 - 5 minutes)

Properties:

  • fetcher (IFetcher): Interface for fetching blockchain data
    • fetchAddressUTxOs(address: string, asset?: string): Promise<UTxO[]> - Fetch UTxOs for an address, optionally filtered by asset
  • submitter (ISubmitter): Interface for submitting transactions
    • submitTx(txHex: string): Promise<string> - Submit a signed transaction and return transaction hash

Example:

import { ProviderUtils } from '@hydra-sdk/core'

// Basic configuration
const provider = new ProviderUtils.BlockfrostProvider({
    apiKey: 'preprodXXXXXXXXXXXXXXXXXXXX',
    network: 'preprod'
})

// With API version and caching
const providerWithCache = new ProviderUtils.BlockfrostProvider({
    apiKey: 'preprodXXXXXXXXXXXXXXXXXXXX',
    network: 'preprod',
    apiVersion: 0,
    cachingOptions: {
        enabled: true,
        maxSize: 200,
        ttl: 600000 // 10 minutes
    }
})

// Fetch all UTxOs for an address
const utxos = await provider.fetcher.fetchAddressUTxOs(
    'addr1qx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer...'
)

// Fetch UTxOs containing a specific asset
const assetUtxos = await provider.fetcher.fetchAddressUTxOs(
    'addr1qx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer...',
    'lovelace' // or policy_id + asset_name
)

// Submit a signed transaction
const txHash = await provider.submitter.submitTx(signedTxHex)
console.log('Transaction submitted:', txHash)

Returns: BlockfrostProvider Provider instance


ProviderUtils.OgmiosProvider(config: OgmiosProviderConfig) → OgmiosProvider

Create an Ogmios provider to query and submit transactions using JSON-RPC 2.0 protocol.

Description: OgmiosProvider is a wallet provider that connects to Ogmios API via HTTP for fetching UTxOs and submitting transactions. It extends BaseWalletProvider and uses JSON-RPC 2.0 protocol to communicate with Ogmios server.

Parameters:

  • config (OgmiosProviderConfig):
    • network (OgmiosSupportedNetworks): Network to connect to ('mainnet', 'preprod', or 'preview')
    • apiEndpoint (string, optional): Ogmios API endpoint URL

Properties:

  • fetcher (IFetcher): Interface for fetching blockchain data
    • fetchAddressUTxOs(address: string, asset?: string): Promise<UTxO[]> - Fetch UTxOs for an address, optionally filtered by asset
  • submitter (ISubmitter): Interface for submitting transactions
    • submitTx(tx: string): Promise<string> - Submit a signed transaction and return transaction hash

Example:

import { ProviderUtils } from '@hydra-sdk/core'

// Connect to remote Ogmios instance
const remoteProvider = new ProviderUtils.OgmiosProvider({
    network: 'preprod',
    apiEndpoint: 'https://preprod.ogmios.cardano-rpc.hydrawallet.app'
})

// Fetch all UTxOs for an address
const utxos = await remoteProvider.fetcher.fetchAddressUTxOs(
    'addr1qx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer...'
)

// Fetch UTxOs containing a specific asset
const assetUtxos = await remoteProvider.fetcher.fetchAddressUTxOs(
    'addr1qx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer...',
    'lovelace' // or policy_id + asset_name
)

// Submit a signed transaction
const txHash = await remoteProvider.submitter.submitTx(signedTxHex)
console.log('Transaction submitted:', txHash)

Returns: OgmiosProvider Provider instance with fetcher and submitter interfaces


ProviderUtils.DemeterProvider(config: DemeterProviderConfig) → DemeterProvider

Create a provider for Demeter's Blockfrost-compatible hosted endpoints. Extends BlockfrostProvider, so it exposes the same fetcher/submitter surface. Authentication is embedded in the endpoint subdomain via authToken.

Parameters:

  • config (DemeterProviderConfig):
    • authToken (string): Your Demeter auth token (also used as the authenticated subdomain)
    • network (DemeterSupportedNetworks): Network to connect to ('mainnet', 'preprod', or 'preview')
    • apiVersion (number, optional): Blockfrost API version (default: 0)
    • cachingOptions (object, optional): Same caching configuration as BlockfrostProvider

Example:

import { ProviderUtils } from '@hydra-sdk/core'

const provider = new ProviderUtils.DemeterProvider({
    authToken: 'blockfrost102lx3ckhzvkjjh7677g',
    network: 'preprod'
})

// Same fetcher / submitter interface as BlockfrostProvider
const utxos = await provider.fetcher.fetchAddressUTxOs(
    'addr1qx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer...'
)
const txHash = await provider.submitter.submitTx(signedTxHex)

The endpoint is built as https://{authToken}.cardano-{network}.blockfrost-m1.demeter.run/api/v{apiVersion ?? 0}.

Returns: DemeterProvider Provider instance with fetcher and submitter interfaces


Cardano WASM Utilities

Serializer.serializeAssetUnit(policyId: string, assetName: string) → string

Build an asset unit string by concatenating a policy ID and an asset name (both hex).

Parameters:

  • policyId (string): Policy ID (hex)
  • assetName (string): Asset name (hex)

Example:

import { Serializer } from '@hydra-sdk/core'

const unit = Serializer.serializeAssetUnit('a1b2c3...', '48656c6c6f')
console.log('Asset unit:', unit)

Returns: string Asset unit (policyId + assetName)


Deserializer.deserializeTx(txCborHex: string) → FixedTransaction

Deserialize a transaction CBOR hex string into a CardanoWASM.FixedTransaction.

Parameters:

  • txCborHex (string): Transaction CBOR hex string

Example:

import { Deserializer } from '@hydra-sdk/core'

const tx = Deserializer.deserializeTx(cborHex)
console.log('Tx hash:', tx.transaction_hash().to_hex())

Returns: FixedTransaction Parsed transaction object


Deserializer.deserializeAmountsFromTx(cborHex: string) → Asset[]

Return all amounts (lovelace + native tokens) across every output of a transaction, merged by unit.

Parameters:

  • cborHex (string): Transaction CBOR hex string

Example:

import { Deserializer } from '@hydra-sdk/core'

const amounts = Deserializer.deserializeAmountsFromTx(cborHex)
console.log('Amounts:', amounts)
// => [{ unit: 'lovelace', quantity: '5000000' }, ...]

Returns: Asset[] Array of { unit, quantity } entries merged by unit


Resolver.resolveTxHash(cborHex: string) → string

Resolve the transaction hash from a transaction CBOR hex string.

Parameters:

  • cborHex (string): Transaction CBOR hex string

Example:

import { Resolver } from '@hydra-sdk/core'

const txHash = Resolver.resolveTxHash(cborHex)
console.log('Transaction hash:', txHash)

Returns: string Transaction hash (hex)


Resolver.resolveTxBodyHash(txBody: TransactionBody) → TransactionHash

Resolve the transaction hash from a TransactionBody.

Parameters:

  • txBody (TransactionBody): Transaction body object

Example:

import { Resolver } from '@hydra-sdk/core'

const hash = Resolver.resolveTxBodyHash(txBody)
console.log('Transaction hash:', hash.to_hex())

Returns: TransactionHash Transaction hash object


Converter.convertUTxOObjectToUTxO(utxoObject: UTxOObject) → UTxO[]

Convert a snapshot-format UTxO object into an array of UTxO items. Use Converter.convertUTxOToUTxOObject(utxos) for the reverse direction, and Converter.convertUTxOObjectToUTxOWithOptions(utxoObject, options) to tune the datum deserialization cache.

Parameters:

  • utxoObject (UTxOObject): Snapshot UTxO object

Example:

import { Converter } from '@hydra-sdk/core'

const utxos = Converter.convertUTxOObjectToUTxO(snapshotUtxo)
console.log('UTxO count:', utxos.length)

// Reverse conversion
const snapshot = Converter.convertUTxOToUTxOObject(utxos)

Returns: UTxO[] Array of UTxOs

Hex conversion helpers live on ParserUtils (see ) — use ParserUtils.bytesToHex / ParserUtils.hexToBytes. Converter deals with UTxO shapes, not raw hex.


BuildKeys.buildKeys(privateKeyHex: string | [string, string], accountIndex: number, keyIndex?: number) → { accountKey, paymentKey, stakeKey, dRepKey? }

Derive account, payment, stake, and dRep keys from a root private key using the BIP-44 derivation path m/1852'/1815'/accountIndex'/role/keyIndex.

Parameters:

  • privateKeyHex (string | string, string): Root private key hex (or an [accountKey, stakeKey] pair)
  • accountIndex (number): Account index
  • keyIndex (number, optional): Key index (default: 0)

Example:

import { BuildKeys } from '@hydra-sdk/core'

const { accountKey, paymentKey, stakeKey } = BuildKeys.buildKeys(rootKeyHex, 0, 0)
console.log('Payment key:', paymentKey.to_hex())

Returns: { accountKey, paymentKey, stakeKey, dRepKey? } Derived Bip32PrivateKey values


BuildKeys.buildBaseAddress(networkId: number, paymentKeyHash, stakeKeyHash) → BaseAddress

Build a base address (payment + staking) from payment and stake key hashes. Companion helpers buildEnterpriseAddress and buildRewardAddress are also available.

Parameters:

  • networkId (number): Network ID (e.g. NETWORK_ID.PREPROD)
  • paymentKeyHash (Ed25519KeyHash): Payment key hash
  • stakeKeyHash (Ed25519KeyHash): Stake key hash

Example:

import { BuildKeys, NETWORK_ID } from '@hydra-sdk/core'

const baseAddress = BuildKeys.buildBaseAddress(
    NETWORK_ID.PREPROD,
    paymentKeyHash,
    stakeKeyHash
)
console.log('Base address:', baseAddress.to_address().to_bech32())

Returns: BaseAddress Base address object


Cost Models

CostModels.buildCostModels(models: { plutusV1?: number[]; plutusV2?: number[]; plutusV3?: number[] }) → Costmdls

Build cost models for Plutus scripts. At least one of plutusV1 / plutusV2 / plutusV3 must be provided, otherwise it throws At least one cost model must be provided. For zero-config defaults use CostModels.defaultCostModels.

Parameters:

  • models (object): Cost model lists keyed by Plutus language version

Example:

import { CostModels } from '@hydra-sdk/core'

// Ready-made defaults for all three Plutus versions
const defaults = CostModels.defaultCostModels

// Or build from explicit cost model lists
const costModels = CostModels.buildCostModels({
    plutusV3: [/* ...cost model integers... */]
})
console.log('Cost Models:', costModels)

Returns: Costmdls Cost models object


Complete Examples

Basic Data Conversion

import {
    ParserUtils,
    DatumUtils,
    PolicyUtils,
    SLOT_CONFIG_NETWORK,
    TimeUtils
} from '@hydra-sdk/core'

// Convert data
const hex = ParserUtils.stringToHex('Hello Cardano')
const bytes = ParserUtils.hexToBytes(hex)
console.log('Hex:', hex)
console.log('Bytes:', bytes)

// Work with time
const currentSlot = TimeUtils.unixTimeToEnclosingSlot(
    Math.floor(Date.now() / 1000),
    SLOT_CONFIG_NETWORK.PREPROD
)
const readableTime = new Date(
    TimeUtils.slotToBeginUnixTime(currentSlot, SLOT_CONFIG_NETWORK.PREPROD) * 1000
)
console.log('Current slot:', currentSlot)
console.log('Readable time:', readableTime.toLocaleString())

// Create datum
const datum = DatumUtils.mkConstr(0, [
    DatumUtils.mkInt(42),
    DatumUtils.mkBytes(hex)
])
console.log('Datum hex:', datum.to_hex())

Working with Keys

import { KeysUtils } from '@hydra-sdk/core'

// Generate Cardano CLI keys
const cardanoKeys = KeysUtils.cardanoCliKeygen()
console.log({
    signingKey: cardanoKeys.sk.cborHex,
    verificationKey: cardanoKeys.vk.cborHex
})

// Generate Hydra keys
const hydraKeys = KeysUtils.hydraCliKeygen()
console.log({
    hydraSigningKey: hydraKeys.sk.cborHex,
    hydraVkey: hydraKeys.vk.cborHex
})

// Generate verification key from signing key
const vkey = KeysUtils.genVkey(cardanoKeys.sk)
console.log('Verification Key:', vkey.cborHex)

Creating Minting Policy

import { PolicyUtils, ParserUtils } from '@hydra-sdk/core'

// Build policy from key hash
const keyHash = '...' // Your public key hash
const policyScript = PolicyUtils.buildMintingPolicyScriptFromKeyHash(keyHash)

// Extract Policy ID
const policyId = PolicyUtils.policyIdFromNativeScript(policyScript)
console.log('Policy ID:', policyId)

// Build policy from address
const address = 'addr1qx2fxv2...'
const addressPolicy = PolicyUtils.buildMintingPolicyScriptFromAddress(address)
const addressPolicyId = PolicyUtils.policyIdFromNativeScript(addressPolicy)
console.log('Address Policy ID:', addressPolicyId)

Handling Metadata

import { MetadataUtils } from '@hydra-sdk/core'

// NFT metadata
const nftMetadata = MetadataUtils.metadataObjToMetadatum({
    name: 'My NFT',
    image: 'ipfs://QmXxxx...',
    description: 'A beautiful NFT',
    attributes: [
        { trait_type: 'Rarity', value: 'Rare' },
        { trait_type: 'Color', value: 'Blue' }
    ]
})

// Custom metadata with numbers and bytes
const customMetadata = MetadataUtils.metadataObjToMetadatum(
    new Map([
        ['owner', 'Alice'],
        ['value', 1000000],
        ['hash', new Uint8Array([0x12, 0x34, 0x56, 0x78])]
    ])
)

console.log('NFT Metadata:', nftMetadata)
console.log('Custom Metadata:', customMetadata)

Query Blockchain with Provider

import { ProviderUtils } from '@hydra-sdk/core'

// Using Blockfrost
const blockfrostProvider = new ProviderUtils.BlockfrostProvider({
    apiKey: 'your-blockfrost-project-id',
    network: 'preprod'
})

// Query UTxOs via the fetcher (there is no getUtxos/getProtocolParameters on providers)
const utxos = await blockfrostProvider.fetcher.fetchAddressUTxOs(address)
console.log('UTxOs:', utxos)

// Submit via the submitter
// const txHash = await blockfrostProvider.submitter.submitTx(signedTxHex)

// Using Ogmios
const ogmiosProvider = new ProviderUtils.OgmiosProvider({
    network: 'preprod',
    apiEndpoint: 'http://localhost:1337'
})

const ogmiosUtxos = await ogmiosProvider.fetcher.fetchAddressUTxOs(address)
console.log('Ogmios UTxOs:', ogmiosUtxos)

Type Definitions

All utilities come with comprehensive TypeScript definitions:

import type {
    SlotConfig,
    Network,
    PlutusData,
    ConstrPlutusData,
    PlutusMap,
    CardanoCLiSkey,
    CardanoCLiVkey,
    HydraCliSkey,
    HydraCliVkey,
    TransactionMetadatum
} from '@hydra-sdk/core'