Smart Contract Optimization
Sourced from the Aiken team's optimization guide.
Before optimizing
Optimizing code can be counter-intuitive, especially in the context of smart contracts. The virtual machine and its associated cost models can be sometimes confusing and move in ways that one fails to anticipate.
Hence, before doing any optimisation work it is essential to set up some baseline benchmarks. Those benchmarks shall cover simple and complex scenarios alike, to easily identify the impact of changes. Sometimes, a change may introduce a one-time cost that slightly increases a simple case while making a more complex scenario significantly better.
Writing baseline benchmarks
A good strategy for writing baseline benchmarks is to write a simple test executing one or more validator from a pre-constructed context and redeemer. This allows to get an overview that is as close as possible to a "real scenario" with a "real transaction".
For example:
use my_validator
test baseline() {
my_validator.main.withdraw(
baseline_redeemer,
baseline_credential,
baseline_transaction,
)
}
Use const
Aiken constants are fully evaluated during compilation and inlined where used. It is, therefore, highly recommended to define preparatory code for benchmarks as constants. This not only allows separating fixture code from benchmark executions, but also allows measuring a cost closer to the real execution.
const baseline_transaction: Transaction = Transaction {
..transaction.placeholder,
inputs: some_inputs(3),
}
test baseline() {
my_validator.main.withdraw(
baseline_redeemer,
baseline_credential,
baseline_transaction,
)
}
Using Fuzzer
Fuzzers constitute a very practical way to write fixtures. Transactions in particular can be easily created using the primitives from fuzz/cardano. For example:
use aiken/fuzz
use cardano/fuzz as cardano
pub fn some_basic_input() -> Fuzzer<Input> {
let output_reference <- fuzz.and_then(cardano.output_reference())
let address <- fuzz.and_then(cardano.address())
fuzz.constant(Input {
output_reference,
output: Output {
address,
value: min_ada_value,
datum: NoDatum,
reference_script: None,
}
})
}
A good rule of thumb is to start off transaction.placeholder from the standard library, and progressively add elements to a transaction in order to make it valid. Fuzzers are handy for elements in the transaction that can be arbitrary, while you may stick to well-known values for others.
const transaction = Transaction {
..transaction.placeholder,
inputs: [
some_input_with_programmable_tokens(
[(policy_programmable_token, asset_name_programmable_token, 42)],
"programmable tokens input",
),
some_input_fuel("fuel input"),
],
outputs: [
some_output_with_programmable_tokens(
[(policy_programmable_token, asset_name_programmable_token, 28)],
),
some_output_with_programmable_tokens(
[(policy_programmable_token, asset_name_programmable_token, 14)],
),
some_output_change("change output"),
],
}
The standard library: good or bad?
Let's cover one last point before we dive in: the standard library. Should you use it? Most certainly yes. Will it harm the performance of your program? To some extent, yes. The standard library is reasonably well optimised, yet it is tuned for correctness and ease of use. Its main goal is to get you started and to be convenient.
Yet, it is easy to replace surgically where needed. Most functions in the standard library are standalone, easily inlinable and can be specialised. Thus it is recommended to always start with the standard library in order to write the most obviously correct code and only then, think about where it could be optimised.
Many optimisations are actually domain-specific and require intrinsic knowledge to be really effective. While still designing smart contracts, optimisations about how the code is written shouldn't be the priority (but rather, be only an architectural concern). Once your on-chain code is mostly fleshed out, it's good to take a step back and reflect on your usage of the standard lib in critical parts of your program: maybe you don't need all the genericity offered by this particular function, or maybe you can use a simpler, more direct recursive implementation of that other function.
There are few functions from the standard library that you particularly want to look for and avoid in validators. Those functions are usually only good for testing, but not so much for critical paths. These red flags are:
assets.{flatten, flatten_with, restricted_to}dict.{from_pairs, keys, map, values}list.{count, flat_map, map, reverse, sort, zip}
You almost certainly never want to use any of those in validators.
Decide early and cheaply
The cheapest work is work that never runs. These three reorder a validator so the common case exits as soon as it can, and the expensive case is the only one that pays.
Fail fast
On-chain code isn't about error handling. If something is wrong: fail. Option is rarely something you want to use.
- Don't
- Do
mem=1.80K · cpu=501.69K
// Be nice to transaction builders in case they provide a negative value
let value = if datum.value <= 0 { -datum.value } else { datum.value }
mem=1.40K · cpu=336.48K
/// invariant violation: value must be non-negative
expect datum.value >= 0
Put cheap and likely checks first
When chaining conditions with and or or, order matters. Aiken short-circuits boolean operators, which means that the first satisfied branch of an or avoids evaluating the others, and the first failing branch of an and stops the rest.
So, when possible, place first the checks that are both:
- cheaper to evaluate, and
- more likely to determine the result (i.e. more frequently
True)
- Don't
- Do
or {
input.output.value |> assets.has_nft_strict(my_nft),
input.output.address.payment_credential != my_script_credential,
}
or {
input.output.address.payment_credential != my_script_credential,
input.output.value |> assets.has_nft_strict(my_nft),
}
In this example, comparing credentials is a direct and predictable check. Inspecting the value to determine whether a specific NFT is present is more involved. Since the first condition may already be sufficient to decide the whole expression, putting it first gives the runtime more opportunities to stop early.
Defer distinctions until they matter
Another common source of unnecessary work comes from splitting terminal cases too early. When several branches eventually collapse into a smaller number of "real" outcomes, it is often better to test the broader condition first and refine only when necessary.
- Don't
- Do
- Bench
mem=85.04K · cpu=29.49M
fn insert_in_order(self: List<Int>, elem: Int) -> List<Int> {
when self is {
[] -> [elem]
[head, ..tail] ->
if head == elem {
self
} else if elem < head {
[elem, ..self]
} else {
[head, ..insert_in_order(tail, elem)]
}
}
}
mem=72.91K · cpu=26.11M
fn insert_in_order(self: List<Int>, elem: Int) -> List<Int> {
when self is {
[] -> [elem]
[head, ..tail] ->
if elem <= head {
if head == elem {
self
} else {
[elem, ..self]
}
} else {
[head, ..insert_in_order(tail, elem)]
}
}
}
test baseline() {
and {
insert_in_order([], 1) == [1],
insert_in_order([1, 2, 3, 4, 5, 6, 7], 8) == [1, 2, 3, 4, 5, 6, 7, 8],
insert_in_order([1, 2, 3, 5, 6], 4) == [1, 2, 3, 4, 5, 6],
insert_in_order([1, 2, 3, 4, 5], 3) == [1, 2, 3, 4, 5],
}
}
This is a small transformation, but it matters in tight recursive loops and in code that executes frequently over large structures.
Choose cheaper representations
Every value a validator builds or compares costs execution units proportional to its shape. Picking a leaner representation is often a larger saving than any change to the logic around it.
Use simple(r) structures
Unless it's coming from the outside world (i.e. datum or redeemer), avoid constructing large records. Aiken is a language which operates directly on encoded objects (a.k.a. Data). This is handy when objects have been pre-constructed ahead of the script execution as it the case for datum, redeemers or the transaction itself.
Yet, constructing large records to carry context across multiple transaction elements will often come at a significant cost. So, prefer using functions with explicit arguments when you do not actually need to materialize an intermediate structure.
- Don't
- Do
- Bench
mem=19.53K · cpu=5.81M
type MultisigContext {
owner: VerificationKeyHash,
signatories: List<VerificationKeyHash>,
withdrawals: Pairs<VerificationKeyHash, Lovelace>,
}
// NOTE: The implementation is irrelevant.
fn verify_multisig(ctx: MultisigContext) {
or {
list.has(ctx.signatories, ctx.owner),
list.any(ctx.withdrawals, fn(Pair(vk, _)) { vk == ctx.owner }),
}
}
mem=14.12K · cpu=3.71M
// NOTE: The implementation is irrelevant.
fn verify_multisig(owner, signatories, withdrawals) {
or {
list.has(signatories, owner),
list.any(withdrawals, fn(Pair(vk, _)) { vk == owner }),
}
}
test baseline_dont() {
let ctx = MultisigContext {
owner: baseline_owner,
signatories: baseline_signatories,
withdrawals: baseline_withdrawals,
}
verify_multisig(ctx)
}
test baseline_do() {
verify_multisig(
baseline_owner,
baseline_signatories,
baseline_withdrawals,
)
}
In particular, if you can avoid it, do not construct Assets and prefer Dict or Pairs over Assets whenever possible.
Assets preserves two important invariants: it does not contain assets with null quantities or policies with empty assets. If you do not rely on these invariants, you can safely go down to Dict.
Dict preserves two important invariants: their keys are in ascending orders and contain no duplicate. If you do not rely on these invariants, you can safely go down to Pairs
Prefer Data equality over manual structural comparisons
Aiken programs operate over encoded Data, and comparing Data values directly is often surprisingly efficient. If two values are expected to match structurally, a raw equality check is almost always cheaper than reconstructing that logic manually.
This can be particularly helpful when working with datums that represent values or state snapshots.
The standard library already exposes useful helpers for this. For instance, assets.match can compare a runtime Assets against a Data representation while letting you parameterize how lovelace should be checked:
pub fn match(
left: Assets,
right: Data,
assert_lovelace: fn(Lovelace, Lovelace) -> Bool,
) -> Bool
The more general lesson is that if most of a structure should remain unchanged, it is often better to compare the unchanged parts directly and isolate only the parts that are expected to vary.
For instance, a powerful optimisation pattern is to quickly split a structure into:
- the part before the variable region,
- the variable region itself,
- the part after the variable region.
You can then compare the stable regions directly through data equality and only inspect the changing part in detail.
let input_tokens_before, input_tokens_at, input_tokens_after <- split_at(input.value, policy_id)
let output_tokens_before, output_tokens_at, output_tokens_after <- split_at(output.value, policy_id)
Then:
expect and {
(input_tokens_before == output_tokens_before)?,
(input_tokens_after == output_tokens_after)?,
(input_tokens_at != output_tokens_at)?,
}
This is often much cheaper than re-computing full semantic comparisons over complete Assets structures.
Use backpassing when returning more than one value
Returning large tuples or records is convenient, but it also means constructing intermediary values only to immediately destructure them again. In hot paths, that overhead can become noticeable.
Backpassing lets you thread the "continuation" directly through the function instead.
- Don't
- Do
- Bench
mem=63.84K · cpu=19.49M
// Construct and de-construct a 2-tuple on each pass
pub fn count_and_sum(self: List<Int>) -> (Int, Int) {
when self is {
[] -> (0, 0)
[head, ..tail] -> {
let (count, sum) = count_and_sum(tail)
(count + 1, sum + head)
}
}
}
mem=47.26K · cpu=12.69M
// Leverage back-passing to avoid needless tuple constructions
pub fn count_and_sum_ret(self: List<Int>, return: fn(Int, Int) -> result) -> result {
when self is {
[] -> return(0, 0)
[head, ..tail] -> {
let count, sum <- count_and_sum_ret(tail)
return(count + 1, sum + head)
}
}
}
test baseline_tuple() {
expect (0, 0) = count_and_sum([])
expect (3, 3) = count_and_sum([1, 1, 1])
expect (5, 15) = count_and_sum([1, 2, 3, 4, 5])
Void
}
test baseline_backpassing() {
expect 0, 0 <- count_and_sum_ret([])
expect 3, 3 <- count_and_sum_ret([1, 1, 1])
expect 5, 15 <- count_and_sum_ret([1, 2, 3, 4, 5])
Void
}
This style becomes even more useful in recursive code and stateful folds. It is also the reason helpers such as list.foldl2 and list.foldr2 are so valuable: they allow you to accumulate multiple pieces of state without repeatedly packaging and unpackaging them.
If backpassing is not an option, prefer Pair over 2-tuples
When you need to return exactly two values and backpassing would make the code less readable, Pair<a, b> is often slightly preferable to (a, b).
Both are ergonomic to access:
pair.1st/tuple.1stpair.2nd/tuple.2nd
But Pair integrates more naturally with dictionaries and pairs-based APIs, so it tends to compose better with the rest of the standard library.
This is not usually a game-changing optimisation, but it is a good default when dealing with key-value shaped data.
Lean more on ByteArrays
Byte arrays are extremely cheap compared to richer structured data. So, when cost is absolutely critical, one option is to give up some of the convenience of structured encodings and operate directly on bytes.
- Don't
- Do
pub type MyRedeemer {
key: ByteArray,
signature: ByteArray,
}
let MyRedeemer { key, signature } = redeemer
pub type MyRedeemer = ByteArray
let key = bytearray.slice(redeemer, 0, 31)
let signature = bytearray.slice(redeemer, 32, 95)
This comes with obvious trade-offs:
- less self-documenting code,
- more manual slicing and offset management,
- fewer type-level guarantees.
So it should only be used when the savings are worth the loss in readability and maintainability.
Search and recurse efficiently
Most validator cost is a traversal of transaction inputs, outputs, or a datum collection. How you write the recursion, and whether you exploit any ordering the data already has, sets what that traversal costs.
Use fast recursion for infallible searches
This is a more specific version of the fail fast strategy that applies to 'infallible searches'. This happens when looking for specific elements within a collection without any possible error recovery: if not present, then it's an error and the entire validator must fail.
Such a scenario is actually quite common in validators, especially when dealing with elements that are part of a protocol.
- Don't
- Do
- Bench
mem=12.15K · cpu=3.13M
// Repeatedly check for empty list
pub fn has(haystack: List<a>, needle: a) -> Bool {
when haystack is {
[] -> False
[head, ..tail] -> head == needle || has(tail, needle)
}
}
mem=9.56K · cpu=2.33M
// Fails anyway on empty list, value must be present.
pub fn has(haystack: List<a>, needle: a) -> Bool {
head_list(haystack) == needle || has(tail_list(haystack), needle)
}
test baseline() {
expect has(["alice", "bob", "carol"], "carol")
}
Favor binary searches over linear searches
It is quite common to have chains of multiple conditions which, when written in the most naive way can result in unnecessary evaluations. When conditions are somewhat equiprobable (i.e. there's no clear unbalance that one may be satisfied way more often than others), it may be useful to restructure and nest certain if/then/else to perform a binary search.
- Don't
- Do
- Bench
mem=46.98K · cpu=12.68M
// Linear search, not ideal.
fn mod32(i) {
if i < 32 { 0 }
else if i < 64 { 1 }
else if i < 96 { 2 }
else if i < 128 { 3 }
else if i < 160 { 4 }
else if i < 192 { 5 }
else if i < 224 { 6 }
else { 7 }
}
mem=37.06K · cpu=9.76M
// Binary search, more efficient and predictable.
fn mod32(i) {
if i < 128 {
if i < 64 {
if i < 32 { 0 } else { 1 }
} else {
if i < 96 { 2 } else { 3 }
}
} else {
if i < 192 {
if i < 160 { 4 } else { 5 }
} else {
if i < 224 { 6 } else { 7 }
}
}
}
test baseline() {
and {
mod32(15) == 0,
mod32(47) == 1,
mod32(89) == 2,
mod32(114) == 3,
mod32(147) == 4,
mod32(171) == 5,
mod32(200) == 6,
mod32(225) == 7,
}
}
In this example, we branch based on the value of some integer chosen between 0 and 255. The first form evaluates each condition one after the other, resulting in a linear search that will average at (n + 1) / 2 evaluations. So for n=7, that's an average of 4 evaluations.
The do example, however, arranges the conditions to reduce the amount of evaluations done at each pass. It performs a binary search which results in log2(n) evaluations. So for n=7, that's an average of 3 evaluations.
Moreover, the binary search has the benefit of being more predictable. In the previous example, it does not only average to 3 condition evaluations, it always evaluates 3 conditions per pass. Unlike the don't example, which sometimes evaluates one condition, sometimes three, sometimes seven, etc...
Unroll recursions
When a recursive function advances one step at a time, its convergence can sometimes be improved by manually unrolling the first few steps. This reduces the number of recursive calls needed in the common case.
- Don't
- Do
- Bench
mem=47.53K · cpu=12.74M
fn elem_at(elems: List<a>, at: Int) -> a {
if at <= 0 {
builtin.head_list(elems)
} else {
elem_at(builtin.tail_list(elems), at - 1)
}
}
mem=35.01K · cpu=9.70M
fn elem_at(elems: List<a>, at: Int) -> a {
if at >= 2 {
elem_at(builtin.tail_list(builtin.tail_list(elems)), at - 2)
} else {
builtin.head_list(if at == 1 { builtin.tail_list(elems) } else { elems })
}
}
test baseline() {
and {
elem_at([1], 0) == 1,
elem_at([1, 2, 3, 4, 5], 0) == 1,
elem_at([1, 2, 3, 4, 5], 4) == 5,
elem_at([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9) == 10,
}
}
This sort of transformation is most useful for small, performance-critical helpers that get called repeatedly.
Write tail-recursive functions
The Plutus VM usually behaves better with tail-recursive functions, especially when working with bytes and accumulators. So when you can express a function as a loop with an explicit accumulator, prefer that form.
- Don't
- Do
- Bench
mem=80.36K · cpu=21.83M
fn fib(n: Int) -> Int {
if n <= 1 { 1 }
else { fib(n - 1) + fib(n - 2) }
}
mem=49.98K · cpu=12.60M
fn fib(n: Int) -> Int {
do_fib(1, 1, n)
}
fn do_fib(last: Int, current: Int, n: Int) -> Int {
if n <= 1 { current }
else { do_fib(current, current + last, n - 1) }
}
test baseline() {
and {
fib(0) == 1,
fib(1) == 1,
fib(2) == 2,
fib(3) == 3,
fib(4) == 5,
fib(5) == 8,
}
}
The tail-recursive version makes the control flow more explicit and typically avoids building up deferred work across calls.
This pattern is especially relevant for:
- folds,
- list traversals,
- byte processing,
- numeric loops.