Workflows
What this deployment runs, from the demo's configuration. A workflow's id is the hash of its WASM binary together with its configuration, so the same binary with another configuration is another workflow, and a receiver contract must allow each id it accepts reports from.
BTC / USD price feed
- id
- 6ded610773957c3179f49547d340152bbceb35fef6abd554a3913c85193b39cf
- nodes running it
- 7 of 7 (by their status.json)
- schedule
- every 5 min 00 s
- receiver
- 0xD181DFD5C4AEa7E28cD4A4F685A429910deD4BD6
- decimals
- 8
- built from
workflows/examples/btc-price-feed
Every node asks four exchanges for the price and takes the median of the answers; the network agrees on the median of the nodes' views and delivers it to a contract.
Source (src/lib.rs without its tests)
//! Puts a price from several exchanges on chain.
//!
//! On a schedule, every node asks each configured source for the price and
//! takes the median of the answers it got, so that one exchange being down
//! or wrong does not move that node's view. The network then agrees on the
//! median of the nodes' views, so that up to two nodes being wrong do not
//! move the result, and delivers it to a contract.
//!
//! The workflow is configured with lines of `key=value`:
//!
//! ```text
//! schedule=0 */5 * * * *
//! chain_id=84532
//! receiver=0x0000000000000000000000000000000000000000
//! decimals=8
//! min_sources=2
//! source=https://api.coinbase.com/v2/prices/BTC-USD/spot data.amount
//! source=https://api.kraken.com/0/public/Ticker?pair=XBTUSD result.XXBTZUSD.c.0
//! ```
//!
//! A source is a URL that answers with JSON and, after a space, where the
//! price is in the answer: object keys and array positions separated by
//! dots. The price may be a JSON string or number. `decimals` is how many
//! decimal places the on-chain integer keeps (8 is what price feeds
//! commonly use); further places are cut off, not rounded. A node that gets
//! fewer than `min_sources` prices has no view for that round.
//!
//! The receiver gets `abi.encode(int256 price, uint64 observedAt)`, which is
//! what `LatestValueReceiver` in `contracts/src/examples` expects.
//! `observedAt` is the schedule time in seconds, the same on every node.
//!
//! Nothing here is specific to Bitcoin but the example configuration.
use cxyz_sdk::evm;
use cxyz_sdk::prelude::*;
/// Used when the configuration names no schedule: every five minutes.
pub const DEFAULT_SCHEDULE: &str = "0 */5 * * * *";
/// More decimal places than this do not fit a price in an `i64`.
const MAX_DECIMALS: u32 = 12;
struct Source {
url: String,
/// Where the price is in the answer.
path: Vec<String>,
}
struct Config {
chain_id: u64,
receiver: [u8; 20],
decimals: u32,
min_sources: usize,
sources: Vec<Source>,
}
/// Every value given for `key`, in order.
fn settings<'a>(text: &'a str, key: &str) -> impl Iterator<Item = &'a str> {
text.lines()
.filter_map(|line| line.split_once('='))
.filter(move |(name, _)| name.trim() == key)
.map(|(_, value)| value.trim())
}
impl Config {
fn parse(config: &[u8]) -> Result<Self, WorkflowError> {
let text = core::str::from_utf8(config)
.map_err(|_| WorkflowError::new("the configuration is not text"))?;
let setting = |key: &str| {
settings(text, key)
.next()
.ok_or_else(|| WorkflowError::new(format!("the configuration has no `{key}`")))
};
let number = |key: &str| {
setting(key)?
.parse::<u64>()
.map_err(|_| WorkflowError::new(format!("`{key}` is not a number")))
};
let sources = settings(text, "source")
.map(|source| {
let (url, path) = source.split_once(' ').ok_or_else(|| {
WorkflowError::new(format!("source `{source}` does not say where the price is"))
})?;
Ok(Source {
url: url.to_owned(),
path: path.trim().split('.').map(str::to_owned).collect(),
})
})
.collect::<Result<Vec<_>, WorkflowError>>()?;
let decimals = number("decimals")? as u32;
if decimals > MAX_DECIMALS {
return Err(WorkflowError::new(format!(
"`decimals` is more than {MAX_DECIMALS}"
)));
}
let min_sources = number("min_sources")? as usize;
if min_sources == 0 || min_sources > sources.len() {
return Err(WorkflowError::new(format!(
"`min_sources` is {min_sources} with {} sources",
sources.len()
)));
}
Ok(Self {
chain_id: number("chain_id")?,
receiver: evm::address(setting("receiver")?)?,
decimals,
min_sources,
sources,
})
}
}
/// A decimal number as an integer with `decimals` decimal places, without
/// ever going through floating point: `"63690.125"` with 2 places is
/// `6369012`. `None` for anything that is not a plain positive decimal.
fn fixed_point(text: &str, decimals: u32) -> Option<i64> {
let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
if whole.is_empty()
|| !whole
.bytes()
.chain(fraction.bytes())
.all(|b| b.is_ascii_digit())
{
return None;
}
let mut value: i64 = whole.parse().ok()?;
let mut digits = fraction.bytes();
for _ in 0..decimals {
let digit = digits.next().map_or(0, |digit| i64::from(digit - b'0'));
value = value.checked_mul(10)?.checked_add(digit)?;
}
(value > 0).then_some(value)
}
/// The price in one source's answer.
fn price_in(body: &str, path: &[String], decimals: u32) -> Result<i64, WorkflowError> {
let answer: serde_json::Value =
serde_json::from_str(body).map_err(|_| WorkflowError::new("the answer is not JSON"))?;
let mut at = &answer;
for step in path {
at = match at {
serde_json::Value::Array(items) => step
.parse::<usize>()
.ok()
.and_then(|index| items.get(index)),
other => other.get(step),
}
.ok_or_else(|| WorkflowError::new(format!("the answer has no `{step}`")))?;
}
let text = match at {
serde_json::Value::String(text) => text.clone(),
serde_json::Value::Number(number) => number.to_string(),
_ => return Err(WorkflowError::new("the price is neither text nor a number")),
};
fixed_point(text.trim(), decimals)
.ok_or_else(|| WorkflowError::new(format!("`{text}` is not a price")))
}
/// The middle of the prices; of an even number, halfway between the two in
/// the middle. `prices` must not be empty.
fn median(mut prices: Vec<i64>) -> i64 {
prices.sort_unstable();
let middle = prices.len() / 2;
if prices.len() % 2 == 1 {
prices[middle]
} else {
// Both are positive and far below the limit, so this cannot overflow.
(prices[middle - 1] + prices[middle]) / 2
}
}
fn on_tick(ctx: &mut Context, event: CronEvent) -> HandlerResult {
let config = Config::parse(ctx.config())?;
let (decimals, min_sources) = (config.decimals, config.min_sources);
let sources = config.sources;
let agreed = ctx.observe(Aggregation::Median, move |node| {
// Every source is asked, whatever the ones before it answered: all
// nodes must make the same calls in the same order.
let mut prices = Vec::new();
let mut failures = Vec::new();
for source in &sources {
let price = node
.http_get(&source.url)
.and_then(|response| price_in(response.text()?, &source.path, decimals));
match price {
Ok(price) => prices.push(price),
Err(error) => failures.push(error.to_string()),
}
}
if prices.len() < min_sources {
return Err(WorkflowError::new(format!(
"only {} of {} sources answered with a price ({})",
prices.len(),
sources.len(),
failures.join("; ")
)));
}
Ok(Value::Int(median(prices)))
})?;
let Value::Int(price) = agreed else {
return Err(WorkflowError::new("the agreed price is not an integer"));
};
ctx.log(format!("agreed on {price}"));
// The schedule time, not a clock: it is the same on every node.
let observed_at = event.scheduled_at.as_millis() / 1_000;
let payload = [evm::int256(price), evm::uint256(observed_at)].concat();
ctx.write_report(config.chain_id, config.receiver, payload)?;
Ok(Value::Int(price))
}
/// The schedule comes from the configuration. A configuration that cannot
/// be read still gives a workflow, whose every run fails saying why.
pub fn workflow(config: &[u8]) -> Workflow {
let schedule = core::str::from_utf8(config)
.ok()
.and_then(|text| settings(text, "schedule").next())
.unwrap_or(DEFAULT_SCHEDULE);
Workflow::new().on_cron(schedule, on_tick)
}
cxyz_sdk::export_workflow!(workflow);Secret reaches an API from the enclave
- id
- 494f4397a88b040ca3b2cb62a57a823d1022d024b063588b06cc11eb9e8f5578
- nodes running it
- 7 of 7 (by their status.json)
- built from
workflows/examples/echo-check
A confidential handler runs inside the enclave, decrypts an API token there, sends it to a service that echoes it back, and lets out only whether the service saw exactly the secret.
Source (src/lib.rs without its tests)
//! Shows that a secret reaches an API from inside an enclave, using a public
//! test service that echoes the credential it was sent.
//!
//! The confidential handler sends the secret as a bearer token to a service
//! such as `https://httpbin.org/bearer`, which answers with the token it
//! received. Inside the enclave the handler compares that with the secret
//! and lets only the verdict out: the HTTP status and whether the service
//! saw exactly the secret. The secret itself never leaves.
//!
//! Configuration, as for `private-api`: `url=...` and `api_key=<hex>`, the
//! secret encrypted under the name `api_key`. An optional `schedule=...`
//! replaces the default of every ten seconds, which is too often for a
//! public test service outside of a short demonstration.
use std::collections::BTreeMap;
use cxyz_sdk::prelude::*;
pub const SCHEDULE: &str = "*/10 * * * * *";
fn setting<'a>(config: &'a [u8], key: &str) -> Result<&'a str, WorkflowError> {
core::str::from_utf8(config)
.map_err(|_| WorkflowError::new("the configuration is not text"))?
.lines()
.filter_map(|line| line.split_once('='))
.find(|(name, _)| name.trim() == key)
.map(|(_, value)| value.trim())
.ok_or_else(|| WorkflowError::new(format!("the configuration has no `{key}`")))
}
fn from_hex(text: &str) -> Result<Vec<u8>, WorkflowError> {
let invalid = || WorkflowError::new("`api_key` is not hex");
if !text.len().is_multiple_of(2) || !text.is_ascii() {
return Err(invalid());
}
text.as_bytes()
.chunks(2)
.map(|pair| {
let pair = core::str::from_utf8(pair).map_err(|_| invalid())?;
u8::from_str_radix(pair, 16).map_err(|_| invalid())
})
.collect()
}
fn on_tick(ctx: &mut Context, _event: CronEvent) -> HandlerResult {
let secret = from_hex(setting(ctx.config(), "api_key")?)?;
ctx.confidential("check", Value::Null, vec![secret])
}
fn check(ctx: &mut EnclaveContext, _input: Value) -> HandlerResult {
let url = setting(ctx.config(), "url")?.to_owned();
let secret = String::from_utf8(ctx.secret("api_key")?)
.map_err(|_| WorkflowError::new("the secret is not text"))?;
let response =
ctx.http(HttpRequest::get(&url).header("Authorization", &format!("Bearer {secret}")))?;
let echoed = core::str::from_utf8(&response.body).is_ok_and(|body| body.contains(&secret));
Ok(Value::Map(BTreeMap::from([
("status".to_owned(), Value::Int(response.status.into())),
("service_saw_the_secret".to_owned(), Value::Bool(echoed)),
])))
}
pub fn workflow() -> Workflow {
Workflow::new()
.on_cron(SCHEDULE, on_tick)
.confidential("check", check)
}
/// The workflow on the schedule its configuration asks for, if it does.
pub fn configured(config: &[u8]) -> Workflow {
match setting(config, "schedule") {
Ok(schedule) => Workflow::new()
.on_cron(schedule, on_tick)
.confidential("check", check),
Err(_) => workflow(),
}
}
cxyz_sdk::export_workflow!(configured);Example workflows in the repository
Embedded when this app was built. Not every example is deployed.
workflows/examples/btc-price-feed
Puts a price from several exchanges on chain.
Source
//! Puts a price from several exchanges on chain.
//!
//! On a schedule, every node asks each configured source for the price and
//! takes the median of the answers it got, so that one exchange being down
//! or wrong does not move that node's view. The network then agrees on the
//! median of the nodes' views, so that up to two nodes being wrong do not
//! move the result, and delivers it to a contract.
//!
//! The workflow is configured with lines of `key=value`:
//!
//! ```text
//! schedule=0 */5 * * * *
//! chain_id=84532
//! receiver=0x0000000000000000000000000000000000000000
//! decimals=8
//! min_sources=2
//! source=https://api.coinbase.com/v2/prices/BTC-USD/spot data.amount
//! source=https://api.kraken.com/0/public/Ticker?pair=XBTUSD result.XXBTZUSD.c.0
//! ```
//!
//! A source is a URL that answers with JSON and, after a space, where the
//! price is in the answer: object keys and array positions separated by
//! dots. The price may be a JSON string or number. `decimals` is how many
//! decimal places the on-chain integer keeps (8 is what price feeds
//! commonly use); further places are cut off, not rounded. A node that gets
//! fewer than `min_sources` prices has no view for that round.
//!
//! The receiver gets `abi.encode(int256 price, uint64 observedAt)`, which is
//! what `LatestValueReceiver` in `contracts/src/examples` expects.
//! `observedAt` is the schedule time in seconds, the same on every node.
//!
//! Nothing here is specific to Bitcoin but the example configuration.
use cxyz_sdk::evm;
use cxyz_sdk::prelude::*;
/// Used when the configuration names no schedule: every five minutes.
pub const DEFAULT_SCHEDULE: &str = "0 */5 * * * *";
/// More decimal places than this do not fit a price in an `i64`.
const MAX_DECIMALS: u32 = 12;
struct Source {
url: String,
/// Where the price is in the answer.
path: Vec<String>,
}
struct Config {
chain_id: u64,
receiver: [u8; 20],
decimals: u32,
min_sources: usize,
sources: Vec<Source>,
}
/// Every value given for `key`, in order.
fn settings<'a>(text: &'a str, key: &str) -> impl Iterator<Item = &'a str> {
text.lines()
.filter_map(|line| line.split_once('='))
.filter(move |(name, _)| name.trim() == key)
.map(|(_, value)| value.trim())
}
impl Config {
fn parse(config: &[u8]) -> Result<Self, WorkflowError> {
let text = core::str::from_utf8(config)
.map_err(|_| WorkflowError::new("the configuration is not text"))?;
let setting = |key: &str| {
settings(text, key)
.next()
.ok_or_else(|| WorkflowError::new(format!("the configuration has no `{key}`")))
};
let number = |key: &str| {
setting(key)?
.parse::<u64>()
.map_err(|_| WorkflowError::new(format!("`{key}` is not a number")))
};
let sources = settings(text, "source")
.map(|source| {
let (url, path) = source.split_once(' ').ok_or_else(|| {
WorkflowError::new(format!("source `{source}` does not say where the price is"))
})?;
Ok(Source {
url: url.to_owned(),
path: path.trim().split('.').map(str::to_owned).collect(),
})
})
.collect::<Result<Vec<_>, WorkflowError>>()?;
let decimals = number("decimals")? as u32;
if decimals > MAX_DECIMALS {
return Err(WorkflowError::new(format!(
"`decimals` is more than {MAX_DECIMALS}"
)));
}
let min_sources = number("min_sources")? as usize;
if min_sources == 0 || min_sources > sources.len() {
return Err(WorkflowError::new(format!(
"`min_sources` is {min_sources} with {} sources",
sources.len()
)));
}
Ok(Self {
chain_id: number("chain_id")?,
receiver: evm::address(setting("receiver")?)?,
decimals,
min_sources,
sources,
})
}
}
/// A decimal number as an integer with `decimals` decimal places, without
/// ever going through floating point: `"63690.125"` with 2 places is
/// `6369012`. `None` for anything that is not a plain positive decimal.
fn fixed_point(text: &str, decimals: u32) -> Option<i64> {
let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
if whole.is_empty()
|| !whole
.bytes()
.chain(fraction.bytes())
.all(|b| b.is_ascii_digit())
{
return None;
}
let mut value: i64 = whole.parse().ok()?;
let mut digits = fraction.bytes();
for _ in 0..decimals {
let digit = digits.next().map_or(0, |digit| i64::from(digit - b'0'));
value = value.checked_mul(10)?.checked_add(digit)?;
}
(value > 0).then_some(value)
}
/// The price in one source's answer.
fn price_in(body: &str, path: &[String], decimals: u32) -> Result<i64, WorkflowError> {
let answer: serde_json::Value =
serde_json::from_str(body).map_err(|_| WorkflowError::new("the answer is not JSON"))?;
let mut at = &answer;
for step in path {
at = match at {
serde_json::Value::Array(items) => step
.parse::<usize>()
.ok()
.and_then(|index| items.get(index)),
other => other.get(step),
}
.ok_or_else(|| WorkflowError::new(format!("the answer has no `{step}`")))?;
}
let text = match at {
serde_json::Value::String(text) => text.clone(),
serde_json::Value::Number(number) => number.to_string(),
_ => return Err(WorkflowError::new("the price is neither text nor a number")),
};
fixed_point(text.trim(), decimals)
.ok_or_else(|| WorkflowError::new(format!("`{text}` is not a price")))
}
/// The middle of the prices; of an even number, halfway between the two in
/// the middle. `prices` must not be empty.
fn median(mut prices: Vec<i64>) -> i64 {
prices.sort_unstable();
let middle = prices.len() / 2;
if prices.len() % 2 == 1 {
prices[middle]
} else {
// Both are positive and far below the limit, so this cannot overflow.
(prices[middle - 1] + prices[middle]) / 2
}
}
fn on_tick(ctx: &mut Context, event: CronEvent) -> HandlerResult {
let config = Config::parse(ctx.config())?;
let (decimals, min_sources) = (config.decimals, config.min_sources);
let sources = config.sources;
let agreed = ctx.observe(Aggregation::Median, move |node| {
// Every source is asked, whatever the ones before it answered: all
// nodes must make the same calls in the same order.
let mut prices = Vec::new();
let mut failures = Vec::new();
for source in &sources {
let price = node
.http_get(&source.url)
.and_then(|response| price_in(response.text()?, &source.path, decimals));
match price {
Ok(price) => prices.push(price),
Err(error) => failures.push(error.to_string()),
}
}
if prices.len() < min_sources {
return Err(WorkflowError::new(format!(
"only {} of {} sources answered with a price ({})",
prices.len(),
sources.len(),
failures.join("; ")
)));
}
Ok(Value::Int(median(prices)))
})?;
let Value::Int(price) = agreed else {
return Err(WorkflowError::new("the agreed price is not an integer"));
};
ctx.log(format!("agreed on {price}"));
// The schedule time, not a clock: it is the same on every node.
let observed_at = event.scheduled_at.as_millis() / 1_000;
let payload = [evm::int256(price), evm::uint256(observed_at)].concat();
ctx.write_report(config.chain_id, config.receiver, payload)?;
Ok(Value::Int(price))
}
/// The schedule comes from the configuration. A configuration that cannot
/// be read still gives a workflow, whose every run fails saying why.
pub fn workflow(config: &[u8]) -> Workflow {
let schedule = core::str::from_utf8(config)
.ok()
.and_then(|text| settings(text, "schedule").next())
.unwrap_or(DEFAULT_SCHEDULE);
Workflow::new().on_cron(schedule, on_tick)
}
cxyz_sdk::export_workflow!(workflow);workflows/examples/cross-chain-sync
Carries a value from one chain to another: when a contract on the source chain announces a new value, the network reads it there and delivers it to a contract on the target chain.
Source
//! Carries a value from one chain to another: when a contract on the source
//! chain announces a new value, the network reads it there and delivers it
//! to a contract on the target chain.
//!
//! This one works with `ValueSource` and `LatestValueReceiver` in
//! `contracts/src/examples`. The workflow is configured with four lines:
//!
//! ```text
//! source_chain_id=1
//! source=0x0000000000000000000000000000000000000000
//! target_chain_id=42161
//! receiver=0x0000000000000000000000000000000000000000
//! ```
//!
//! What triggers the workflow depends on that configuration, so the builder
//! takes it.
use cxyz_sdk::evm;
use cxyz_sdk::prelude::*;
#[derive(Clone, Copy)]
struct Config {
source_chain_id: u64,
source: [u8; 20],
target_chain_id: u64,
receiver: [u8; 20],
}
impl Config {
fn parse(config: &[u8]) -> Result<Self, WorkflowError> {
let text = core::str::from_utf8(config)
.map_err(|_| WorkflowError::new("the configuration is not text"))?;
let setting = |key: &str| {
text.lines()
.filter_map(|line| line.split_once('='))
.find(|(name, _)| name.trim() == key)
.map(|(_, value)| value.trim())
.ok_or_else(|| WorkflowError::new(format!("the configuration has no `{key}`")))
};
let number = |key: &str| {
setting(key)?
.parse::<u64>()
.map_err(|_| WorkflowError::new(format!("`{key}` is not a number")))
};
Ok(Self {
source_chain_id: number("source_chain_id")?,
source: evm::address(setting("source")?)?,
target_chain_id: number("target_chain_id")?,
receiver: evm::address(setting("receiver")?)?,
})
}
}
fn on_value_set(ctx: &mut Context, config: Config, log: EvmLog) -> HandlerResult {
// ValueSet(uint256 value, uint64 at): neither is indexed, so both are in
// the data.
let at = evm::word_as_u64(&log.data, 1)?;
// Read the value at the block of the event instead of taking it from the
// event: the nodes then agree on the contract's state, not only on a log.
let output = ctx.evm_read_at(
config.source_chain_id,
config.source,
evm::selector("value()").to_vec(),
log.block_number,
)?;
let value = evm::word_as_u64(&output, 0)?;
ctx.log(format!("value {value} set at block {}", log.block_number));
ctx.write_report(
config.target_chain_id,
config.receiver,
[evm::uint256(value), evm::uint256(at)].concat(),
)?;
i64::try_from(value)
.map(Value::Int)
.map_err(|_| WorkflowError::new("the value does not fit"))
}
/// A workflow whose configuration cannot be read has no handlers, so a node
/// given a bad configuration runs nothing rather than something unintended.
pub fn workflow(config: &[u8]) -> Workflow {
let Ok(config) = Config::parse(config) else {
return Workflow::new();
};
Workflow::new().on_evm_log(
config.source_chain_id,
config.source,
evm::event_topic("ValueSet(uint256,uint64)"),
move |ctx, log| on_value_set(ctx, config, log),
)
}
cxyz_sdk::export_workflow!(workflow);workflows/examples/echo-check
Shows that a secret reaches an API from inside an enclave, using a public test service that echoes the credential it was sent.
Source
//! Shows that a secret reaches an API from inside an enclave, using a public
//! test service that echoes the credential it was sent.
//!
//! The confidential handler sends the secret as a bearer token to a service
//! such as `https://httpbin.org/bearer`, which answers with the token it
//! received. Inside the enclave the handler compares that with the secret
//! and lets only the verdict out: the HTTP status and whether the service
//! saw exactly the secret. The secret itself never leaves.
//!
//! Configuration, as for `private-api`: `url=...` and `api_key=<hex>`, the
//! secret encrypted under the name `api_key`. An optional `schedule=...`
//! replaces the default of every ten seconds, which is too often for a
//! public test service outside of a short demonstration.
use std::collections::BTreeMap;
use cxyz_sdk::prelude::*;
pub const SCHEDULE: &str = "*/10 * * * * *";
fn setting<'a>(config: &'a [u8], key: &str) -> Result<&'a str, WorkflowError> {
core::str::from_utf8(config)
.map_err(|_| WorkflowError::new("the configuration is not text"))?
.lines()
.filter_map(|line| line.split_once('='))
.find(|(name, _)| name.trim() == key)
.map(|(_, value)| value.trim())
.ok_or_else(|| WorkflowError::new(format!("the configuration has no `{key}`")))
}
fn from_hex(text: &str) -> Result<Vec<u8>, WorkflowError> {
let invalid = || WorkflowError::new("`api_key` is not hex");
if !text.len().is_multiple_of(2) || !text.is_ascii() {
return Err(invalid());
}
text.as_bytes()
.chunks(2)
.map(|pair| {
let pair = core::str::from_utf8(pair).map_err(|_| invalid())?;
u8::from_str_radix(pair, 16).map_err(|_| invalid())
})
.collect()
}
fn on_tick(ctx: &mut Context, _event: CronEvent) -> HandlerResult {
let secret = from_hex(setting(ctx.config(), "api_key")?)?;
ctx.confidential("check", Value::Null, vec![secret])
}
fn check(ctx: &mut EnclaveContext, _input: Value) -> HandlerResult {
let url = setting(ctx.config(), "url")?.to_owned();
let secret = String::from_utf8(ctx.secret("api_key")?)
.map_err(|_| WorkflowError::new("the secret is not text"))?;
let response =
ctx.http(HttpRequest::get(&url).header("Authorization", &format!("Bearer {secret}")))?;
let echoed = core::str::from_utf8(&response.body).is_ok_and(|body| body.contains(&secret));
Ok(Value::Map(BTreeMap::from([
("status".to_owned(), Value::Int(response.status.into())),
("service_saw_the_secret".to_owned(), Value::Bool(echoed)),
])))
}
pub fn workflow() -> Workflow {
Workflow::new()
.on_cron(SCHEDULE, on_tick)
.confidential("check", check)
}
/// The workflow on the schedule its configuration asks for, if it does.
pub fn configured(config: &[u8]) -> Workflow {
match setting(config, "schedule") {
Ok(schedule) => Workflow::new()
.on_cron(schedule, on_tick)
.confidential("check", check),
Err(_) => workflow(),
}
}
cxyz_sdk::export_workflow!(configured);workflows/examples/hello-cron
The smallest useful workflow: every ten seconds, log a line and return the time the tick was scheduled for.
Source
//! The smallest useful workflow: every ten seconds, log a line and return the
//! time the tick was scheduled for.
use std::collections::BTreeMap;
use cxyz_sdk::prelude::*;
pub const SCHEDULE: &str = "*/10 * * * * *";
fn on_tick(ctx: &mut Context, event: CronEvent) -> HandlerResult {
let scheduled_at_ms = event.scheduled_at.as_millis();
ctx.log(format!("tick scheduled at {scheduled_at_ms} ms"));
Ok(Value::Map(BTreeMap::from([(
"scheduled_at_ms".to_owned(),
Value::Int(scheduled_at_ms as i64),
)])))
}
pub fn workflow() -> Workflow {
Workflow::new().on_cron(SCHEDULE, on_tick)
}
cxyz_sdk::export_workflow!(workflow);workflows/examples/keeper
A keeper: on a schedule, checks a condition on chain and, when it holds, has the network tell the contract to act.
Source
//! A keeper: on a schedule, checks a condition on chain and, when it holds,
//! has the network tell the contract to act.
//!
//! This one works with `HarvestKeeper` in `contracts/src/examples`: it reads
//! `needsHarvest()` and reports to the contract when a harvest is due. The
//! workflow is configured with two lines:
//!
//! ```text
//! chain_id=1
//! target=0x0000000000000000000000000000000000000000
//! ```
use cxyz_sdk::evm;
use cxyz_sdk::prelude::*;
pub const SCHEDULE: &str = "*/10 * * * * *";
struct Config {
chain_id: u64,
target: [u8; 20],
}
impl Config {
fn parse(config: &[u8]) -> Result<Self, WorkflowError> {
let text = core::str::from_utf8(config)
.map_err(|_| WorkflowError::new("the configuration is not text"))?;
let setting = |key: &str| {
text.lines()
.filter_map(|line| line.split_once('='))
.find(|(name, _)| name.trim() == key)
.map(|(_, value)| value.trim())
.ok_or_else(|| WorkflowError::new(format!("the configuration has no `{key}`")))
};
Ok(Self {
chain_id: setting("chain_id")?
.parse()
.map_err(|_| WorkflowError::new("`chain_id` is not a number"))?,
target: evm::address(setting("target")?)?,
})
}
}
fn on_tick(ctx: &mut Context, _event: CronEvent) -> HandlerResult {
let config = Config::parse(ctx.config())?;
let read = ctx.evm_read(
config.chain_id,
config.target,
evm::selector("needsHarvest()").to_vec(),
)?;
if !evm::word_as_bool(&read.output, 0)? {
ctx.log(format!("nothing to harvest at block {}", read.block_number));
return Ok(Value::Bool(false));
}
// The contract acts on the report's arrival; the block the condition was
// seen at is included for whoever reads the transaction later.
ctx.log(format!("harvest due at block {}", read.block_number));
ctx.write_report(
config.chain_id,
config.target,
evm::uint256(read.block_number).to_vec(),
)?;
Ok(Value::Bool(true))
}
pub fn workflow() -> Workflow {
Workflow::new().on_cron(SCHEDULE, on_tick)
}
cxyz_sdk::export_workflow!(workflow);workflows/examples/price-feed
Puts a price on chain: every node fetches it from an API, the network agrees on the median, and the result is delivered to a contract.
Source
//! Puts a price on chain: every node fetches it from an API, the network
//! agrees on the median, and the result is delivered to a contract.
//!
//! The workflow is configured with three lines:
//!
//! ```text
//! url=https://api.example.com/price
//! chain_id=1
//! receiver=0x0000000000000000000000000000000000000000
//! ```
//!
//! The API must answer with an integer, such as a price in cents. The
//! receiver gets `abi.encode(int256 price, uint64 observedAt)`, which is what
//! `LatestValueReceiver` in `contracts/src/examples` expects.
use cxyz_sdk::evm;
use cxyz_sdk::prelude::*;
pub const SCHEDULE: &str = "*/10 * * * * *";
struct Config {
url: String,
chain_id: u64,
receiver: [u8; 20],
}
impl Config {
fn parse(config: &[u8]) -> Result<Self, WorkflowError> {
let text = core::str::from_utf8(config)
.map_err(|_| WorkflowError::new("the configuration is not text"))?;
let setting = |key: &str| {
text.lines()
.filter_map(|line| line.split_once('='))
.find(|(name, _)| name.trim() == key)
.map(|(_, value)| value.trim())
.ok_or_else(|| WorkflowError::new(format!("the configuration has no `{key}`")))
};
Ok(Self {
url: setting("url")?.to_owned(),
chain_id: setting("chain_id")?
.parse()
.map_err(|_| WorkflowError::new("`chain_id` is not a number"))?,
receiver: evm::address(setting("receiver")?)?,
})
}
}
fn on_tick(ctx: &mut Context, event: CronEvent) -> HandlerResult {
let config = Config::parse(ctx.config())?;
let url = config.url;
let agreed = ctx.observe(Aggregation::Median, move |node| {
let response = node.http_get(&url)?;
let price: i64 = response
.text()?
.trim()
.parse()
.map_err(|_| WorkflowError::new("the feed did not answer with an integer"))?;
Ok(Value::Int(price))
})?;
let Value::Int(price) = agreed else {
return Err(WorkflowError::new("the agreed price is not an integer"));
};
ctx.log(format!("agreed on {price}"));
// The schedule time, not a clock: it is the same on every node.
let observed_at = event.scheduled_at.as_millis() / 1_000;
let payload = [evm::int256(price), evm::uint256(observed_at)].concat();
ctx.write_report(config.chain_id, config.receiver, payload)?;
Ok(Value::Int(price))
}
pub fn workflow() -> Workflow {
Workflow::new().on_cron(SCHEDULE, on_tick)
}
cxyz_sdk::export_workflow!(workflow);workflows/examples/private-api
Calls an API with a credential no node may see.
Source
//! Calls an API with a credential no node may see.
//!
//! On a schedule, the workflow has its confidential handler run inside an
//! enclave. Only there is the API key decrypted and used; what comes back
//! out is the one number the workflow needs. The nodes agree on that number.
//!
//! The workflow is configured with two lines. `api_key` is the key encrypted
//! to the network's public key, as hex, under the label `secret_label` gives
//! for this workflow's code and the name `api_key`:
//!
//! ```text
//! url=https://api.example.com/balance
//! api_key=6a1f...
//! ```
//!
//! The API must answer with an integer.
use cxyz_sdk::prelude::*;
pub const SCHEDULE: &str = "*/10 * * * * *";
struct Config {
url: String,
api_key: Vec<u8>,
}
impl Config {
fn parse(config: &[u8]) -> Result<Self, WorkflowError> {
let text = core::str::from_utf8(config)
.map_err(|_| WorkflowError::new("the configuration is not text"))?;
let setting = |key: &str| {
text.lines()
.filter_map(|line| line.split_once('='))
.find(|(name, _)| name.trim() == key)
.map(|(_, value)| value.trim())
.ok_or_else(|| WorkflowError::new(format!("the configuration has no `{key}`")))
};
Ok(Self {
url: setting("url")?.to_owned(),
api_key: from_hex(setting("api_key")?)?,
})
}
}
fn from_hex(text: &str) -> Result<Vec<u8>, WorkflowError> {
let invalid = || WorkflowError::new("`api_key` is not hex");
if !text.len().is_multiple_of(2) || !text.is_ascii() {
return Err(invalid());
}
text.as_bytes()
.chunks(2)
.map(|pair| {
let pair = core::str::from_utf8(pair).map_err(|_| invalid())?;
u8::from_str_radix(pair, 16).map_err(|_| invalid())
})
.collect()
}
/// Runs on every node: only starts the confidential part and passes on what
/// comes back.
fn on_tick(ctx: &mut Context, _event: CronEvent) -> HandlerResult {
let config = Config::parse(ctx.config())?;
let balance = ctx.confidential("fetch_balance", Value::Null, vec![config.api_key])?;
ctx.log(format!("the enclave returned {balance:?}"));
Ok(balance)
}
/// Runs inside the enclave: the only place the API key exists in the clear.
fn fetch_balance(ctx: &mut EnclaveContext, _input: Value) -> HandlerResult {
let config = Config::parse(ctx.config())?;
let api_key = String::from_utf8(ctx.secret("api_key")?)
.map_err(|_| WorkflowError::new("the API key is not text"))?;
let response = ctx.http(
HttpRequest::get(&config.url).header("Authorization", &format!("Bearer {api_key}")),
)?;
let balance: i64 = response
.text()?
.trim()
.parse()
.map_err(|_| WorkflowError::new("the API did not answer with an integer"))?;
// Only the number leaves the enclave: not the key, not the response.
Ok(Value::Int(balance))
}
pub fn workflow() -> Workflow {
Workflow::new()
.on_cron(SCHEDULE, on_tick)
.confidential("fetch_balance", fetch_balance)
}
cxyz_sdk::export_workflow!(workflow);