@hydra-sdk/bridge
Classes
HydraBridge
Main class for connecting to and managing Hydra Heads.
HydraBridge.constructor(options: HydraBridgeOptions) → HydraBridge
Initialize a new Hydra Bridge instance.
Parameters:
options(HydraBridgeOptions):url?: WebSocket URL (e.g., 'ws://localhost:4001')connector?: Custom connector instanceverbose?: Enable verbose logging mode
Example:
import { HydraBridge } from '@hydra-sdk/bridge'
// Direct WebSocket connection
const bridge = new HydraBridge({
url: 'ws://localhost:4001',
verbose: true
})
// Using custom connector
const bridge = new HydraBridge({
connector: customConnector,
verbose: true
})
Returns: HydraBridge
New HydraBridge instance
Connection Management
HydraBridge.connect() → Promise<void>
Connect to the Hydra Node.
Example:
await bridge.connect()
console.log('Connected to Hydra Node')
Returns: Promise<void>
HydraBridge.disconnect() → Promise<void>
Disconnect from the Hydra Node.
Example:
await bridge.disconnect()
console.log('Disconnected from Hydra Node')
Returns: Promise<void>
HydraBridge.connected() → boolean
Check the connection status.
Example:
const isConnected = bridge.connected()
console.log('Connection status:', isConnected)
Returns: boolean
True if connected, false otherwise
Head Information
HydraBridge.headInfo() → Promise<HeadInfo>
Get information about the current Head.
Example:
const info = await bridge.headInfo()
console.log({
headId: info.headId,
headStatus: info.headStatus,
vkey: info.vkey
})
Returns: Promise<HeadInfo>
Head information object
Protocol Parameters
HydraBridge.getProtocolParameters() → Promise<Protocol>
Get Cardano protocol parameters.
Example:
const protocolParams = await bridge.getProtocolParameters()
console.log({
minFeeA: protocolParams.min_fee_a,
minFeeB: protocolParams.min_fee_b,
maxTxSize: protocolParams.max_tx_size,
keyDeposit: protocolParams.key_deposit,
poolDeposit: protocolParams.pool_deposit
})
Returns: Promise<Protocol>
Protocol parameters object
UTxO Management
HydraBridge.querySnapshotUtxo() → Promise<UTxOObject>
Query UTxOs in the current snapshot.
Example:
const utxoObject = await bridge.querySnapshotUtxo()
console.log('Snapshot UTxO:', utxoObject)
Returns: Promise<UTxOObject>
UTxO object from snapshot
HydraBridge.snapshotUtxoArray() → UTxO[]
Get UTxOs array from snapshot.
Example:
const utxoArray = bridge.snapshotUtxoArray()
console.log('UTxO array:', utxoArray)
Returns: UTxO[]
Array of UTxOs
HydraBridge.queryAddressUTxO(address: string) → Promise<UTxO[]>
Query UTxOs for a specific address.
Parameters:
address(string): Cardano address (bech32)
Example:
const account = wallet.getAccount(0, 0)
const addressUtxos = await bridge.queryAddressUTxO(account.baseAddressBech32)
console.log('Address UTxOs:', addressUtxos)
Returns: Promise<UTxO[]>
Array of UTxOs for the address
HydraBridge.addressesInHead() → Promise<string[]>
Get all addresses in the current Head.
Example:
const addresses = await bridge.addressesInHead()
console.log('Addresses in Head:', addresses)
Returns: Promise<string[]>
Array of addresses
Transaction Operations
HydraBridge.submitTxSync(transaction: Transaction, options?: SubmitOptions) → Promise<TxResult>
Submit transaction and wait for confirmation.
Parameters:
transaction(Transaction): Transaction to submitoptions?(SubmitOptions): Submission optionstimeout?: Timeout in milliseconds
Example:
const result = await bridge.submitTxSync({
type: 'Witnessed Tx ConwayEra',
description: 'Ledger Cddl Format',
cborHex: signedTxCbor,
txId: transactionId
}, { timeout: 30000 })
console.log({
txId: result.txId,
isValid: result.isValid,
isConfirmed: result.isConfirmed
})
Returns: Promise<TxResult>
Transaction result object
HydraBridge.commit(data: CommitData) → Promise<any>
Commit UTxOs into the Head.
Parameters:
data(CommitData): Commit data object
Example:
const result = await bridge.commit({
cborHex: commitTxCbor,
description: 'Commit transaction'
})
console.log('Commit result:', result)
Returns: Promise<any>
HydraBridge.submitCardanoTransaction(data: TransactionData) → Promise<any>
Submit transaction to Cardano network.
Parameters:
data(TransactionData): Transaction data object
Example:
const result = await bridge.submitCardanoTransaction({
cborHex: txCbor,
description: 'Cardano transaction'
})
console.log('Cardano transaction submitted:', result)
Returns: Promise<any>
Commands
HydraBridge.commands.init() → void
Initialize a new Hydra Head.
Example:
bridge.commands.init()
HydraBridge.commands.close() → void
Close the Hydra Head.
Example:
bridge.commands.close()
HydraBridge.commands.abort() → void
Abort Head initialization.
Example:
bridge.commands.abort()
HydraBridge.commands.fanout() → void
Perform fanout after closing Head.
Example:
bridge.commands.fanout()
HydraBridge.commands.contest() → void
Contest the Head closure.
Example:
bridge.commands.contest()
HydraBridge.commands.recover(recoverTxId: string) → void
Recover from a specific transaction.
Parameters:
recoverTxId(string): Transaction hash to recover from
Example:
bridge.commands.recover('tx_hash_here')
HydraBridge.commands.newTx(cborHex: string, description: string, callback?: Function) → void
Send a new transaction to the Head.
Parameters:
cborHex(string): Transaction in CBOR hex formatdescription(string): Transaction descriptioncallback?(Function): Callback function when sent
Example:
bridge.commands.newTx(
signedTxCbor,
'Payment transaction',
() => console.log('Transaction sent to Head')
)
HydraBridge.commands.decommit(payload: DecommitPayload) → Promise<DecommitResult>
Decommit UTxOs from the Head.
Parameters:
payload(DecommitPayload): Decommit datacborHex: Transaction CBOR hextxId: Transaction IDtimeout?: Timeout value
Example:
const result = await bridge.commands.decommit({
cborHex: decommitTxCbor,
txId: transactionId,
timeout: 30000
})
console.log('Decommit result:', result)
Returns: Promise<DecommitResult>
HydraBridge.commands.initSync(retry?: number, interval?: number) → Promise<any>
Initialize Head with retry logic.
Parameters:
retry?(number): Number of retries. Default: 3interval?(number): Interval between retries (ms). Default: 20000
Example:
const result = await bridge.commands.initSync(3, 20000)
console.log('Head initialized:', result)
Returns: Promise<any>
Connectors
WebsocketConnector
Basic WebSocket connector for direct connection to Hydra Node.
Constructor:
import { WebsocketConnector } from '@hydra-sdk/bridge'
const connector = new WebsocketConnector({
websocketUrl: 'ws://localhost:4001'
})
const bridge = new HydraBridge({
connector: connector,
verbose: true
})
HexcoreConnector
Advanced connector for Hexcore API integration with Socket.IO authentication.
Constructor:
import { HexcoreConnector } from '@hydra-sdk/bridge'
const connector = new HexcoreConnector({
socketIoUrl: 'wss://api.hexcore.io/hydra',
socketIoOptions: {
auth: {
token: 'your_jwt_token'
},
transports: ['websocket'],
timeout: 20000
},
namespace: 'hydra'
})
const bridge = new HydraBridge({
connector: connector,
verbose: true
})
await bridge.connect()
Event Handling
Bridge provides comprehensive event handling through the events property:
Connection Events
// Connection established
bridge.events.on('onConnected', () => {
console.log('Connected to Hydra Node')
})
// Connection lost
bridge.events.on('onDisconnected', () => {
console.log('Disconnected from Hydra Node')
})
// Connection error
bridge.events.on('onConnectError', (error) => {
console.error('Connection error:', error)
})
// General error
bridge.events.on('onError', (error) => {
console.error('Bridge error:', error)
})
Head Lifecycle Events
bridge.events.on('onMessage', (payload) => {
console.log('Message received:', payload.tag, payload.timestamp)
switch (payload.tag) {
case 'Greetings':
console.log('Greeting from Head:', {
headStatus: payload.headStatus,
headId: payload.hydraHeadId
})
break
case 'HeadIsInitializing':
console.log('Head initializing with parties:', payload.parties)
break
case 'HeadIsOpen':
console.log('Head is open and ready for transactions!')
break
case 'HeadIsClosed':
console.log('Head closed, performing fanout...')
break
case 'HeadIsFinalized':
console.log('Head lifecycle completed')
break
case 'TxValid':
console.log('Transaction is valid:', payload.transaction)
break
case 'TxInvalid':
console.log('Transaction is invalid:', {
transaction: payload.transaction,
error: payload.validationError
})
break
case 'SnapshotConfirmed':
console.log('Snapshot confirmed')
break
case 'Committed':
console.log('UTxO committed:', payload.utxo)
break
case 'DecommitApproved':
console.log('Decommit approved:', payload.decommitTxId)
break
case 'DecommitFinalized':
console.log('Decommit finalized')
break
case 'CommandFailed':
console.error('Command failed:', payload.clientInput)
break
}
})
Types and Interfaces
HydraBridgeOptions
interface HydraBridgeOptions {
url?: string
connector?: HydraBridgeConnector
verbose?: boolean
}
HydraPayload
interface HydraPayload {
tag: HydraHeadTag
timestamp: string
seq?: number
[key: string]: any
}
HydraHeadStatus
enum HydraHeadStatus {
Idle = 'Idle',
Initializing = 'Initializing',
Open = 'Open',
Closed = 'Closed',
FanoutPossible = 'FanoutPossible',
Final = 'Final'
}
Protocol
interface Protocol {
min_fee_a: number
min_fee_b: number
max_tx_size: number
key_deposit: string
pool_deposit: string
[key: string]: any
}
Complete Examples
Basic Head Management
import { HydraBridge } from '@hydra-sdk/bridge'
async function manageHydraHead() {
const bridge = new HydraBridge({
url: 'ws://localhost:4001',
verbose: true
})
// Set up event handlers before connecting
bridge.events.on('onConnected', () => {
console.log('Connected! Initializing Head...')
bridge.commands.init()
})
bridge.events.on('onMessage', (payload) => {
switch (payload.tag) {
case 'HeadIsInitializing':
console.log('Head initializing with', payload.parties.length, 'parties')
break
case 'HeadIsOpen':
console.log('Head is open and ready for transactions!')
break
case 'TxValid':
console.log('Transaction confirmed:', payload.transaction.txId)
break
case 'HeadIsClosed':
console.log('Head closed, performing fanout...')
bridge.commands.fanout()
break
case 'HeadIsFinalized':
console.log('Head lifecycle completed')
bridge.disconnect()
break
}
})
// Connect to start the process
await bridge.connect()
}
Processing Transactions in Hydra Head
import { HydraBridge } from '@hydra-sdk/bridge'
import { TxBuilder } from '@hydra-sdk/transaction'
import { AppWallet } from '@hydra-sdk/core'
async function processHydraTransactions() {
const bridge = new HydraBridge({
url: 'ws://localhost:4001',
verbose: true
})
const wallet = new AppWallet({
networkId: 0,
key: { type: 'mnemonic', words: AppWallet.brew() }
})
bridge.events.on('onConnected', async () => {
// Get protocol parameters
const protocolParams = await bridge.getProtocolParameters()
// Create transaction builder
const txBuilder = new TxBuilder({
isHydra: true,
params: protocolParams
})
// Get account and UTxOs
const account = wallet.getAccount(0, 0)
const addressUtxos = await bridge.queryAddressUTxO(account.baseAddressBech32)
if (addressUtxos.length === 0) {
console.log('No UTxOs found for address')
return
}
// Build and sign transaction
const tx = await txBuilder
.setInputs(addressUtxos)
.txOut(account.baseAddressBech32, [{ unit: 'lovelace', quantity: '1000000' }])
.changeAddress(account.baseAddressBech32)
.complete()
const signedTx = await wallet.signTx(tx.to_hex(), false, 0, 0)
// Submit to Hydra Head
const result = await bridge.submitTxSync({
type: 'Witnessed Tx ConwayEra',
description: 'Ledger Cddl Format',
cborHex: signedTx,
txId: tx.id
}, { timeout: 30000 })
console.log('Transaction successful:', result)
})
await bridge.connect()
}
Advanced Hexcore Integration
import { HydraBridge, HexcoreConnector } from '@hydra-sdk/bridge'
async function connectToHexcore() {
const connector = new HexcoreConnector({
socketIoUrl: 'wss://api.hexcore.io/hydra',
socketIoOptions: {
auth: {
token: 'your_jwt_token'
},
transports: ['websocket'],
timeout: 20000
},
namespace: 'hydra'
})
const bridge = new HydraBridge({
connector: connector,
verbose: true
})
bridge.events.on('onConnected', () => {
console.log('Authenticated and connected to Hexcore')
})
bridge.events.on('onError', (error) => {
console.error('Hexcore connection error:', error)
})
await bridge.connect()
}
Best Practices
- Event Setup: Always set up event handlers before calling
connect() - Error Handling: Implement comprehensive error handling and reconnection logic
- State Management: Track Head state to ensure valid operations
- Authentication: Use proper JWT tokens for Hexcore connections
- Resource Cleanup: Always call
disconnect()when done - Transaction Validation: Validate transactions before submission
- Timeout Configuration: Set appropriate timeouts for operations
- Logging: Enable verbose mode for debugging during development
Related Documentation
- Core API - Wallet and utilities
- Transaction Builder API - Build transactions
