Skip to main content

freenet_stdlib/
delegate_interface.rs

1use std::{
2    borrow::{Borrow, Cow},
3    fmt::Display,
4    fs::File,
5    io::Read,
6    ops::Deref,
7    path::Path,
8};
9
10use blake3::{traits::digest::Digest, Hasher as Blake3};
11use serde::{Deserialize, Deserializer, Serialize};
12use serde_with::serde_as;
13
14use crate::generated::client_request::{
15    DelegateKey as FbsDelegateKey, InboundDelegateMsg as FbsInboundDelegateMsg,
16    InboundDelegateMsgType,
17};
18
19use crate::common_generated::common::SecretsId as FbsSecretsId;
20
21use crate::client_api::{TryFromFbs, WsApiError};
22use crate::contract_interface::{RelatedContracts, UpdateData};
23use crate::prelude::{ContractInstanceId, WrappedState, CONTRACT_KEY_SIZE};
24use crate::versioning::ContractContainer;
25use crate::{code_hash::CodeHash, prelude::Parameters};
26
27const DELEGATE_HASH_LENGTH: usize = 32;
28
29#[derive(Clone, Debug, Serialize, Deserialize)]
30pub struct Delegate<'a> {
31    #[serde(borrow)]
32    parameters: Parameters<'a>,
33    #[serde(borrow)]
34    pub data: DelegateCode<'a>,
35    key: DelegateKey,
36}
37
38impl Delegate<'_> {
39    pub fn key(&self) -> &DelegateKey {
40        &self.key
41    }
42
43    pub fn code(&self) -> &DelegateCode<'_> {
44        &self.data
45    }
46
47    pub fn code_hash(&self) -> &CodeHash {
48        &self.data.code_hash
49    }
50
51    pub fn params(&self) -> &Parameters<'_> {
52        &self.parameters
53    }
54
55    pub fn into_owned(self) -> Delegate<'static> {
56        Delegate {
57            parameters: self.parameters.into_owned(),
58            data: self.data.into_owned(),
59            key: self.key,
60        }
61    }
62
63    pub fn size(&self) -> usize {
64        self.parameters.size() + self.data.size()
65    }
66
67    pub(crate) fn deserialize_delegate<'de, D>(deser: D) -> Result<Delegate<'static>, D::Error>
68    where
69        D: Deserializer<'de>,
70    {
71        let data: Delegate<'de> = Deserialize::deserialize(deser)?;
72        Ok(data.into_owned())
73    }
74}
75
76impl PartialEq for Delegate<'_> {
77    fn eq(&self, other: &Self) -> bool {
78        self.key == other.key
79    }
80}
81
82impl Eq for Delegate<'_> {}
83
84impl<'a> From<(&DelegateCode<'a>, &Parameters<'a>)> for Delegate<'a> {
85    fn from((data, parameters): (&DelegateCode<'a>, &Parameters<'a>)) -> Self {
86        Self {
87            key: DelegateKey::from_params_and_code(parameters, data),
88            parameters: parameters.clone(),
89            data: data.clone(),
90        }
91    }
92}
93
94/// Executable delegate
95#[derive(Debug, Serialize, Deserialize, Clone)]
96#[serde_as]
97pub struct DelegateCode<'a> {
98    #[serde_as(as = "serde_with::Bytes")]
99    #[serde(borrow)]
100    pub(crate) data: Cow<'a, [u8]>,
101    // todo: skip serializing and instead compute it
102    pub(crate) code_hash: CodeHash,
103}
104
105impl DelegateCode<'static> {
106    /// Loads the contract raw wasm module, without any version.
107    pub fn load_raw(path: &Path) -> Result<Self, std::io::Error> {
108        let contract_data = Self::load_bytes(path)?;
109        Ok(DelegateCode::from(contract_data))
110    }
111
112    pub(crate) fn load_bytes(path: &Path) -> Result<Vec<u8>, std::io::Error> {
113        let mut contract_file = File::open(path)?;
114        let mut contract_data = if let Ok(md) = contract_file.metadata() {
115            Vec::with_capacity(md.len() as usize)
116        } else {
117            Vec::new()
118        };
119        contract_file.read_to_end(&mut contract_data)?;
120        Ok(contract_data)
121    }
122}
123
124impl DelegateCode<'_> {
125    /// Delegate code hash.
126    pub fn hash(&self) -> &CodeHash {
127        &self.code_hash
128    }
129
130    /// Returns the `Base58` string representation of the delegate key.
131    pub fn hash_str(&self) -> String {
132        Self::encode_hash(&self.code_hash.0)
133    }
134
135    /// Reference to delegate code.
136    pub fn data(&self) -> &[u8] {
137        &self.data
138    }
139
140    /// Returns the `Base58` string representation of a hash.
141    pub fn encode_hash(hash: &[u8; DELEGATE_HASH_LENGTH]) -> String {
142        bs58::encode(hash)
143            .with_alphabet(bs58::Alphabet::BITCOIN)
144            .into_string()
145    }
146
147    pub fn into_owned(self) -> DelegateCode<'static> {
148        DelegateCode {
149            code_hash: self.code_hash,
150            data: Cow::from(self.data.into_owned()),
151        }
152    }
153
154    pub fn size(&self) -> usize {
155        self.data.len()
156    }
157}
158
159impl PartialEq for DelegateCode<'_> {
160    fn eq(&self, other: &Self) -> bool {
161        self.code_hash == other.code_hash
162    }
163}
164
165impl Eq for DelegateCode<'_> {}
166
167impl AsRef<[u8]> for DelegateCode<'_> {
168    fn as_ref(&self) -> &[u8] {
169        self.data.borrow()
170    }
171}
172
173impl From<Vec<u8>> for DelegateCode<'static> {
174    fn from(data: Vec<u8>) -> Self {
175        let key = CodeHash::from_code(data.as_slice());
176        DelegateCode {
177            data: Cow::from(data),
178            code_hash: key,
179        }
180    }
181}
182
183impl<'a> From<&'a [u8]> for DelegateCode<'a> {
184    fn from(code: &'a [u8]) -> Self {
185        let key = CodeHash::from_code(code);
186        DelegateCode {
187            data: Cow::from(code),
188            code_hash: key,
189        }
190    }
191}
192
193#[serde_as]
194#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
195pub struct DelegateKey {
196    #[serde_as(as = "[_; DELEGATE_HASH_LENGTH]")]
197    key: [u8; DELEGATE_HASH_LENGTH],
198    code_hash: CodeHash,
199}
200
201impl From<DelegateKey> for SecretsId {
202    fn from(key: DelegateKey) -> SecretsId {
203        SecretsId {
204            hash: key.key,
205            key: vec![],
206        }
207    }
208}
209
210impl DelegateKey {
211    pub const fn new(key: [u8; DELEGATE_HASH_LENGTH], code_hash: CodeHash) -> Self {
212        Self { key, code_hash }
213    }
214
215    fn from_params_and_code<'a>(
216        params: impl Borrow<Parameters<'a>>,
217        wasm_code: impl Borrow<DelegateCode<'a>>,
218    ) -> Self {
219        let code = wasm_code.borrow();
220        let key = generate_id(params.borrow(), code);
221        Self {
222            key,
223            code_hash: *code.hash(),
224        }
225    }
226
227    pub fn encode(&self) -> String {
228        bs58::encode(self.key)
229            .with_alphabet(bs58::Alphabet::BITCOIN)
230            .into_string()
231    }
232
233    pub fn code_hash(&self) -> &CodeHash {
234        &self.code_hash
235    }
236
237    pub fn bytes(&self) -> &[u8] {
238        self.key.as_ref()
239    }
240
241    pub fn from_params(
242        code_hash: impl Into<String>,
243        parameters: &Parameters,
244    ) -> Result<Self, bs58::decode::Error> {
245        let mut code_key = [0; DELEGATE_HASH_LENGTH];
246        bs58::decode(code_hash.into())
247            .with_alphabet(bs58::Alphabet::BITCOIN)
248            .onto(&mut code_key)?;
249        let mut hasher = Blake3::new();
250        hasher.update(code_key.as_slice());
251        hasher.update(parameters.as_ref());
252        let full_key_arr = hasher.finalize();
253
254        debug_assert_eq!(full_key_arr[..].len(), DELEGATE_HASH_LENGTH);
255        let mut key = [0; DELEGATE_HASH_LENGTH];
256        key.copy_from_slice(&full_key_arr);
257
258        Ok(Self {
259            key,
260            code_hash: CodeHash(code_key),
261        })
262    }
263}
264
265impl Deref for DelegateKey {
266    type Target = [u8; DELEGATE_HASH_LENGTH];
267
268    fn deref(&self) -> &Self::Target {
269        &self.key
270    }
271}
272
273impl Display for DelegateKey {
274    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275        write!(f, "{}", self.encode())
276    }
277}
278
279impl<'a> TryFromFbs<&FbsDelegateKey<'a>> for DelegateKey {
280    fn try_decode_fbs(key: &FbsDelegateKey<'a>) -> Result<Self, WsApiError> {
281        let mut key_bytes = [0; DELEGATE_HASH_LENGTH];
282        key_bytes.copy_from_slice(key.key().bytes().iter().as_ref());
283        Ok(DelegateKey {
284            key: key_bytes,
285            code_hash: CodeHash::from_code(key.code_hash().bytes()),
286        })
287    }
288}
289
290/// Type of errors during interaction with a delegate.
291#[derive(Debug, thiserror::Error, Serialize, Deserialize)]
292pub enum DelegateError {
293    #[error("de/serialization error: {0}")]
294    Deser(String),
295    #[error("{0}")]
296    Other(String),
297}
298
299fn generate_id<'a>(
300    parameters: &Parameters<'a>,
301    code_data: &DelegateCode<'a>,
302) -> [u8; DELEGATE_HASH_LENGTH] {
303    let contract_hash = code_data.hash();
304
305    let mut hasher = Blake3::new();
306    hasher.update(contract_hash.0.as_slice());
307    hasher.update(parameters.as_ref());
308    let full_key_arr = hasher.finalize();
309
310    debug_assert_eq!(full_key_arr[..].len(), DELEGATE_HASH_LENGTH);
311    let mut key = [0; DELEGATE_HASH_LENGTH];
312    key.copy_from_slice(&full_key_arr);
313    key
314}
315
316#[serde_as]
317#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
318pub struct SecretsId {
319    #[serde_as(as = "serde_with::Bytes")]
320    key: Vec<u8>,
321    #[serde_as(as = "[_; 32]")]
322    hash: [u8; 32],
323}
324
325impl SecretsId {
326    pub fn new(key: Vec<u8>) -> Self {
327        let mut hasher = Blake3::new();
328        hasher.update(&key);
329        let hashed = hasher.finalize();
330        let mut hash = [0; 32];
331        hash.copy_from_slice(&hashed);
332        Self { key, hash }
333    }
334
335    pub fn encode(&self) -> String {
336        bs58::encode(self.hash)
337            .with_alphabet(bs58::Alphabet::BITCOIN)
338            .into_string()
339    }
340
341    pub fn hash(&self) -> &[u8; 32] {
342        &self.hash
343    }
344    pub fn key(&self) -> &[u8] {
345        self.key.as_slice()
346    }
347}
348
349impl Display for SecretsId {
350    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
351        write!(f, "{}", self.encode())
352    }
353}
354
355impl<'a> TryFromFbs<&FbsSecretsId<'a>> for SecretsId {
356    fn try_decode_fbs(key: &FbsSecretsId<'a>) -> Result<Self, WsApiError> {
357        let mut key_hash = [0; 32];
358        key_hash.copy_from_slice(key.hash().bytes().iter().as_ref());
359        Ok(SecretsId {
360            key: key.key().bytes().to_vec(),
361            hash: key_hash,
362        })
363    }
364}
365
366/// A Delegate is a webassembly code designed to act as an agent for the user on
367/// Freenet. Delegates can:
368///
369///  * Store private data on behalf of the user
370///  * Create, read, and modify contracts
371///  * Create other delegates
372///  * Send and receive messages from other delegates and user interfaces
373///  * Ask the user questions and receive answers
374///
375/// Example use cases:
376///
377///  * A delegate stores a private key for the user, other components can ask
378///    the delegate to sign messages, it will ask the user for permission
379///  * A delegate monitors an inbox contract and downloads new messages when
380///    they arrive
381///
382/// # Example
383///
384/// ```ignore
385/// use freenet_stdlib::prelude::*;
386///
387/// struct MyDelegate;
388///
389/// #[delegate]
390/// impl DelegateInterface for MyDelegate {
391///     fn process(
392///         ctx: &mut DelegateCtx,
393///         _params: Parameters<'static>,
394///         _attested: Option<&'static [u8]>,
395///         message: InboundDelegateMsg,
396///     ) -> Result<Vec<OutboundDelegateMsg>, DelegateError> {
397///         // Access secrets synchronously - no round-trip needed!
398///         if let Some(key) = ctx.get_secret(b"private_key") {
399///             // use key...
400///         }
401///         ctx.set_secret(b"new_key", b"value");
402///
403///         // Read/write context for temporary state within a batch
404///         ctx.write(b"some state");
405///
406///         Ok(vec![])
407///     }
408/// }
409/// ```
410pub trait DelegateInterface {
411    /// Process inbound message, producing zero or more outbound messages in response.
412    ///
413    /// # Arguments
414    /// - `ctx`: Mutable handle to the delegate's execution environment. Provides:
415    ///   - **Context** (temporary): `read()`, `write()`, `len()`, `clear()` - state within a batch
416    ///   - **Secrets** (persistent): `get_secret()`, `set_secret()`, `has_secret()`, `remove_secret()`
417    /// - `parameters`: The delegate's initialization parameters.
418    /// - `attested`: An optional identifier for the client of this function. Usually
419    ///   will be a [`ContractInstanceId`].
420    /// - `message`: The inbound message to process.
421    fn process(
422        ctx: &mut crate::delegate_host::DelegateCtx,
423        parameters: Parameters<'static>,
424        attested: Option<&'static [u8]>,
425        message: InboundDelegateMsg,
426    ) -> Result<Vec<OutboundDelegateMsg>, DelegateError>;
427}
428
429#[serde_as]
430#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
431pub struct DelegateContext(#[serde_as(as = "serde_with::Bytes")] Vec<u8>);
432
433impl DelegateContext {
434    pub const MAX_SIZE: usize = 4096 * 10 * 10;
435
436    pub fn new(bytes: Vec<u8>) -> Self {
437        assert!(bytes.len() < Self::MAX_SIZE);
438        Self(bytes)
439    }
440
441    pub fn append(&mut self, bytes: &mut Vec<u8>) {
442        assert!(self.0.len() + bytes.len() < Self::MAX_SIZE);
443        self.0.append(bytes)
444    }
445
446    pub fn replace(&mut self, bytes: Vec<u8>) {
447        assert!(bytes.len() < Self::MAX_SIZE);
448        let _ = std::mem::replace(&mut self.0, bytes);
449    }
450}
451
452impl AsRef<[u8]> for DelegateContext {
453    fn as_ref(&self) -> &[u8] {
454        &self.0
455    }
456}
457
458#[derive(Serialize, Deserialize, Debug, Clone)]
459pub enum InboundDelegateMsg<'a> {
460    ApplicationMessage(ApplicationMessage),
461    UserResponse(#[serde(borrow)] UserInputResponse<'a>),
462    GetContractResponse(GetContractResponse),
463    PutContractResponse(PutContractResponse),
464    UpdateContractResponse(UpdateContractResponse),
465    SubscribeContractResponse(SubscribeContractResponse),
466}
467
468impl InboundDelegateMsg<'_> {
469    pub fn into_owned(self) -> InboundDelegateMsg<'static> {
470        match self {
471            InboundDelegateMsg::ApplicationMessage(r) => InboundDelegateMsg::ApplicationMessage(r),
472            InboundDelegateMsg::UserResponse(r) => InboundDelegateMsg::UserResponse(r.into_owned()),
473            InboundDelegateMsg::GetContractResponse(r) => {
474                InboundDelegateMsg::GetContractResponse(r)
475            }
476            InboundDelegateMsg::PutContractResponse(r) => {
477                InboundDelegateMsg::PutContractResponse(r)
478            }
479            InboundDelegateMsg::UpdateContractResponse(r) => {
480                InboundDelegateMsg::UpdateContractResponse(r)
481            }
482            InboundDelegateMsg::SubscribeContractResponse(r) => {
483                InboundDelegateMsg::SubscribeContractResponse(r)
484            }
485        }
486    }
487
488    pub fn get_context(&self) -> Option<&DelegateContext> {
489        match self {
490            InboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
491                Some(context)
492            }
493            InboundDelegateMsg::GetContractResponse(GetContractResponse { context, .. }) => {
494                Some(context)
495            }
496            InboundDelegateMsg::PutContractResponse(PutContractResponse { context, .. }) => {
497                Some(context)
498            }
499            InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
500                context, ..
501            }) => Some(context),
502            InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
503                context,
504                ..
505            }) => Some(context),
506            _ => None,
507        }
508    }
509
510    pub fn get_mut_context(&mut self) -> Option<&mut DelegateContext> {
511        match self {
512            InboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
513                Some(context)
514            }
515            InboundDelegateMsg::GetContractResponse(GetContractResponse { context, .. }) => {
516                Some(context)
517            }
518            InboundDelegateMsg::PutContractResponse(PutContractResponse { context, .. }) => {
519                Some(context)
520            }
521            InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
522                context, ..
523            }) => Some(context),
524            InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
525                context,
526                ..
527            }) => Some(context),
528            _ => None,
529        }
530    }
531}
532
533impl From<ApplicationMessage> for InboundDelegateMsg<'_> {
534    fn from(value: ApplicationMessage) -> Self {
535        Self::ApplicationMessage(value)
536    }
537}
538
539impl<'a> TryFromFbs<&FbsInboundDelegateMsg<'a>> for InboundDelegateMsg<'a> {
540    fn try_decode_fbs(msg: &FbsInboundDelegateMsg<'a>) -> Result<Self, WsApiError> {
541        match msg.inbound_type() {
542            InboundDelegateMsgType::common_ApplicationMessage => {
543                let app_msg = msg.inbound_as_common_application_message().unwrap();
544                let mut instance_key_bytes = [0; CONTRACT_KEY_SIZE];
545                instance_key_bytes
546                    .copy_from_slice(app_msg.app().data().bytes().to_vec().as_slice());
547                let app_msg = ApplicationMessage {
548                    app: ContractInstanceId::new(instance_key_bytes),
549                    payload: app_msg.payload().bytes().to_vec(),
550                    context: DelegateContext::new(app_msg.context().bytes().to_vec()),
551                    processed: app_msg.processed(),
552                };
553                Ok(InboundDelegateMsg::ApplicationMessage(app_msg))
554            }
555            InboundDelegateMsgType::UserInputResponse => {
556                let user_response = msg.inbound_as_user_input_response().unwrap();
557                let user_response = UserInputResponse {
558                    request_id: user_response.request_id(),
559                    response: ClientResponse::new(user_response.response().data().bytes().to_vec()),
560                    context: DelegateContext::new(
561                        user_response.delegate_context().bytes().to_vec(),
562                    ),
563                };
564                Ok(InboundDelegateMsg::UserResponse(user_response))
565            }
566            _ => unreachable!("invalid inbound delegate message type"),
567        }
568    }
569}
570
571#[non_exhaustive]
572#[derive(Serialize, Deserialize, Debug, Clone)]
573pub struct ApplicationMessage {
574    pub app: ContractInstanceId,
575    pub payload: Vec<u8>,
576    pub context: DelegateContext,
577    pub processed: bool,
578}
579
580impl ApplicationMessage {
581    pub fn new(app: ContractInstanceId, payload: Vec<u8>) -> Self {
582        Self {
583            app,
584            payload,
585            context: DelegateContext::default(),
586            processed: false,
587        }
588    }
589
590    pub fn with_context(mut self, context: DelegateContext) -> Self {
591        self.context = context;
592        self
593    }
594
595    pub fn processed(mut self, p: bool) -> Self {
596        self.processed = p;
597        self
598    }
599}
600
601#[derive(Serialize, Deserialize, Debug, Clone)]
602pub struct UserInputResponse<'a> {
603    pub request_id: u32,
604    #[serde(borrow)]
605    pub response: ClientResponse<'a>,
606    pub context: DelegateContext,
607}
608
609impl UserInputResponse<'_> {
610    pub fn into_owned(self) -> UserInputResponse<'static> {
611        UserInputResponse {
612            request_id: self.request_id,
613            response: self.response.into_owned(),
614            context: self.context,
615        }
616    }
617}
618
619#[derive(Serialize, Deserialize, Debug, Clone)]
620pub enum OutboundDelegateMsg {
621    // for the apps
622    ApplicationMessage(ApplicationMessage),
623    RequestUserInput(
624        #[serde(deserialize_with = "OutboundDelegateMsg::deser_user_input_req")]
625        UserInputRequest<'static>,
626    ),
627    // todo: remove when context can be accessed from the delegate environment and we pass it as reference
628    ContextUpdated(DelegateContext),
629    GetContractRequest(GetContractRequest),
630    PutContractRequest(PutContractRequest),
631    UpdateContractRequest(UpdateContractRequest),
632    SubscribeContractRequest(SubscribeContractRequest),
633}
634
635impl From<ApplicationMessage> for OutboundDelegateMsg {
636    fn from(req: ApplicationMessage) -> Self {
637        Self::ApplicationMessage(req)
638    }
639}
640
641impl From<GetContractRequest> for OutboundDelegateMsg {
642    fn from(req: GetContractRequest) -> Self {
643        Self::GetContractRequest(req)
644    }
645}
646
647impl From<PutContractRequest> for OutboundDelegateMsg {
648    fn from(req: PutContractRequest) -> Self {
649        Self::PutContractRequest(req)
650    }
651}
652
653impl From<UpdateContractRequest> for OutboundDelegateMsg {
654    fn from(req: UpdateContractRequest) -> Self {
655        Self::UpdateContractRequest(req)
656    }
657}
658
659impl From<SubscribeContractRequest> for OutboundDelegateMsg {
660    fn from(req: SubscribeContractRequest) -> Self {
661        Self::SubscribeContractRequest(req)
662    }
663}
664
665impl OutboundDelegateMsg {
666    fn deser_user_input_req<'de, D>(deser: D) -> Result<UserInputRequest<'static>, D::Error>
667    where
668        D: serde::Deserializer<'de>,
669    {
670        let value = <UserInputRequest<'de> as Deserialize>::deserialize(deser)?;
671        Ok(value.into_owned())
672    }
673
674    pub fn processed(&self) -> bool {
675        match self {
676            OutboundDelegateMsg::ApplicationMessage(msg) => msg.processed,
677            OutboundDelegateMsg::GetContractRequest(msg) => msg.processed,
678            OutboundDelegateMsg::PutContractRequest(msg) => msg.processed,
679            OutboundDelegateMsg::UpdateContractRequest(msg) => msg.processed,
680            OutboundDelegateMsg::SubscribeContractRequest(msg) => msg.processed,
681            OutboundDelegateMsg::RequestUserInput(_) => true,
682            OutboundDelegateMsg::ContextUpdated(_) => true,
683        }
684    }
685
686    pub fn get_context(&self) -> Option<&DelegateContext> {
687        match self {
688            OutboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
689                Some(context)
690            }
691            OutboundDelegateMsg::GetContractRequest(GetContractRequest { context, .. }) => {
692                Some(context)
693            }
694            OutboundDelegateMsg::PutContractRequest(PutContractRequest { context, .. }) => {
695                Some(context)
696            }
697            OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
698                context, ..
699            }) => Some(context),
700            OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
701                context,
702                ..
703            }) => Some(context),
704            _ => None,
705        }
706    }
707
708    pub fn get_mut_context(&mut self) -> Option<&mut DelegateContext> {
709        match self {
710            OutboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
711                Some(context)
712            }
713            OutboundDelegateMsg::GetContractRequest(GetContractRequest { context, .. }) => {
714                Some(context)
715            }
716            OutboundDelegateMsg::PutContractRequest(PutContractRequest { context, .. }) => {
717                Some(context)
718            }
719            OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
720                context, ..
721            }) => Some(context),
722            OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
723                context,
724                ..
725            }) => Some(context),
726            _ => None,
727        }
728    }
729}
730
731/// Request to get contract state from within a delegate.
732#[derive(Serialize, Deserialize, Debug, Clone)]
733pub struct GetContractRequest {
734    pub contract_id: ContractInstanceId,
735    pub context: DelegateContext,
736    pub processed: bool,
737}
738
739impl GetContractRequest {
740    pub fn new(contract_id: ContractInstanceId) -> Self {
741        Self {
742            contract_id,
743            context: Default::default(),
744            processed: false,
745        }
746    }
747}
748
749/// Response containing contract state for a delegate.
750#[derive(Serialize, Deserialize, Debug, Clone)]
751pub struct GetContractResponse {
752    pub contract_id: ContractInstanceId,
753    /// The contract state, or None if the contract was not found locally.
754    pub state: Option<WrappedState>,
755    pub context: DelegateContext,
756}
757
758/// Request to store a new contract from within a delegate.
759#[derive(Serialize, Deserialize, Debug, Clone)]
760pub struct PutContractRequest {
761    /// The contract code and parameters.
762    pub contract: ContractContainer,
763    /// The initial state for the contract.
764    pub state: WrappedState,
765    /// Related contracts that this contract depends on.
766    #[serde(deserialize_with = "RelatedContracts::deser_related_contracts")]
767    pub related_contracts: RelatedContracts<'static>,
768    /// Context for the delegate.
769    pub context: DelegateContext,
770    /// Whether this request has been processed.
771    pub processed: bool,
772}
773
774impl PutContractRequest {
775    pub fn new(
776        contract: ContractContainer,
777        state: WrappedState,
778        related_contracts: RelatedContracts<'static>,
779    ) -> Self {
780        Self {
781            contract,
782            state,
783            related_contracts,
784            context: Default::default(),
785            processed: false,
786        }
787    }
788}
789
790/// Response after attempting to store a contract from a delegate.
791#[derive(Serialize, Deserialize, Debug, Clone)]
792pub struct PutContractResponse {
793    /// The ID of the contract that was (attempted to be) stored.
794    pub contract_id: ContractInstanceId,
795    /// Success (Ok) or error message (Err).
796    pub result: Result<(), String>,
797    /// Context for the delegate.
798    pub context: DelegateContext,
799}
800
801/// Request to update an existing contract's state from within a delegate.
802#[derive(Serialize, Deserialize, Debug, Clone)]
803pub struct UpdateContractRequest {
804    /// The contract to update.
805    pub contract_id: ContractInstanceId,
806    /// The update to apply (full state or delta).
807    #[serde(deserialize_with = "UpdateContractRequest::deser_update_data")]
808    pub update: UpdateData<'static>,
809    /// Context for the delegate.
810    pub context: DelegateContext,
811    /// Whether this request has been processed.
812    pub processed: bool,
813}
814
815impl UpdateContractRequest {
816    pub fn new(contract_id: ContractInstanceId, update: UpdateData<'static>) -> Self {
817        Self {
818            contract_id,
819            update,
820            context: Default::default(),
821            processed: false,
822        }
823    }
824
825    fn deser_update_data<'de, D>(deser: D) -> Result<UpdateData<'static>, D::Error>
826    where
827        D: Deserializer<'de>,
828    {
829        let value = <UpdateData<'de> as Deserialize>::deserialize(deser)?;
830        Ok(value.into_owned())
831    }
832}
833
834/// Response after attempting to update a contract from a delegate.
835#[derive(Serialize, Deserialize, Debug, Clone)]
836pub struct UpdateContractResponse {
837    /// The contract that was updated.
838    pub contract_id: ContractInstanceId,
839    /// Success (Ok) or error message (Err).
840    pub result: Result<(), String>,
841    /// Context for the delegate.
842    pub context: DelegateContext,
843}
844
845/// Request to subscribe to a contract's state changes from within a delegate.
846#[derive(Serialize, Deserialize, Debug, Clone)]
847pub struct SubscribeContractRequest {
848    /// The contract to subscribe to.
849    pub contract_id: ContractInstanceId,
850    /// Context for the delegate.
851    pub context: DelegateContext,
852    /// Whether this request has been processed.
853    pub processed: bool,
854}
855
856impl SubscribeContractRequest {
857    pub fn new(contract_id: ContractInstanceId) -> Self {
858        Self {
859            contract_id,
860            context: Default::default(),
861            processed: false,
862        }
863    }
864}
865
866/// Response after attempting to subscribe to a contract from a delegate.
867///
868/// Note: This confirms subscription registration only. Actual notification
869/// delivery to the delegate when the contract updates is not yet implemented
870/// and will require the async delegate v2 API.
871#[derive(Serialize, Deserialize, Debug, Clone)]
872pub struct SubscribeContractResponse {
873    /// The contract subscribed to.
874    pub contract_id: ContractInstanceId,
875    /// Success (Ok) or error message (Err).
876    pub result: Result<(), String>,
877    /// Context for the delegate.
878    pub context: DelegateContext,
879}
880
881#[serde_as]
882#[derive(Serialize, Deserialize, Debug, Clone)]
883pub struct NotificationMessage<'a>(
884    #[serde_as(as = "serde_with::Bytes")]
885    #[serde(borrow)]
886    Cow<'a, [u8]>,
887);
888
889impl TryFrom<&serde_json::Value> for NotificationMessage<'static> {
890    type Error = ();
891
892    fn try_from(json: &serde_json::Value) -> Result<NotificationMessage<'static>, ()> {
893        // todo: validate format when we have a better idea of what we want here
894        let bytes = serde_json::to_vec(json).unwrap();
895        Ok(Self(Cow::Owned(bytes)))
896    }
897}
898
899impl NotificationMessage<'_> {
900    pub fn into_owned(self) -> NotificationMessage<'static> {
901        NotificationMessage(self.0.into_owned().into())
902    }
903    pub fn bytes(&self) -> &[u8] {
904        self.0.as_ref()
905    }
906}
907
908#[serde_as]
909#[derive(Serialize, Deserialize, Debug, Clone)]
910pub struct ClientResponse<'a>(
911    #[serde_as(as = "serde_with::Bytes")]
912    #[serde(borrow)]
913    Cow<'a, [u8]>,
914);
915
916impl Deref for ClientResponse<'_> {
917    type Target = [u8];
918
919    fn deref(&self) -> &Self::Target {
920        &self.0
921    }
922}
923
924impl ClientResponse<'_> {
925    pub fn new(response: Vec<u8>) -> Self {
926        Self(response.into())
927    }
928    pub fn into_owned(self) -> ClientResponse<'static> {
929        ClientResponse(self.0.into_owned().into())
930    }
931    pub fn bytes(&self) -> &[u8] {
932        self.0.as_ref()
933    }
934}
935
936#[derive(Serialize, Deserialize, Debug, Clone)]
937pub struct UserInputRequest<'a> {
938    pub request_id: u32,
939    #[serde(borrow)]
940    /// An interpretable message by the notification system.
941    pub message: NotificationMessage<'a>,
942    /// If a response is required from the user they can be chosen from this list.
943    pub responses: Vec<ClientResponse<'a>>,
944}
945
946impl UserInputRequest<'_> {
947    pub fn into_owned(self) -> UserInputRequest<'static> {
948        UserInputRequest {
949            request_id: self.request_id,
950            message: self.message.into_owned(),
951            responses: self.responses.into_iter().map(|r| r.into_owned()).collect(),
952        }
953    }
954}
955
956#[doc(hidden)]
957pub(crate) mod wasm_interface {
958    //! Contains all the types to interface between the host environment and
959    //! the wasm module execution.
960    use super::*;
961    use crate::memory::WasmLinearMem;
962
963    #[repr(C)]
964    #[derive(Debug, Clone, Copy)]
965    pub struct DelegateInterfaceResult {
966        ptr: i64,
967        size: u32,
968    }
969
970    impl DelegateInterfaceResult {
971        pub unsafe fn from_raw(ptr: i64, mem: &WasmLinearMem) -> Self {
972            let result = Box::leak(Box::from_raw(crate::memory::buf::compute_ptr(
973                ptr as *mut Self,
974                mem,
975            )));
976            #[cfg(feature = "trace")]
977            {
978                tracing::trace!(
979                    "got FFI result @ {ptr} ({:p}) -> {result:?}",
980                    ptr as *mut Self
981                );
982            }
983            *result
984        }
985
986        #[cfg(feature = "contract")]
987        pub fn into_raw(self) -> i64 {
988            #[cfg(feature = "trace")]
989            {
990                tracing::trace!("returning FFI -> {self:?}");
991            }
992            let ptr = Box::into_raw(Box::new(self));
993            #[cfg(feature = "trace")]
994            {
995                tracing::trace!("FFI result ptr: {ptr:p} ({}i64)", ptr as i64);
996            }
997            ptr as _
998        }
999
1000        pub unsafe fn unwrap(
1001            self,
1002            mem: WasmLinearMem,
1003        ) -> Result<Vec<OutboundDelegateMsg>, DelegateError> {
1004            let ptr = crate::memory::buf::compute_ptr(self.ptr as *mut u8, &mem);
1005            let serialized = std::slice::from_raw_parts(ptr as *const u8, self.size as _);
1006            let value: Result<Vec<OutboundDelegateMsg>, DelegateError> =
1007                bincode::deserialize(serialized)
1008                    .map_err(|e| DelegateError::Other(format!("{e}")))?;
1009            #[cfg(feature = "trace")]
1010            {
1011                tracing::trace!(
1012                    "got result through FFI; addr: {:p} ({}i64, mapped: {ptr:p})
1013                     serialized: {serialized:?}
1014                     value: {value:?}",
1015                    self.ptr as *mut u8,
1016                    self.ptr
1017                );
1018            }
1019            value
1020        }
1021    }
1022
1023    impl From<Result<Vec<OutboundDelegateMsg>, DelegateError>> for DelegateInterfaceResult {
1024        fn from(value: Result<Vec<OutboundDelegateMsg>, DelegateError>) -> Self {
1025            let serialized = bincode::serialize(&value).unwrap();
1026            let size = serialized.len() as _;
1027            let ptr = serialized.as_ptr();
1028            #[cfg(feature = "trace")]
1029            {
1030                tracing::trace!(
1031                    "sending result through FFI; addr: {ptr:p} ({}),\n  serialized: {serialized:?}\n  value: {value:?}",
1032                    ptr as i64
1033                );
1034            }
1035            std::mem::forget(serialized);
1036            Self {
1037                ptr: ptr as i64,
1038                size,
1039            }
1040        }
1041    }
1042}