Utilities Examples

This section provides practical examples based on real implementations from nodejs-playground/src.

Data Conversion

String and Hex Conversion

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

// String to hex for token names
const assetNameHex = ParserUtils.stringToHex('AniaToken')
console.log('Asset name hex:', assetNameHex)

// Bytes to hex conversion
const bytes = new Uint8Array([0xde, 0xad, 0xbe, 0xef])
const hex = ParserUtils.bytesToHex(bytes)
const backToBytes = ParserUtils.hexToBytes(hex)
console.log('Round trip successful:', bytes.every((b, i) => b === backToBytes[i]))

Asset Serialization

typescript
import { serializeAssetUnit } from '@hydra-sdk/core'

const policyId = 'your_policy_id_here'
const assetNameHex = ParserUtils.stringToHex('AniaToken')
const assetUnit = serializeAssetUnit(policyId, assetNameHex)

// Use in transaction output
const output = {
  address: 'addr1...',
  amount: [
    { unit: 'lovelace', quantity: '2000000' },
    { unit: assetUnit, quantity: '1000000' }
  ]
}

Datum Creation

Basic Datum Construction

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

// Simple datum types
const intDatum = DatumUtils.mkInt(42)
const bytesDatum = DatumUtils.mkBytes('deadbeef')
const listDatum = DatumUtils.mkList([intDatum, bytesDatum])

// Constructor datum
const constrDatum = DatumUtils.mkConstr(0, [intDatum, bytesDatum])

// Map datum
const mapDatum = DatumUtils.mkMap([
  [DatumUtils.mkBytes('key1'), intDatum],
  [DatumUtils.mkBytes('key2'), bytesDatum]
])

NFT Metadata Datum

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

const createNFTDatum = (name: string, image: string, attributes: Record<string, string>) => {
  const attributeEntries = Object.entries(attributes).map(([key, value]) => [
    DatumUtils.mkBytes(ParserUtils.stringToHex(key)),
    DatumUtils.mkBytes(ParserUtils.stringToHex(value))
  ])

  return DatumUtils.mkMap([
    [DatumUtils.mkBytes(ParserUtils.stringToHex("name")), 
     DatumUtils.mkBytes(ParserUtils.stringToHex(name))],
    [DatumUtils.mkBytes(ParserUtils.stringToHex("image")), 
     DatumUtils.mkBytes(ParserUtils.stringToHex(image))],
    [DatumUtils.mkBytes(ParserUtils.stringToHex("attributes")), 
     DatumUtils.mkMap(attributeEntries)]
  ])
}

// Usage
const nftDatum = createNFTDatum(
  "CryptoPunk #1234",
  "ipfs://QmYourHashHere",
  { "type": "Alien", "accessory": "3D Glasses" }
)

Time and Slot Utilities

Transaction Timing

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

// Calculate validity range (real pattern from hydra-unlock.ts)
const now = Date.now()
const slotConfig = SLOT_CONFIG_NETWORK.PREPROD

const validFrom = TimeUtils.unixTimeToEnclosingSlot(now, slotConfig)
const validUntil = TimeUtils.unixTimeToEnclosingSlot(now + 60 * 60 * 1000, slotConfig) // 1 hour

console.log(`Transaction valid from slot ${validFrom} to ${validUntil}`)

// Convert slot to readable time
const readableTime = new Date(
  TimeUtils.slotToBeginUnixTime(validUntil, slotConfig)
).toLocaleString()
console.log(`Valid until: ${readableTime}`)

Vesting Schedule

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

const createVestingDatum = (
  beneficiary: string,
  totalAmount: bigint,
  vestingMonths: number
) => {
  const slotConfig = SLOT_CONFIG_NETWORK.PREPROD
  const startTime = Date.now() + (30 * 24 * 60 * 60 * 1000) // Start in 30 days
  const endTime = startTime + (vestingMonths * 30 * 24 * 60 * 60 * 1000)
  
  const startSlot = TimeUtils.unixTimeToEnclosingSlot(startTime, slotConfig)
  const endSlot = TimeUtils.unixTimeToEnclosingSlot(endTime, slotConfig)
  
  return DatumUtils.mkConstr(0, [
    DatumUtils.mkBytes(beneficiary),
    DatumUtils.mkInt(totalAmount),
    DatumUtils.mkInt(startSlot),
    DatumUtils.mkInt(endSlot)
  ])
}

Policy Creation

Minting Policy

typescript
import { PolicyUtils, AppWallet, NETWORK_ID } from '@hydra-sdk/core'

const wallet = new AppWallet({
  networkId: NETWORK_ID.PREPROD,
  key: { type: 'mnemonic', words: AppWallet.brew() }
})

const account = wallet.getAccount(0, 0)
const policyScript = PolicyUtils.buildMintingPolicyScriptFromAddress(
  account.baseAddressBech32
)

console.log('Policy script:', policyScript)
console.log('Minter address:', account.baseAddressBech32)

Provider Setup

Blockfrost Provider

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

const provider = new ProviderUtils.BlockfrostProvider({
  apiKey: process.env.BLOCKFROST_API_KEY || '',
  network: 'preprod'
})

// Fetch UTxOs
const utxos = await provider.fetcher.fetchAddressUTxOs(address)
console.log('UTxOs:', utxos.length)

Ogmios Provider

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

const provider = new ProviderUtils.OgmiosProvider({
  apiEndpoint: 'https://preprod.cardano-rpc.hydrawallet.app',
  network: 'preprod'
})

// Submit transaction
const txHash = await provider.submitter.submitTx(signedTxCbor)
console.log('Transaction hash:', txHash)

Error Handling

Safe Utility Operations

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

class SafeUtils {
  static safeStringToHex(str: string): string | null {
    try {
      return ParserUtils.stringToHex(str)
    } catch (error) {
      console.error('String to hex conversion failed:', error.message)
      return null
    }
  }
  
  static safeTimeToSlot(timestamp: number): number | null {
    try {
      return TimeUtils.unixTimeToEnclosingSlot(timestamp, SLOT_CONFIG_NETWORK.PREPROD)
    } catch (error) {
      console.error('Time to slot conversion failed:', error.message)
      return null
    }
  }
}

// Usage
const hex = SafeUtils.safeStringToHex("Hello World")
const slot = SafeUtils.safeTimeToSlot(Date.now())

if (hex && slot) {
  console.log('Conversions successful:', { hex, slot })
}

Transaction Deserialization

Basic Transaction Info

typescript
import { deserializeTx } from '@hydra-sdk/core'

const signedTxCbor = 'your_signed_transaction_cbor'
const tx = deserializeTx(signedTxCbor)

// Get transaction hash
const txHash = tx.transaction_hash().to_hex()
console.log('Transaction hash:', txHash)

// Inspect transaction structure
const body = tx.transaction_body()
console.log('Inputs:', body.inputs().len())
console.log('Outputs:', body.outputs().len())

These examples demonstrate practical usage patterns for Hydra SDK v1.1.0 utilities, based on real implementations from the nodejs-playground.