Conditional Actions
Conditional actions allow a route to execute different sets of actions based on
runtime conditions. They use an if/else syntax within the action list.
Syntax
if condition => [
// actions when true
] else [
// actions when false
]
The else branch is optional:
if condition => [
// actions when true
]
Basic Usage
Execute an action only when a condition is met:
routes {
withdraw(amount: U256) => [
if amount > 0 => [
~> msg::sender with { value: amount }
]
]
}
If/Else
Choose between two action sequences:
routes {
process(amount: U256) => [
if amount >= m_threshold => [
LargeTransfer(amount) ~> m_compliance,
~> msg::sender with { value: amount }
] else [
~> msg::sender with { value: amount }
]
]
}
Conditions
The condition can be any boolean expression:
Comparisons
if m_balance >= amount => [
~> recipient with { value: amount }
]
Macro Calls
if @is_owner() => [
~> m_treasury with { value: m_balance }
]
Member State
if m_status == Status::Active => [
Process(data) ~> m_processor
] else [
Queue(data) ~> m_queue
]
Compound Conditions
if amount > 0 && m_balance >= amount => [
~> msg::sender with { value: amount }
]
Nested Conditionals
Conditional actions can be nested for multi-branch logic:
routes {
categorize(score: u64) => [
if score >= 90 => [
Award("gold") ~> m_rewards
] else [
if score >= 70 => [
Award("silver") ~> m_rewards
] else [
Award("bronze") ~> m_rewards
]
]
]
}
Conditional Sends
A common pattern is conditionally sending a refund:
routes {
bid()
where msg::value > m_highest_bid : throw 100
=> [
if m_highest_bid > 0 => [
~> m_highest_bidder with { value: m_highest_bid }
]
]
}
This refunds the previous highest bidder only if there was a previous bid.
Conditional Deploy
Deploy an entity only under certain conditions:
routes {
ensure_vault(user: address) => [
if m_vaults.exists(user) == false => [
deploy UserVault(user) with { value: 1_000_000 }
]
]
}
Conditionals with Let Bindings
Let bindings can precede conditional actions:
routes {
distribute(total: U256) => [
let fee = total * 3 / 100;
let net = total - fee;
if fee > 0 => [
~> m_treasury with { value: fee }
],
~> m_recipient with { value: net }
]
}
Complete Example
entity Escrow {
routes {
resolve(approved: bool)
where msg::sender == m_arbiter : throw 200
=> [
if approved => [
~> m_seller with { value: m_amount },
Resolved(m_deal_id, true) ~> m_logger
] else [
~> m_buyer with { value: m_amount },
Resolved(m_deal_id, false) ~> m_logger
]
]
}
}