@hydra-sdk/cardano-wasm API Reference
The Cardano WASM package provides comprehensive bindings for advanced blockchain operations, including transaction building, cryptographic utilities, metadata handling, and complete Cardano protocol support.
CardanoWASM
Main export containing all Cardano WASM functionality from the Emurgo Cardano Serialization Library.
Import
import { CardanoWASM } from '@hydra-sdk/cardano-wasm'
// Access all WASM functions and classes
const {
min_fee,
Transaction,
TransactionBuilder,
Address,
Value,
BigNum,
PlutusData,
// ... and many more
} = CardanoWASM
# Top-level Functions
min_fee(tx, linear_fee)
Calculate the minimum fee for a transaction:
const linearFee = CardanoWASM.LinearFee.new(
CardanoWASM.BigNum.from_str('44'),
CardanoWASM.BigNum.from_str('155381')
)
const minFee = CardanoWASM.min_fee(transaction, linearFee)
console.log('Minimum fee:', minFee.to_str())
calculate_ex_units_ceil_cost(ex_units, ex_unit_prices)
Calculate execution unit cost:
const exUnits = CardanoWASM.ExUnits.new(
CardanoWASM.BigNum.from_str('14000000'),
CardanoWASM.BigNum.from_str('10000000000')
)
const exUnitPrices = CardanoWASM.ExUnitPrices.new(
CardanoWASM.UnitInterval.new(CardanoWASM.BigNum.from_str('721'), CardanoWASM.BigNum.from_str('10000000')),
CardanoWASM.UnitInterval.new(CardanoWASM.BigNum.from_str('577'), CardanoWASM.BigNum.from_str('10000'))
)
const cost = CardanoWASM.calculate_ex_units_ceil_cost(exUnits, exUnitPrices)
console.log('Execution cost:', cost.to_str())
min_script_fee(tx, ex_unit_prices)
Calculate minimum script fee:
const scriptFee = CardanoWASM.min_script_fee(transaction, exUnitPrices)
console.log('Minimum script fee:', scriptFee.to_str())
min_ref_script_fee(total_ref_scripts_size, ref_script_coins_per_byte)
Calculate minimum reference script fee:
const refScriptCoinsPerByte = CardanoWASM.UnitInterval.new(
CardanoWASM.BigNum.from_str('15'),
CardanoWASM.BigNum.from_str('1')
)
const refScriptFee = CardanoWASM.min_ref_script_fee(1024, refScriptCoinsPerByte)
console.log('Reference script fee:', refScriptFee.to_str())
min_ada_for_output(output, data_cost)
Calculate minimum ADA required for output:
const dataCost = CardanoWASM.DataCost.new_coins_per_byte(
CardanoWASM.BigNum.from_str('4310')
)
const minAda = CardanoWASM.min_ada_for_output(output, dataCost)
console.log('Minimum ADA:', minAda.to_str())
# Plutus Data Functions
encode_json_str_to_plutus_datum(json, schema)
Convert JSON to Plutus datum:
const jsonData = '{"constructor": 0, "fields": [{"int": 42}]}'
const datum = CardanoWASM.encode_json_str_to_plutus_datum(
jsonData,
CardanoWASM.PlutusDatumSchema.DetailedSchema
)
console.log('Plutus datum:', datum.to_hex())
decode_plutus_datum_to_json_str(datum, schema)
Convert Plutus datum to JSON:
const json = CardanoWASM.decode_plutus_datum_to_json_str(
datum,
CardanoWASM.PlutusDatumSchema.DetailedSchema
)
console.log('JSON data:', json)
hash_plutus_data(plutus_data)
Hash Plutus data:
const dataHash = CardanoWASM.hash_plutus_data(plutusData)
console.log('Data hash:', dataHash.to_hex())
hash_script_data(redeemers, cost_models, datums?)
Hash script data for transaction:
const scriptDataHash = CardanoWASM.hash_script_data(
redeemers,
costModels,
datums
)
console.log('Script data hash:', scriptDataHash.to_hex())
# Metadata Functions
encode_json_str_to_metadatum(json, schema)
Convert JSON to transaction metadata:
const jsonMetadata = '{"674": {"msg": ["Hello", "World"]}}'
const metadatum = CardanoWASM.encode_json_str_to_metadatum(
jsonMetadata,
CardanoWASM.MetadataJsonSchema.DetailedSchema
)
decode_metadatum_to_json_str(metadatum, schema)
Convert metadata to JSON:
const json = CardanoWASM.decode_metadatum_to_json_str(
metadatum,
CardanoWASM.MetadataJsonSchema.DetailedSchema
)
console.log('Metadata JSON:', json)
encode_arbitrary_bytes_as_metadatum(bytes)
Encode bytes as metadata:
const bytes = new Uint8Array([72, 101, 108, 108, 111]) // "Hello"
const metadatum = CardanoWASM.encode_arbitrary_bytes_as_metadatum(bytes)
decode_arbitrary_bytes_from_metadatum(metadata)
Decode bytes from metadata:
const bytes = CardanoWASM.decode_arbitrary_bytes_from_metadatum(metadatum)
console.log('Decoded bytes:', Array.from(bytes))
# Witness Functions
make_vkey_witness(tx_body_hash, sk)
Create verification key witness:
const txBodyHash = transaction.body().hash()
const privateKey = CardanoWASM.PrivateKey.from_hex('private_key_hex')
const vkeyWitness = CardanoWASM.make_vkey_witness(txBodyHash, privateKey)
console.log('VKey witness:', vkeyWitness.to_hex())
make_daedalus_bootstrap_witness(tx_body_hash, addr, key)
Create Daedalus bootstrap witness:
const bootstrapWitness = CardanoWASM.make_daedalus_bootstrap_witness(
txBodyHash,
byronAddress,
legacyDaedalusKey
)
make_icarus_bootstrap_witness(tx_body_hash, addr, key)
Create Icarus bootstrap witness:
const bootstrapWitness = CardanoWASM.make_icarus_bootstrap_witness(
txBodyHash,
byronAddress,
bip32PrivateKey
)
# Hash Functions
hash_auxiliary_data(auxiliary_data)
Hash auxiliary data:
const auxDataHash = CardanoWASM.hash_auxiliary_data(auxiliaryData)
console.log('Auxiliary data hash:', auxDataHash.to_hex())
# Transaction Utilities
get_implicit_input(txbody, pool_deposit, key_deposit)
Get implicit input value:
const poolDeposit = CardanoWASM.BigNum.from_str('500000000')
const keyDeposit = CardanoWASM.BigNum.from_str('2000000')
const implicitInput = CardanoWASM.get_implicit_input(
transactionBody,
poolDeposit,
keyDeposit
)
console.log('Implicit input:', implicitInput.coin().to_str())
get_deposit(txbody, pool_deposit, key_deposit)
Get deposit amount:
const deposit = CardanoWASM.get_deposit(
transactionBody,
poolDeposit,
keyDeposit
)
console.log('Deposit:', deposit.to_str())
# Encryption Functions
encrypt_with_password(password, salt, nonce, data)
Encrypt data with password:
const encrypted = CardanoWASM.encrypt_with_password(
'my_password',
'salt_string',
'nonce_string',
'data_to_encrypt'
)
console.log('Encrypted:', encrypted)
decrypt_with_password(password, data)
Decrypt data with password:
const decrypted = CardanoWASM.decrypt_with_password(
'my_password',
encryptedData
)
console.log('Decrypted:', decrypted)
# Native Script Functions
encode_json_str_to_native_script(json, self_xpub, schema)
Create native script from JSON:
const scriptJson = `{
"type": "all",
"scripts": [
{"type": "sig", "keyHash": "key_hash_here"},
{"type": "before", "slot": 1000000}
]
}`
const nativeScript = CardanoWASM.encode_json_str_to_native_script(
scriptJson,
selfXpub,
CardanoWASM.ScriptSchema.Wallet
)
# Utility Functions
create_send_all(address, utxos, config)
Create send-all transaction batches:
const batches = CardanoWASM.create_send_all(
recipientAddress,
utxos,
transactionBuilderConfig
)
console.log('Transaction batches:', batches.len())
has_transaction_set_tag(tx_bytes)
Check transaction set tags:
const txBytes = new Uint8Array(transactionHex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)))
const setTagState = CardanoWASM.has_transaction_set_tag(txBytes)
console.log('Set tag state:', setTagState)
Core Classes
Address
Address handling for all Cardano address types:
// Create from Bech32
const address = CardanoWASM.Address.from_bech32('addr_test1...')
// Create base address
const baseAddr = CardanoWASM.BaseAddress.new(
CardanoWASM.NetworkId.testnet(),
CardanoWASM.Credential.from_keyhash(paymentKeyHash),
CardanoWASM.Credential.from_keyhash(stakeKeyHash)
)
// Convert to address
const address = baseAddr.to_address()
console.log('Address:', address.to_bech32())
Value
Value and multi-asset handling:
// Create ADA-only value
const adaValue = CardanoWASM.Value.new(
CardanoWASM.BigNum.from_str('2000000')
)
// Create multi-asset value
const multiAsset = CardanoWASM.MultiAsset.new()
const assets = CardanoWASM.Assets.new()
assets.insert(
CardanoWASM.AssetName.new(Buffer.from('TokenName')),
CardanoWASM.BigNum.from_str('100')
)
multiAsset.insert(
CardanoWASM.ScriptHash.from_hex('policy_id'),
assets
)
const value = CardanoWASM.Value.new_with_assets(
CardanoWASM.BigNum.from_str('2000000'),
multiAsset
)
BigNum
Arbitrary precision numbers:
const bigNum = CardanoWASM.BigNum.from_str('1000000000000')
console.log('Big number:', bigNum.to_str())
// Arithmetic operations
const sum = bigNum.checked_add(CardanoWASM.BigNum.from_str('500000'))
const product = bigNum.checked_mul(CardanoWASM.BigNum.from_str('2'))
Transaction and TransactionBuilder
Transaction construction:
// Create transaction builder
const txBuilderCfg = CardanoWASM.TransactionBuilderConfigBuilder.new()
.fee_algo(CardanoWASM.LinearFee.new(
CardanoWASM.BigNum.from_str('44'),
CardanoWASM.BigNum.from_str('155381')
))
.pool_deposit(CardanoWASM.BigNum.from_str('500000000'))
.key_deposit(CardanoWASM.BigNum.from_str('2000000'))
.max_value_size(5000)
.max_tx_size(16384)
.coins_per_utxo_size(CardanoWASM.BigNum.from_str('4310'))
.build()
const txBuilder = CardanoWASM.TransactionBuilder.new(txBuilderCfg)
// Add input
txBuilder.add_input(
fromAddress,
CardanoWASM.TransactionInput.new(txHash, outputIndex),
inputValue
)
// Add output
txBuilder.add_output(
CardanoWASM.TransactionOutput.new(toAddress, outputValue)
)
// Build transaction
const txBody = txBuilder.build()
const tx = CardanoWASM.Transaction.new(
txBody,
CardanoWASM.TransactionWitnessSet.new()
)
PlutusData
Plutus data construction:
// Create integer datum
const intDatum = CardanoWASM.PlutusData.new_integer(
CardanoWASM.BigInt.from_str('42')
)
// Create bytes datum
const bytesDatum = CardanoWASM.PlutusData.new_bytes(
new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f])
)
// Create constructor datum
const constrDatum = CardanoWASM.PlutusData.new_constr_plutus_data(
CardanoWASM.ConstrPlutusData.new(
CardanoWASM.BigNum.from_str('0'),
CardanoWASM.PlutusList.new()
)
)
// Create map datum
const mapDatum = CardanoWASM.PlutusData.new_map(
CardanoWASM.PlutusMap.new()
)
// Create list datum
const listDatum = CardanoWASM.PlutusData.new_list(
CardanoWASM.PlutusList.new()
)
NativeScript
Native script construction:
// Signature script
const sigScript = CardanoWASM.NativeScript.new_script_pubkey(
CardanoWASM.ScriptPubkey.new(keyHash)
)
// Time lock scripts
const timeLockAfter = CardanoWASM.NativeScript.new_timelock_start(
CardanoWASM.TimelockStart.new(CardanoWASM.BigNum.from_str('1000000'))
)
const timeLockBefore = CardanoWASM.NativeScript.new_timelock_expiry(
CardanoWASM.TimelockExpiry.new(CardanoWASM.BigNum.from_str('2000000'))
)
// Multi-sig scripts
const scripts = CardanoWASM.NativeScripts.new()
scripts.add(sigScript)
scripts.add(timeLockAfter)
const allScript = CardanoWASM.NativeScript.new_script_all(
CardanoWASM.ScriptAll.new(scripts)
)
const anyScript = CardanoWASM.NativeScript.new_script_any(
CardanoWASM.ScriptAny.new(scripts)
)
const nOfKScript = CardanoWASM.NativeScript.new_script_n_of_k(
CardanoWASM.ScriptNOfK.new(2, scripts) // 2 of 3
)
PlutusScript
Plutus script handling:
// Create from hex with version
const plutusScript = CardanoWASM.PlutusScript.from_hex_with_version(
scriptHex,
CardanoWASM.Language.new_plutus_v3()
)
// Create from bytes
const plutusScript = CardanoWASM.PlutusScript.from_bytes(scriptBytes)
// Get hash
const scriptHash = plutusScript.hash()
console.log('Script hash:', scriptHash.to_hex())
Certificates
Certificate construction:
// Stake registration
const stakeReg = CardanoWASM.Certificate.new_stake_registration(
CardanoWASM.StakeRegistration.new(
CardanoWASM.Credential.from_keyhash(stakeKeyHash)
)
)
// Stake delegation
const stakeDel = CardanoWASM.Certificate.new_stake_delegation(
CardanoWASM.StakeDelegation.new(
CardanoWASM.Credential.from_keyhash(stakeKeyHash),
poolKeyHash
)
)
// Pool registration
const poolParams = CardanoWASM.PoolParams.new(
poolKeyHash,
vrfKeyHash,
pledge,
cost,
margin,
rewardAccount,
poolOwners,
relays,
poolMetadata
)
const poolReg = CardanoWASM.Certificate.new_pool_registration(
CardanoWASM.PoolRegistration.new(poolParams)
)
// Pool retirement
const poolRet = CardanoWASM.Certificate.new_pool_retirement(
CardanoWASM.PoolRetirement.new(poolKeyHash, epoch)
)
Metadata
Transaction metadata construction:
// Create general metadata
const generalMetadata = CardanoWASM.GeneralTransactionMetadata.new()
// Add text metadata
const textMetadatum = CardanoWASM.TransactionMetadatum.new_text('Hello World')
generalMetadata.insert(
CardanoWASM.BigNum.from_str('674'),
textMetadatum
)
// Add map metadata
const metadataMap = CardanoWASM.MetadataMap.new()
metadataMap.insert_str('key', 'value')
const mapMetadatum = CardanoWASM.TransactionMetadatum.new_map(metadataMap)
generalMetadata.insert(
CardanoWASM.BigNum.from_str('721'),
mapMetadatum
)
// Create auxiliary data
const auxData = CardanoWASM.AuxiliaryData.new()
auxData.set_metadata(generalMetadata)
Withdrawals
Reward withdrawals:
const withdrawals = CardanoWASM.Withdrawals.new()
withdrawals.insert(
CardanoWASM.RewardAddress.from_bech32('stake_test1...'),
CardanoWASM.BigNum.from_str('5000000') // 5 ADA
)
// Add to transaction
txBuilder.set_withdrawals(withdrawals)
Enums and Constants
NetworkId
const testnet = CardanoWASM.NetworkId.testnet()
const mainnet = CardanoWASM.NetworkId.mainnet()
Languages
const plutusV1 = CardanoWASM.Language.new_plutus_v1()
const plutusV2 = CardanoWASM.Language.new_plutus_v2()
const plutusV3 = CardanoWASM.Language.new_plutus_v3()
CoinSelectionStrategy
const strategy = CardanoWASM.CoinSelectionStrategyCIP2.LargestFirstMultiAsset
Certificate Types
// Available certificate kinds
CardanoWASM.CertificateKind.StakeRegistration
CardanoWASM.CertificateKind.StakeDeregistration
CardanoWASM.CertificateKind.StakeDelegation
CardanoWASM.CertificateKind.PoolRegistration
CardanoWASM.CertificateKind.PoolRetirement
// ... and more
Redeemer Tags
CardanoWASM.RedeemerTagKind.Spend
CardanoWASM.RedeemerTagKind.Mint
CardanoWASM.RedeemerTagKind.Cert
CardanoWASM.RedeemerTagKind.Reward
CardanoWASM.RedeemerTagKind.Vote
CardanoWASM.RedeemerTagKind.VotingProposal
Plutus Data Schemas
CardanoWASM.PlutusDatumSchema.DetailedSchema
CardanoWASM.PlutusDatumSchema.BasicSchema
Metadata Schemas
CardanoWASM.MetadataJsonSchema.DetailedSchema
CardanoWASM.MetadataJsonSchema.BasicSchema
Script Schema
CardanoWASM.ScriptSchema.Wallet
CardanoWASM.ScriptSchema.Node
Complete Examples
Basic Transaction
import { CardanoWASM } from '@hydra-sdk/cardano-wasm'
function createBasicTransaction() {
// Create transaction builder config
const txBuilderCfg = CardanoWASM.TransactionBuilderConfigBuilder.new()
.fee_algo(CardanoWASM.LinearFee.new(
CardanoWASM.BigNum.from_str('44'),
CardanoWASM.BigNum.from_str('155381')
))
.pool_deposit(CardanoWASM.BigNum.from_str('500000000'))
.key_deposit(CardanoWASM.BigNum.from_str('2000000'))
.max_value_size(5000)
.max_tx_size(16384)
.coins_per_utxo_size(CardanoWASM.BigNum.from_str('4310'))
.build()
const txBuilder = CardanoWASM.TransactionBuilder.new(txBuilderCfg)
// Add inputs (UTxOs)
const txHash = CardanoWASM.TransactionHash.from_hex('tx_hash_hex')
const txInput = CardanoWASM.TransactionInput.new(txHash, 0)
const inputValue = CardanoWASM.Value.new(CardanoWASM.BigNum.from_str('10000000'))
txBuilder.add_input(
CardanoWASM.Address.from_bech32('addr_test1...'),
txInput,
inputValue
)
// Add output
const outputAddr = CardanoWASM.Address.from_bech32('addr_test1...')
const outputValue = CardanoWASM.Value.new(CardanoWASM.BigNum.from_str('2000000'))
const output = CardanoWASM.TransactionOutput.new(outputAddr, outputValue)
txBuilder.add_output(output)
// Set change address
const changeAddr = CardanoWASM.Address.from_bech32('addr_test1...')
txBuilder.add_change_if_needed(changeAddr)
// Build transaction
const txBody = txBuilder.build()
const witnessSet = CardanoWASM.TransactionWitnessSet.new()
const transaction = CardanoWASM.Transaction.new(txBody, witnessSet)
return transaction
}
Multi-Asset Transaction
function createMultiAssetTransaction() {
const txBuilder = CardanoWASM.TransactionBuilder.new(config)
// Create multi-asset value
const multiAsset = CardanoWASM.MultiAsset.new()
const assets = CardanoWASM.Assets.new()
// Add native tokens
assets.insert(
CardanoWASM.AssetName.new(Buffer.from('MyToken')),
CardanoWASM.BigNum.from_str('100')
)
multiAsset.insert(
CardanoWASM.ScriptHash.from_hex('policy_id_hex'),
assets
)
const outputValue = CardanoWASM.Value.new_with_assets(
CardanoWASM.BigNum.from_str('2000000'), // ADA
multiAsset
)
const output = CardanoWASM.TransactionOutput.new(outputAddress, outputValue)
txBuilder.add_output(output)
return txBuilder.build()
}
NFT Minting Transaction
function createNFTMintingTransaction() {
const txBuilder = CardanoWASM.TransactionBuilder.new(config)
// Create minting value
const mint = CardanoWASM.Mint.new()
const mintAssets = CardanoWASM.MintAssets.new()
mintAssets.insert(
CardanoWASM.AssetName.new(Buffer.from('MyNFT')),
CardanoWASM.Int.new_i32(1) // Mint 1 NFT
)
mint.insert(
CardanoWASM.ScriptHash.from_hex('policy_id'),
mintAssets
)
txBuilder.set_mint(mint)
// Add minting script witness
const nativeScript = CardanoWASM.NativeScript.new_script_pubkey(
CardanoWASM.ScriptPubkey.new(keyHash)
)
const witnessSet = CardanoWASM.TransactionWitnessSet.new()
const nativeScripts = CardanoWASM.NativeScripts.new()
nativeScripts.add(nativeScript)
witnessSet.set_native_scripts(nativeScripts)
// Add NFT metadata
const metadata = CardanoWASM.GeneralTransactionMetadata.new()
const nftMetadata = createNFTMetadata('MyNFT', 'ipfs://...')
metadata.insert(CardanoWASM.BigNum.from_str('721'), nftMetadata)
const auxData = CardanoWASM.AuxiliaryData.new()
auxData.set_metadata(metadata)
const txBody = txBuilder.build()
return CardanoWASM.Transaction.new(txBody, witnessSet, auxData)
}
function createNFTMetadata(name, image) {
const metadataMap = CardanoWASM.MetadataMap.new()
metadataMap.insert_str('name', name)
metadataMap.insert_str('image', image)
metadataMap.insert_str('description', 'My unique NFT')
return CardanoWASM.TransactionMetadatum.new_map(metadataMap)
}
Plutus Script Transaction
function createPlutusScriptTransaction() {
const txBuilder = CardanoWASM.TransactionBuilder.new(config)
// Add script input
const scriptInput = CardanoWASM.TransactionInput.new(scriptTxHash, 0)
const scriptValue = CardanoWASM.Value.new(CardanoWASM.BigNum.from_str('10000000'))
txBuilder.add_input(scriptAddress, scriptInput, scriptValue)
// Create redeemer
const redeemer = CardanoWASM.Redeemer.new(
CardanoWASM.RedeemerTag.new_spend(),
CardanoWASM.BigNum.from_str('0'), // Input index
CardanoWASM.PlutusData.new_empty_constr_plutus_data(CardanoWASM.BigNum.zero()),
CardanoWASM.ExUnits.new(
CardanoWASM.BigNum.from_str('14000000'),
CardanoWASM.BigNum.from_str('10000000000')
)
)
const redeemers = CardanoWASM.Redeemers.new()
redeemers.add(redeemer)
// Add Plutus script
const plutusScript = CardanoWASM.PlutusScript.from_hex_with_version(
scriptHex,
CardanoWASM.Language.new_plutus_v3()
)
const plutusScripts = CardanoWASM.PlutusScripts.new()
plutusScripts.add(plutusScript)
// Add datum
const datum = CardanoWASM.PlutusData.from_hex('d87980')
const datums = CardanoWASM.PlutusList.new()
datums.add(datum)
// Create witness set
const witnessSet = CardanoWASM.TransactionWitnessSet.new()
witnessSet.set_plutus_scripts(plutusScripts)
witnessSet.set_plutus_data(datums)
witnessSet.set_redeemers(redeemers)
// Add collateral
const collateralInput = CardanoWASM.TransactionInput.new(collateralTxHash, 0)
const collaterals = CardanoWASM.TransactionInputs.new()
collaterals.add(collateralInput)
txBuilder.set_collateral(collaterals)
const txBody = txBuilder.build()
return CardanoWASM.Transaction.new(txBody, witnessSet)
}
Staking Operations
function createStakingTransaction() {
const txBuilder = CardanoWASM.TransactionBuilder.new(config)
// Create stake registration certificate
const stakeCredential = CardanoWASM.Credential.from_keyhash(stakeKeyHash)
const stakeRegistration = CardanoWASM.StakeRegistration.new(stakeCredential)
const regCert = CardanoWASM.Certificate.new_stake_registration(stakeRegistration)
// Create stake delegation certificate
const stakeDelegation = CardanoWASM.StakeDelegation.new(
stakeCredential,
poolKeyHash
)
const delCert = CardanoWASM.Certificate.new_stake_delegation(stakeDelegation)
// Add certificates
const certs = CardanoWASM.Certificates.new()
certs.add(regCert)
certs.add(delCert)
txBuilder.set_certs(certs)
// Add key deposit for registration
const keyDeposit = CardanoWASM.BigNum.from_str('2000000')
return txBuilder.build()
}
function createRewardWithdrawal() {
const txBuilder = CardanoWASM.TransactionBuilder.new(config)
// Create withdrawals
const withdrawals = CardanoWASM.Withdrawals.new()
const rewardAddress = CardanoWASM.RewardAddress.from_bech32('stake_test1...')
const rewardAmount = CardanoWASM.BigNum.from_str('5000000') // 5 ADA
withdrawals.insert(rewardAddress, rewardAmount)
txBuilder.set_withdrawals(withdrawals)
return txBuilder.build()
}
Advanced Metadata
function createAdvancedMetadata() {
const generalMetadata = CardanoWASM.GeneralTransactionMetadata.new()
// CIP-20 message metadata
const messageMap = CardanoWASM.MetadataMap.new()
const messageList = CardanoWASM.MetadataList.new()
messageList.add(CardanoWASM.TransactionMetadatum.new_text('Hello'))
messageList.add(CardanoWASM.TransactionMetadatum.new_text('Cardano'))
messageList.add(CardanoWASM.TransactionMetadatum.new_text('Community'))
messageMap.insert(
CardanoWASM.TransactionMetadatum.new_text('msg'),
CardanoWASM.TransactionMetadatum.new_list(messageList)
)
generalMetadata.insert(
CardanoWASM.BigNum.from_str('674'),
CardanoWASM.TransactionMetadatum.new_map(messageMap)
)
// CIP-25 NFT metadata
const nftMap = CardanoWASM.MetadataMap.new()
const policyMap = CardanoWASM.MetadataMap.new()
const assetMap = CardanoWASM.MetadataMap.new()
assetMap.insert_str('name', 'My Amazing NFT')
assetMap.insert_str('description', 'This is a unique digital collectible')
assetMap.insert_str('image', 'ipfs://QmHash...')
const attributesList = CardanoWASM.MetadataList.new()
const attribute1 = CardanoWASM.MetadataMap.new()
attribute1.insert_str('trait_type', 'Color')
attribute1.insert_str('value', 'Blue')
attributesList.add(CardanoWASM.TransactionMetadatum.new_map(attribute1))
assetMap.insert(
CardanoWASM.TransactionMetadatum.new_text('attributes'),
CardanoWASM.TransactionMetadatum.new_list(attributesList)
)
policyMap.insert(
CardanoWASM.TransactionMetadatum.new_text('AssetName'),
CardanoWASM.TransactionMetadatum.new_map(assetMap)
)
nftMap.insert(
CardanoWASM.TransactionMetadatum.new_text('policy_id'),
CardanoWASM.TransactionMetadatum.new_map(policyMap)
)
generalMetadata.insert(
CardanoWASM.BigNum.from_str('721'),
CardanoWASM.TransactionMetadatum.new_map(nftMap)
)
return generalMetadata
}
Error Handling
function handleCardanoWASMErrors() {
try {
// WASM operations that might fail
const bigNum = CardanoWASM.BigNum.from_str('invalid_number')
} catch (error) {
if (error.message.includes('BigNum')) {
console.error('BigNum parsing error:', error.message)
// Handle BigNum specific errors
} else {
console.error('General WASM error:', error)
}
}
// Safe operations with validation
function safeBigNumFromStr(str) {
try {
return CardanoWASM.BigNum.from_str(str)
} catch (error) {
console.error('Invalid BigNum string:', str)
return CardanoWASM.BigNum.zero()
}
}
function safeAddressFromBech32(bech32) {
try {
return CardanoWASM.Address.from_bech32(bech32)
} catch (error) {
console.error('Invalid address:', bech32)
return null
}
}
}
Best Practices
- Memory Management: WASM objects should be properly disposed when no longer needed
- Error Handling: Always wrap WASM calls in try-catch blocks
- Validation: Validate inputs before passing to WASM functions
- Big Numbers: Use BigNum for all monetary values and large integers
- Serialization: Use proper CBOR encoding/decoding methods
- Protocol Parameters: Keep protocol parameters up to date
- Script Validation: Validate Plutus scripts before transaction submission
- Metadata Standards: Follow established metadata standards (CIP-25, CIP-20, etc.)
