Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
use alloy_primitives::LogData;
use anyhow::bail;
use iri_string::types::UriString;
use semver::Version;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::num::{NonZeroU32, NonZeroU64};
use std::str::FromStr;
use thiserror::Error;
use utoipa::ToSchema;
use wasm_pkg_common::package::PackageRef;

#[cfg(feature = "ts-bindings")]
use ts_rs::TS;

use crate::{ByteArray, ComponentDigest, ServiceDigest, Timestamp};

use super::{ChainKey, ServiceId, WorkflowId};

/// ATProto Jetstream commit action types
#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema, Hash)]
#[serde(rename_all = "snake_case")]
pub enum AtProtoAction {
    /// Create a new record
    Create,
    /// Update an existing record
    Update,
    /// Delete a record
    Delete,
}

impl std::fmt::Display for AtProtoAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AtProtoAction::Create => write!(f, "create"),
            AtProtoAction::Update => write!(f, "update"),
            AtProtoAction::Delete => write!(f, "delete"),
        }
    }
}

impl FromStr for AtProtoAction {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "create" => Ok(AtProtoAction::Create),
            "update" => Ok(AtProtoAction::Update),
            "delete" => Ok(AtProtoAction::Delete),
            _ => bail!(
                "Invalid action '{}'. Must be one of: create, update, delete",
                s
            ),
        }
    }
}

#[derive(Error, Debug)]
pub enum ServiceError {
    #[error("Failed to serialize service for hashing: {0}")]
    SerializationError(#[from] serde_json::Error),
}

/// Service validation is a runtime check, and depends on:
///
/// 1. All service handlers on a given chain use the same service manager
/// 2. All service managers on non-source chains properly mirror the operator set of the source
/// 3. All components are legitimate (e.g. can be downloaded, match the provided digest, execute as expected, etc.)
#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct Service {
    /// This is any utf-8 string, for human-readable display.
    pub name: String,

    /// We support multiple workflows in one service with unique service-scoped IDs.
    pub workflows: BTreeMap<WorkflowId, Workflow>,

    pub status: ServiceStatus,

    pub manager: ServiceManager,
}

impl Service {
    // this is only used for local/tests, but we want to keep it consistent
    pub fn hash(&self) -> Result<ServiceDigest, ServiceError> {
        let service_bytes = serde_json::to_vec(self)?;
        Ok(ServiceDigest::hash(&service_bytes))
    }

    pub fn id(&self) -> ServiceId {
        ServiceId::from(&self.manager)
    }
}

#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum ServiceManager {
    Evm {
        chain: ChainKey,
        #[schema(value_type = String)]
        #[cfg_attr(feature = "ts-bindings", ts(type = "string"))]
        address: alloy_primitives::Address,
    },
    Cosmos {
        chain: ChainKey,
        #[schema(value_type = String)]
        #[cfg_attr(feature = "ts-bindings", ts(type = "string"))]
        address: layer_climb_address::CosmosAddr,
    },
}

impl From<&ServiceManager> for ServiceId {
    fn from(manager: &ServiceManager) -> Self {
        match manager {
            ServiceManager::Evm { chain, address } => {
                let mut bytes = Vec::new();
                bytes.extend_from_slice(b"evm");
                bytes.extend_from_slice(chain.to_string().as_bytes());
                bytes.extend_from_slice(address.as_slice());
                ServiceId::hash(bytes)
            }
            ServiceManager::Cosmos { chain, address } => {
                let mut bytes = Vec::new();
                bytes.extend_from_slice(b"cosmos");
                bytes.extend_from_slice(chain.to_string().as_bytes());
                bytes.extend_from_slice(&address.to_vec());
                ServiceId::hash(bytes)
            }
        }
    }
}

impl ServiceManager {
    pub fn chain(&self) -> &ChainKey {
        match self {
            ServiceManager::Evm { chain, .. } => chain,
            ServiceManager::Cosmos { chain, .. } => chain,
        }
    }
    pub fn address(&self) -> layer_climb_address::Address {
        match self {
            ServiceManager::Evm { address, .. } => (*address).into(),
            ServiceManager::Cosmos { address, .. } => address.clone().into(),
        }
    }
}

impl Service {
    pub fn new_simple(
        name: Option<String>,
        trigger: Trigger,
        source: ComponentSource,
        submit: Submit,
        manager: ServiceManager,
    ) -> Self {
        let workflow_id = WorkflowId::default();

        let workflow = Workflow {
            trigger,
            component: Component::new(source),
            submit,
        };

        let workflows = BTreeMap::from([(workflow_id, workflow)]);

        Self {
            name: name.unwrap_or_else(|| "Unknown".to_string()),
            workflows,
            status: ServiceStatus::Active,
            manager,
        }
    }
}

#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct Component {
    pub source: ComponentSource,

    // What permissions this component has.
    // These are currently not enforced, you can pass in Default::default() for now
    pub permissions: Permissions,

    /// The maximum amount of compute metering to allow for a single component execution
    /// If not supplied, will be `Workflow::DEFAULT_FUEL_LIMIT`
    pub fuel_limit: Option<u64>,

    /// The maximum amount of time to allow for a single component execution, in seconds
    /// If not supplied, default will be `Workflow::DEFAULT_TIME_LIMIT_SECONDS`
    pub time_limit_seconds: Option<u64>,

    /// Key-value pairs that are accessible in the components via host bindings.
    pub config: BTreeMap<String, String>,

    /// External env variable keys to be read from the system host on execute (i.e. API keys).
    /// Must be prefixed with `WAVS_ENV_`.
    pub env_keys: BTreeSet<String>,
}

#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ComponentSource {
    /// The wasm bytecode provided at fixed url, digest provided to ensure no tampering
    Download {
        #[schema(value_type = String)]
        #[cfg_attr(feature = "ts-bindings", ts(type = "string"))]
        uri: UriString,
        #[cfg_attr(feature = "ts-bindings", ts(type = "string"))]
        digest: ComponentDigest,
    },
    /// The wasm bytecode downloaded from a standard registry, digest provided to ensure no tampering
    Registry {
        #[serde(flatten)]
        registry: Registry,
    },
    /// An already deployed component
    #[cfg_attr(feature = "ts-bindings", ts(type = "string"))]
    Digest(ComponentDigest),
}

#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
pub struct Registry {
    pub digest: ComponentDigest,
    /// Optional domain to use for a registry (such as ghcr.io)
    /// if default of wa.dev (or whatever wavs uses in the future)
    /// is not desired by user
    pub domain: Option<String>,
    /// Optional semver value, if absent then latest is used
    #[schema(value_type = Option<String>)]
    #[cfg_attr(feature = "ts-bindings", ts(type = "string | null"))]
    pub version: Option<Version>,
    /// Package identifier of form <namespace>:<packagename>
    #[schema(value_type = String)]
    #[cfg_attr(feature = "ts-bindings", ts(type = "string"))]
    pub package: PackageRef,
}

impl ComponentSource {
    pub fn digest(&self) -> &ComponentDigest {
        match self {
            ComponentSource::Download { digest, .. } => digest,
            ComponentSource::Registry { registry } => &registry.digest,
            ComponentSource::Digest(digest) => digest,
        }
    }
}

// FIXME: happy for a better name.
/// This captures the triggers we listen to, the components we run, and how we submit the result
#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct Workflow {
    /// The trigger that fires this workflow
    pub trigger: Trigger,

    /// The component to run when the trigger fires
    pub component: Component,

    /// How to submit the result of the component.
    pub submit: Submit,
}

impl Workflow {
    pub const DEFAULT_FUEL_LIMIT: u64 = u64::MAX;
    pub const DEFAULT_TIME_LIMIT_SECONDS: u64 = u64::MAX;
}

// The TriggerManager reacts to these triggers
#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Hash, Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum Trigger {
    // A contract that emits an event
    CosmosContractEvent {
        #[schema(value_type = String)]
        #[cfg_attr(feature = "ts-bindings", ts(type = "string"))]
        address: layer_climb_address::CosmosAddr,
        chain: ChainKey,
        event_type: String,
    },
    EvmContractEvent {
        #[schema(value_type = String)]
        #[cfg_attr(feature = "ts-bindings", ts(type = "string"))]
        address: alloy_primitives::Address,
        chain: ChainKey,
        #[cfg_attr(feature = "ts-bindings", ts(type = "string"))]
        event_hash: ByteArray<32>,
    },
    BlockInterval {
        /// The chain to use for the block interval
        chain: ChainKey,
        /// Number of blocks to wait between each execution
        #[schema(value_type = u32)]
        n_blocks: NonZeroU32,
        /// Optional start block height indicating when the interval begins.
        #[schema(value_type = Option<u64>)]
        start_block: Option<NonZeroU64>,
        /// Optional end block height indicating when the interval begins.
        #[schema(value_type = Option<u64>)]
        end_block: Option<NonZeroU64>,
    },
    Cron {
        /// A cron expression defining the schedule for execution.
        schedule: String,
        /// Optional start time (timestamp in nanoseconds) indicating when the schedule begins.
        start_time: Option<Timestamp>,
        /// Optional end time (timestamp in nanoseconds) indicating when the schedule ends.
        end_time: Option<Timestamp>,
    },
    /// ATProto Jetstream event trigger
    AtProtoEvent {
        /// Collection NSID to filter for (e.g., "app.bsky.feed.post")
        /// Supports wildcards with prefix matching (e.g., "app.bsky.feed.*")
        collection: String,
        /// Optional DID to filter for specific repositories
        /// If None, will match events from any repository
        repo_did: Option<String>,
        /// Action type to filter for (create, update, delete)
        /// If None, will match all action types
        action: Option<AtProtoAction>,
    },
    /// Hypercore append event trigger
    HypercoreAppend {
        /// Feed key to filter on.
        feed_key: String,
    },
    // not a real trigger, just for testing
    Manual,
}

/// The data that came from the trigger and is passed to the component after being converted into the WIT-friendly type
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema)]
pub enum TriggerData {
    CosmosContractEvent {
        /// The address of the contract that emitted the event
        #[schema(value_type = String)]
        contract_address: layer_climb_address::CosmosAddr,
        /// The chain where the event was emitted
        chain: ChainKey,
        /// The data that was emitted by the contract
        #[schema(value_type = Object)]
        event: cosmwasm_std::Event,
        /// The block height where the event was emitted
        block_height: u64,
        /// The index of the event in this block, required for unique identification
        event_index: u64,
    },
    EvmContractEvent {
        /// The chain where the event was emitted
        chain: ChainKey,
        /// The address of the contract that emitted the event
        #[schema(value_type = String)]
        contract_address: alloy_primitives::Address,
        /// The log data
        #[schema(value_type = Object)]
        log_data: LogData,
        /// The transaction hash where the event was emitted
        #[schema(value_type = String)]
        tx_hash: alloy_primitives::TxHash,
        /// The block height where the event was emitted
        block_number: u64,
        /// The index of the log in the block
        log_index: u64,
        // these are all optional because they may not be present in the log and we don't need them
        /// Hash of the block the transaction that emitted this log was mined in
        #[schema(value_type = String)]
        block_hash: alloy_primitives::B256,
        /// The timestamp of the block containing this event, as proposed in https://github.com/ethereum/execution-apis/issues/295
        /// This field is optional since nodes are not required to include it in event logs.
        /// If not provided, applications may need to fetch the block header directly to obtain the timestamp.
        block_timestamp: Option<u64>,
        /// Index of the Transaction in the block
        tx_index: u64,
    },
    BlockInterval {
        /// The chain where the blocks are checked
        chain: ChainKey,
        /// The block height where the event was emitted
        block_height: u64,
    },
    Cron {
        /// The trigger time
        trigger_time: Timestamp,
    },
    /// ATProto Jetstream event data
    AtProtoEvent {
        /// Sequence number of the event in the stream
        sequence: i64,
        /// Timestamp in microseconds
        timestamp: i64,
        /// Repository DID that generated the event
        repo: String,
        /// Collection NSID (e.g., "app.bsky.feed.post")
        collection: String,
        /// Record key within the collection
        rkey: String,
        /// Action type (create, update, delete)
        action: AtProtoAction,
        /// CID of the record (None for delete events)
        cid: Option<String>,
        /// Record data as JSON (None for delete events)
        record: Option<serde_json::Value>,
        /// Repository revision identifier for this commit (if provided by the event)
        rev: Option<String>,
        /// Index of the operation within the commit (0-based)
        op_index: Option<u32>,
    },
    HypercoreAppend {
        /// Hypercore feed key that emitted the append
        feed_key: String,
        /// Index of the appended entry
        index: u64,
        /// Raw entry data
        data: Vec<u8>,
    },
    Raw(Vec<u8>),
}

impl Default for TriggerData {
    fn default() -> Self {
        Self::new_raw(vec![])
    }
}

impl TriggerData {
    pub fn new_raw(data: impl AsRef<[u8]>) -> Self {
        TriggerData::Raw(data.as_ref().to_vec())
    }

    pub fn trigger_type(&self) -> &str {
        match self {
            TriggerData::CosmosContractEvent { .. } => "cosmos_contract_event",
            TriggerData::EvmContractEvent { .. } => "evm_contract_event",
            TriggerData::BlockInterval { .. } => "block_interval",
            TriggerData::Cron { .. } => "cron",
            TriggerData::AtProtoEvent { .. } => "atproto_event",
            TriggerData::HypercoreAppend { .. } => "hypercore_append",
            TriggerData::Raw(_) => "manual",
        }
    }

    pub fn chain(&self) -> Option<&ChainKey> {
        match self {
            TriggerData::CosmosContractEvent { chain, .. }
            | TriggerData::EvmContractEvent { chain, .. }
            | TriggerData::BlockInterval { chain, .. } => Some(chain),
            TriggerData::Cron { .. }
            | TriggerData::AtProtoEvent { .. }
            | TriggerData::HypercoreAppend { .. }
            | TriggerData::Raw(_) => None,
        }
    }
}

/// A bundle of the trigger and the associated data needed to take action on it
#[derive(
    Serialize, Deserialize, Clone, Debug, PartialEq, Eq, bincode::Decode, bincode::Encode, ToSchema,
)]
pub struct TriggerAction {
    #[bincode(with_serde)]
    /// Identify which trigger this came from
    pub config: TriggerConfig,

    #[bincode(with_serde)]
    /// The data that came from the trigger
    pub data: TriggerData,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema)]
// Trigger with metadata so it can be identified in relation to services and workflows
pub struct TriggerConfig {
    pub service_id: ServiceId,
    pub workflow_id: WorkflowId,
    pub trigger: Trigger,
}

// TODO - rename this? Trigger is a noun, Submit is a verb.. feels a bit weird
#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum Submit {
    // useful for when the component just does something with its own state
    None,
    Aggregator {
        /// component dynamically determines the destination
        component: Box<Component>,
        signature_kind: SignatureKind,
    },
}

/// Defines the signature configuration for cryptographic operations in WAVS.
///
/// This struct separates the cryptographic algorithm from the message formatting
/// to provide flexibility in signature schemes while maintaining compatibility
/// across different blockchain ecosystems.
///
/// ## Why Separate Algorithm and Prefix?
///
/// The separation of `algorithm` and `prefix` serves several important purposes:
///
/// 1. **Algorithm Independence**: The same cryptographic algorithm (e.g., secp256k1)
///    can be used with different message formatting schemes. This allows the same
///    private key to work across different contexts.
///
/// 2. **Ethereum Compatibility**: Some signatures need EIP-191 prefixing for
///    Ethereum compatibility, while others work with raw message hashes. The
///    optional prefix allows both modes.
///
/// 3. **Future Extensibility**: As new signature algorithms (BLS12-381, Ed25519, etc.)
///    and prefix schemes are added, this structure can accommodate them without
///    breaking changes.
#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema, Hash)]
pub struct SignatureKind {
    /// The cryptographic algorithm used for signature generation and verification.
    ///
    /// This determines the elliptic curve and mathematical operations used,
    /// but not how the message is formatted before signing.
    pub algorithm: SignatureAlgorithm,

    /// Optional message prefix scheme applied before signing.
    ///
    /// When `Some(prefix)`, the message is formatted according to the specified
    /// scheme (e.g., EIP-191 for Ethereum compatibility). When `None`, the raw
    /// message hash is signed directly.
    pub prefix: Option<SignaturePrefix>,
}

impl SignatureKind {
    pub fn evm_default() -> Self {
        Self {
            algorithm: SignatureAlgorithm::Secp256k1,
            prefix: Some(SignaturePrefix::Eip191),
        }
    }
}

#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema, Hash)]
#[serde(rename_all = "snake_case")]
pub enum SignatureAlgorithm {
    Secp256k1,
    // Future: Bls12381, Ed25519, Secp256r1, etc.
}

#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema, Hash)]
#[serde(rename_all = "snake_case")]
pub enum SignaturePrefix {
    Eip191,
}

#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Copy, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ServiceStatus {
    Active,
    // Service is paused, no workflows will be executed
    // however the service can still be queried for AVS Key etc.
    Paused,
}

impl FromStr for ServiceStatus {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "active" => Ok(ServiceStatus::Active),
            "paused" => Ok(ServiceStatus::Paused),
            _ => Err(anyhow::anyhow!("Invalid service status: {}", s)),
        }
    }
}

#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema, Default)]
#[serde(default, rename_all = "snake_case")]
pub struct Permissions {
    /// If it can talk to http hosts on the network
    pub allowed_http_hosts: AllowedHostPermission,
    /// If it can write to it's own local directory in the filesystem
    pub file_system: bool,
    /// If it can use the host's raw sockets (not needed for http)
    pub raw_sockets: bool,
    /// If it can perform DNS resolution (not needed for http)
    pub dns_resolution: bool,
}

#[test]
fn permission_defaults() {
    let permissions_json: Permissions = serde_json::from_str("{}").unwrap();
    let permissions_default: Permissions = Permissions::default();

    assert_eq!(permissions_json, permissions_default);
    assert_eq!(
        permissions_default.allowed_http_hosts,
        AllowedHostPermission::None
    );
    assert!(!permissions_default.file_system);
}

// TODO: remove / change defaults?

#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum AllowedHostPermission {
    All,
    Only(Vec<String>),
    #[default]
    None,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, ToSchema)]
#[serde(default, rename_all = "snake_case")]
#[derive(Default)]
pub struct WasmResponse {
    #[serde(with = "const_hex")]
    pub payload: Vec<u8>,
    pub ordering: Option<u64>,
    #[serde(with = "crate::serde_helpers::option_const_hex")]
    pub event_id_salt: Option<Vec<u8>>,
}

impl WasmResponse {
    /// Default maximum payload size: 50 MB
    pub const DEFAULT_MAX_PAYLOAD_SIZE: usize = 50 * 1024 * 1024;
    /// Default maximum event_id_salt size: 1 MB
    pub const DEFAULT_MAX_SALT_SIZE: usize = 1024 * 1024;

    /// Validates that the payload and salt are within size limits.
    pub fn validate_size(
        &self,
        max_payload_size: usize,
        max_salt_size: usize,
    ) -> Result<(), WasmResponseSizeError> {
        if self.payload.len() > max_payload_size {
            return Err(WasmResponseSizeError::PayloadTooLarge {
                size: self.payload.len(),
                max: max_payload_size,
            });
        }
        if let Some(salt) = &self.event_id_salt {
            if salt.len() > max_salt_size {
                return Err(WasmResponseSizeError::SaltTooLarge {
                    size: salt.len(),
                    max: max_salt_size,
                });
            }
        }
        Ok(())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum WasmResponseSizeError {
    #[error("Payload size {size} bytes exceeds maximum of {max} bytes")]
    PayloadTooLarge { size: usize, max: usize },
    #[error("Event ID salt size {size} bytes exceeds maximum of {max} bytes")]
    SaltTooLarge { size: usize, max: usize },
}

// TODO - these shouldn't be needed in main code... gate behind `debug_assertions`
// will need to go through use-cases of `test-utils`, maybe move into layer-tests or something
mod test_ext {
    use std::{
        collections::{BTreeMap, BTreeSet},
        num::NonZeroU32,
    };

    use crate::{
        ByteArray, ChainKey, ChainKeyError, ComponentSource, ServiceId, WorkflowId, WorkflowIdError,
    };

    use super::{Component, Trigger, TriggerConfig};

    impl Component {
        pub fn new(source: ComponentSource) -> Component {
            Self {
                source,
                permissions: Default::default(),
                fuel_limit: None,
                time_limit_seconds: None,
                config: BTreeMap::new(),
                env_keys: BTreeSet::new(),
            }
        }
    }

    impl Trigger {
        pub fn cosmos_contract_event(
            address: layer_climb_address::CosmosAddr,
            chain: impl TryInto<ChainKey, Error = ChainKeyError>,
            event_type: impl ToString,
        ) -> Self {
            Trigger::CosmosContractEvent {
                address,
                chain: chain.try_into().unwrap(),
                event_type: event_type.to_string(),
            }
        }
        pub fn evm_contract_event(
            address: alloy_primitives::Address,
            chain: impl TryInto<ChainKey, Error = ChainKeyError>,
            event_hash: ByteArray<32>,
        ) -> Self {
            Trigger::EvmContractEvent {
                address,
                chain: chain.try_into().unwrap(),
                event_hash,
            }
        }
    }

    impl TriggerConfig {
        pub fn cosmos_contract_event(
            service_id: ServiceId,
            workflow_id: impl TryInto<WorkflowId, Error = WorkflowIdError>,
            contract_address: layer_climb_address::CosmosAddr,
            chain: impl TryInto<ChainKey, Error = ChainKeyError>,
            event_type: impl ToString,
        ) -> Self {
            Self {
                service_id,
                workflow_id: workflow_id.try_into().unwrap(),
                trigger: Trigger::cosmos_contract_event(contract_address, chain, event_type),
            }
        }

        pub fn evm_contract_event(
            service_id: ServiceId,
            workflow_id: impl TryInto<WorkflowId, Error = WorkflowIdError>,
            contract_address: alloy_primitives::Address,
            chain: impl TryInto<ChainKey, Error = ChainKeyError>,
            event_hash: ByteArray<32>,
        ) -> Self {
            Self {
                service_id,
                workflow_id: workflow_id.try_into().unwrap(),
                trigger: Trigger::evm_contract_event(contract_address, chain, event_hash),
            }
        }

        pub fn block_interval_event(
            service_id: ServiceId,
            workflow_id: impl TryInto<WorkflowId, Error = WorkflowIdError>,
            chain: impl TryInto<ChainKey, Error = ChainKeyError>,
            n_blocks: NonZeroU32,
        ) -> Self {
            Self {
                service_id,
                workflow_id: workflow_id.try_into().unwrap(),
                trigger: Trigger::BlockInterval {
                    chain: chain.try_into().unwrap(),
                    n_blocks,
                    start_block: None,
                    end_block: None,
                },
            }
        }

        #[cfg(test)]
        pub fn manual(
            service_id: ServiceId,
            workflow_id: impl TryInto<WorkflowId, Error = WorkflowIdError>,
        ) -> Self {
            Self {
                service_id,
                workflow_id: workflow_id.try_into().unwrap(),
                trigger: Trigger::Manual,
            }
        }
    }
}