Skip to Content
Scalus Club is now open! Join us to get an early access to new features 🎉
DocumentationSmart ContractsExtracting from Data

Extracting from Data

FromData type class is used to convert a Data value to a Scalus value.

import scalus.builtin.*, Builtins.*, Data.* case class Account(hash: ByteString, balance: BigInt) enum State: case Empty case Active(account: Account) val fromDataExample = compile { // The `fromData` function is used to convert a `Data` value to a Scalus value. val data = iData(123) // fromData is a summoner method for the `FromData` type class // there are instances for all built-in types val a = fromData[BigInt](data) // also you can use extension method `to` on Data val b = data.to[BigInt] // you can define your own `FromData` instances { given FromData[Account] = (d: Data) => { val args = unConstrData(d).snd Account(args.head.to[ByteString], args.tail.head.to[BigInt]) } val account = data.to[Account] } // or your can you a macro to derive the FromData instance { given FromData[Account] = FromData.derived given FromData[State] = FromData.derived } }

ou can derive FromData instances for your case classes and enums via standard Scala 3 derives syntax. One caveat - you must always supply companion object with @Compile annotation on it even if it is empty. This is because Scalus needs to compile the companion object to include the FromData instance in the UPLC script.

import scalus.builtin.*, Builtins.*, Data.* case class Account(hash: ByteString, balance: BigInt) derives FromData, ToData @Compile object Account enum State derives FromData, ToData: case Empty case Active(account: Account2) @Compile object State
Last updated on