Skip to main content

pyde_rust_sdk/contract/
runtime.rs

1//! Untyped contract runtime — `Contract<P>` wraps a provider +
2//! contract address + parsed ABI, and exposes dynamic
3//! `call(name, args)` / `send(name, args, signer)` / event filter
4//! helpers.
5//!
6//! The `pyde_abi!` macro generates a typed shell around this
7//! runtime; dapps that build calldata by hand can use this module
8//! directly.
9
10use std::sync::Arc;
11
12use crate::error::SdkError;
13use crate::provider::{PendingTx, Provider};
14use crate::signer::Signer;
15use crate::tx::TxBuilder;
16use crate::types::{
17    Address, CallOverrides, CallPayload, CallRequest, ContractAbi, Event, EventAbi, FunctionAbi,
18    FunctionAttrs, LogFilter, Tx, TxType,
19};
20
21use super::codec::{decode_return, encode_calldata, Value};
22
23/// Untyped contract handle — provider + address + ABI.
24///
25/// Built from a parsed [`ContractAbi`] (typically via
26/// [`crate::abi::extract_abi`] on the deployed bytecode, or from
27/// the inline ABI shipped with a `pyde_abi!` invocation).
28pub struct Contract {
29    address: Address,
30    abi: ContractAbi,
31    provider: Arc<dyn Provider>,
32}
33
34impl Contract {
35    /// Build a handle from address + ABI + provider.
36    #[must_use]
37    pub fn new(address: Address, abi: ContractAbi, provider: Arc<dyn Provider>) -> Self {
38        Self {
39            address,
40            abi,
41            provider,
42        }
43    }
44
45    /// Resolve a contract by name via [`Provider::resolve_name`] and
46    /// fetch its ABI via [`Provider::get_contract_code`] +
47    /// [`crate::abi::extract_abi`].
48    ///
49    /// # Errors
50    /// - [`SdkError::InvalidArgument`] if the name doesn't resolve.
51    /// - Any error from the underlying provider calls or the ABI
52    ///   extraction.
53    pub async fn load(name: &str, provider: Arc<dyn Provider>) -> Result<Self, SdkError> {
54        let address = provider.resolve_name(name).await?.ok_or_else(|| {
55            SdkError::InvalidArgument(format!("contract {name:?} is not registered"))
56        })?;
57        Self::load_at(address, provider).await
58    }
59
60    /// Load a contract at a known address. Fetches the bytecode
61    /// and parses the embedded `pyde.abi`.
62    ///
63    /// # Errors
64    /// - [`SdkError::InvalidArgument`] if no contract is deployed
65    ///   at `address`.
66    /// - Any error from [`Provider::get_contract_code`] or
67    ///   [`crate::abi::extract_abi`].
68    pub async fn load_at(address: Address, provider: Arc<dyn Provider>) -> Result<Self, SdkError> {
69        let bytecode = provider.get_contract_code(&address).await?;
70        if bytecode.is_empty() {
71            return Err(SdkError::InvalidArgument(format!(
72                "no contract code at {address}"
73            )));
74        }
75        let abi = crate::abi::extract_abi(&bytecode)?;
76        Ok(Self::new(address, abi, provider))
77    }
78
79    /// Contract address.
80    #[must_use]
81    pub fn address(&self) -> Address {
82        self.address
83    }
84
85    /// Parsed ABI.
86    #[must_use]
87    pub fn abi(&self) -> &ContractAbi {
88        &self.abi
89    }
90
91    /// Underlying provider.
92    #[must_use]
93    pub fn provider(&self) -> Arc<dyn Provider> {
94        Arc::clone(&self.provider)
95    }
96
97    // ── View call ───────────────────────────────────────────────
98
99    /// Execute a read-only call.
100    ///
101    /// Builds a [`CallRequest`] from the function name + args,
102    /// dispatches `pyde_call`, and decodes the return data per the
103    /// ABI's `returns` field.
104    ///
105    /// # Errors
106    /// - [`SdkError::InvalidArgument`] for unknown function names,
107    ///   arity mismatches, calling a non-view function.
108    /// - Any error from [`Provider::call`] or the return decoder.
109    pub async fn call(&self, name: &str, args: Vec<Value>) -> Result<Option<Value>, SdkError> {
110        self.call_with(name, args, CallOverrides::default()).await
111    }
112
113    /// Execute a read-only call with overrides on `from`, attached
114    /// value, and gas budget.
115    ///
116    /// # Errors
117    /// Same as [`Self::call`].
118    pub async fn call_with(
119        &self,
120        name: &str,
121        args: Vec<Value>,
122        overrides: CallOverrides,
123    ) -> Result<Option<Value>, SdkError> {
124        let function = self.lookup_function(name)?;
125        let calldata = encode_calldata(&function.params, &args)?;
126        let payload = CallPayload {
127            function: function.name.clone(),
128            calldata,
129        };
130        let payload_bytes = borsh::to_vec(&payload)
131            .map_err(|e| SdkError::Other(format!("borsh encode CallPayload: {e}")))?;
132        let req = CallRequest {
133            to: self.address.to_hex(),
134            data: format!("0x{}", hex::encode(&payload_bytes)),
135            from: overrides.from.map(|a| a.to_hex()),
136            value: overrides.value.map(|v| format!("0x{v:x}")),
137            gas: overrides.gas_limit.map(|g| format!("0x{g:x}")),
138        };
139        let return_bytes = self.provider.call(&req).await?;
140        decode_return(&function.returns, &return_bytes)
141    }
142
143    // ── State-mutating send ────────────────────────────────────
144
145    /// Build the unsigned [`Tx`] for a state-mutating call.
146    ///
147    /// Useful when the caller wants to sign + submit the tx out-of-
148    /// band; for the common path use [`Self::send`] instead.
149    ///
150    /// # Errors
151    /// Same arity / function-lookup errors as [`Self::call`].
152    //
153    // 8 args by design — every field is independently meaningful
154    // for a chain-submitted Tx and there's no useful grouping.
155    // Callers that want to reuse defaults should drive the call via
156    // the typed `pyde_abi!`-generated wrappers or via [`Self::send`].
157    #[allow(clippy::too_many_arguments)]
158    pub fn build_tx(
159        &self,
160        from: Address,
161        name: &str,
162        args: Vec<Value>,
163        chain_id: u64,
164        nonce: u64,
165        gas_limit: u64,
166        value: u128,
167    ) -> Result<Tx, SdkError> {
168        let function = self.lookup_function(name)?;
169        if value > 0 && !function.attrs.is_payable() {
170            return Err(SdkError::InvalidArgument(format!(
171                "function {name:?} is not payable; cannot attach value"
172            )));
173        }
174        let calldata = encode_calldata(&function.params, &args)?;
175        let payload = CallPayload {
176            function: function.name.clone(),
177            calldata,
178        };
179        let data = borsh::to_vec(&payload)
180            .map_err(|e| SdkError::Other(format!("borsh encode CallPayload: {e}")))?;
181        TxBuilder::new()
182            .from(from)
183            .to(self.address)
184            .data(data)
185            .gas_limit(gas_limit)
186            .nonce(nonce)
187            .chain_id(chain_id)
188            .value(value)
189            .tx_type(TxType::Standard)
190            .build()
191    }
192
193    /// Sign + submit a state-mutating call.
194    ///
195    /// Looks up the function in the ABI, builds calldata, fetches
196    /// `chain_id` + `nonce` from the provider, signs via `signer`,
197    /// and submits — returning a [`PendingTx`] handle for the
198    /// caller to await.
199    ///
200    /// # Errors
201    /// - All errors from [`Self::build_tx`].
202    /// - Any error from the provider or the signer.
203    pub async fn send(
204        &self,
205        signer: &dyn Signer,
206        name: &str,
207        args: Vec<Value>,
208        gas_limit: u64,
209        value: u128,
210    ) -> Result<PendingTx, SdkError> {
211        let chain_id = self.provider.chain_id().await?;
212        let nonce = self.provider.get_nonce(&signer.address()).await?;
213        let mut tx = self.build_tx(
214            signer.address(),
215            name,
216            args,
217            chain_id,
218            nonce,
219            gas_limit,
220            value,
221        )?;
222        signer.sign_tx(&mut tx).await?;
223        let hash = self.provider.send_raw_transaction(&tx).await?;
224        Ok(PendingTx::new(hash, Arc::clone(&self.provider)))
225    }
226
227    // ── Event helpers ──────────────────────────────────────────
228
229    /// Build a [`LogFilter`] scoped to this contract's address.
230    /// Pass to [`Provider::get_logs`] or
231    /// [`crate::ws::WsProvider::subscribe_logs`].
232    #[must_use]
233    pub fn event_filter(&self) -> LogFilter {
234        LogFilter {
235            contracts: vec![self.address.to_hex()],
236            ..Default::default()
237        }
238    }
239
240    /// Build a [`LogFilter`] scoped to a single named event on this
241    /// contract. The event signature topic is placed at position 0
242    /// of the `topics` filter array; additional indexed-parameter
243    /// constraints can be set by the caller after the filter is
244    /// returned.
245    ///
246    /// # Errors
247    /// Returns [`SdkError::InvalidArgument`] for unknown event names.
248    pub fn event_filter_for(&self, event_name: &str) -> Result<LogFilter, SdkError> {
249        let ev = self
250            .abi
251            .event_by_name(event_name)
252            .ok_or_else(|| SdkError::InvalidArgument(format!("event {event_name:?} not in ABI")))?;
253        let topic0 = event_signature_topic(ev);
254        Ok(LogFilter {
255            contracts: vec![self.address.to_hex()],
256            topics: vec![Some(vec![format!("0x{}", hex::encode(topic0))])],
257            ..Default::default()
258        })
259    }
260
261    /// Look up a function in the ABI, returning a clear error for
262    /// unknown names + view-mode violations.
263    fn lookup_function(&self, name: &str) -> Result<&FunctionAbi, SdkError> {
264        let f = self
265            .abi
266            .function_by_name(name)
267            .ok_or_else(|| SdkError::InvalidArgument(format!("function {name:?} not in ABI")))?;
268        if f.attrs.is_constructor() && !f.attrs.has(FunctionAttrs::ENTRY) {
269            return Err(SdkError::InvalidArgument(format!(
270                "function {name:?} is the constructor — deploy-time only"
271            )));
272        }
273        Ok(f)
274    }
275}
276
277impl std::fmt::Debug for Contract {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        f.debug_struct("Contract")
280            .field("address", &self.address)
281            .field("name", &self.abi.name)
282            .field("functions", &self.abi.functions.len())
283            .finish()
284    }
285}
286
287// ── Event signature topic ──────────────────────────────────────
288
289/// Compute the topic-0 hash for an event signature.
290///
291/// Signature shape: `"name(ty1,ty2,…)"` (parameter type names
292/// joined by commas). Hash via Blake3 (Pyde's high-volume native
293/// path per the dual-hash strategy).
294#[must_use]
295pub fn event_signature_topic(event: &EventAbi) -> [u8; 32] {
296    let mut sig = String::new();
297    sig.push_str(&event.name);
298    sig.push('(');
299    for (i, p) in event.params.iter().enumerate() {
300        if i > 0 {
301            sig.push(',');
302        }
303        write_canonical_type(&mut sig, &p.ty);
304    }
305    sig.push(')');
306    *blake3::hash(sig.as_bytes()).as_bytes()
307}
308
309fn write_canonical_type(out: &mut String, ty: &crate::types::ParamType) {
310    use crate::types::ParamType as P;
311    // Canonical event-signature type names follow the Solidity
312    // convention (`uintN` / `intN`) — the same convention the
313    // otigen `declare_events!` macro and downstream consumers
314    // (explorers, indexers, ts-sdk) use. Authors writing
315    // `signature = "Foo(uint64)"` in `otigen.toml` get a topic-0
316    // that matches; the SDK's reconstruction from the parsed
317    // ABI's typed params must use the same names to round-trip.
318    match ty {
319        P::U8 => out.push_str("uint8"),
320        P::U16 => out.push_str("uint16"),
321        P::U32 => out.push_str("uint32"),
322        P::U64 => out.push_str("uint64"),
323        P::U128 => out.push_str("uint128"),
324        P::I8 => out.push_str("int8"),
325        P::I16 => out.push_str("int16"),
326        P::I32 => out.push_str("int32"),
327        P::I64 => out.push_str("int64"),
328        P::I128 => out.push_str("int128"),
329        P::Bool => out.push_str("bool"),
330        P::Address => out.push_str("address"),
331        P::Bytes => out.push_str("bytes"),
332        P::String => out.push_str("string"),
333        P::FixedBytes(n) => {
334            out.push_str("bytes");
335            out.push_str(&n.to_string());
336        }
337        P::Vec(inner) => {
338            write_canonical_type(out, inner);
339            out.push_str("[]");
340        }
341        P::Map { key, value } => {
342            out.push_str("map<");
343            write_canonical_type(out, key);
344            out.push(',');
345            write_canonical_type(out, value);
346            out.push('>');
347        }
348        P::Option(inner) => {
349            out.push_str("option<");
350            write_canonical_type(out, inner);
351            out.push('>');
352        }
353        P::Custom(name) => {
354            // Custom types refer to a named struct/enum; the canonical
355            // signature uses the name as-is.
356            out.push_str(name);
357        }
358    }
359}
360
361// ── Decoded event ──────────────────────────────────────────────
362
363/// Decoded event — typed name + (topic, data) split per ABI.
364///
365/// Returned by [`Contract::decode_event`]. Indexed parameters are
366/// preserved in `topics` (one per indexed parameter, in declaration
367/// order — *after* topic 0, the event signature). Non-indexed
368/// parameters are Borsh-decoded from `data`.
369#[derive(Debug, Clone)]
370pub struct DecodedEvent {
371    /// Event name as declared in the ABI.
372    pub name: String,
373    /// Indexed parameter values in declaration order. v1 stores
374    /// each indexed value as a raw 32-byte topic — the caller's
375    /// typed wrapper is responsible for interpreting the bytes
376    /// (the SDK doesn't yet attempt to decode arbitrary types from
377    /// 32-byte topic words).
378    pub indexed: Vec<[u8; 32]>,
379    /// Non-indexed parameter values, in declaration order, decoded
380    /// from the event `data` payload.
381    pub data: Vec<Value>,
382}
383
384impl Contract {
385    /// Decode a raw [`Event`] log into a typed [`DecodedEvent`] by
386    /// matching the topic-0 signature against this contract's ABI.
387    ///
388    /// # Errors
389    /// - [`SdkError::InvalidResponse`] if the log's address doesn't
390    ///   match this contract, if topic 0 is missing, if no event
391    ///   signature matches, or if `data` doesn't decode.
392    pub fn decode_event(&self, log: &Event) -> Result<DecodedEvent, SdkError> {
393        let log_addr = Address::from_hex(&log.contract_addr)?;
394        if log_addr != self.address {
395            return Err(SdkError::InvalidResponse(format!(
396                "event from {log_addr}, expected {}",
397                self.address
398            )));
399        }
400        let topic0_hex = log.topics.first().ok_or_else(|| {
401            SdkError::InvalidResponse("event has no topic 0 — cannot decode".into())
402        })?;
403        let topic0_bytes = hex::decode(topic0_hex.trim_start_matches("0x"))
404            .map_err(|e| SdkError::InvalidResponse(format!("topic 0 hex: {e}")))?;
405        if topic0_bytes.len() != 32 {
406            return Err(SdkError::InvalidResponse(format!(
407                "topic 0 must be 32 bytes; got {}",
408                topic0_bytes.len()
409            )));
410        }
411        let mut topic0_arr = [0u8; 32];
412        topic0_arr.copy_from_slice(&topic0_bytes);
413
414        let ev_abi = self
415            .abi
416            .events
417            .iter()
418            .find(|e| event_signature_topic(e) == topic0_arr)
419            .ok_or_else(|| {
420                SdkError::InvalidResponse(format!("no event in ABI matches topic 0 {topic0_hex}"))
421            })?;
422
423        // Collect indexed-parameter topics (everything after topic 0).
424        let mut indexed = Vec::with_capacity(ev_abi.topic_count() as usize);
425        for t_hex in log.topics.iter().skip(1) {
426            let bytes = hex::decode(t_hex.trim_start_matches("0x"))
427                .map_err(|e| SdkError::InvalidResponse(format!("topic hex: {e}")))?;
428            if bytes.len() != 32 {
429                return Err(SdkError::InvalidResponse(format!(
430                    "topic must be 32 bytes; got {}",
431                    bytes.len()
432                )));
433            }
434            let mut arr = [0u8; 32];
435            arr.copy_from_slice(&bytes);
436            indexed.push(arr);
437        }
438
439        // Decode non-indexed parameters from `data`.
440        let data_bytes = log.data_bytes();
441        let mut slice = data_bytes.as_slice();
442        let mut data_values = Vec::new();
443        for (i, p) in ev_abi.params.iter().enumerate() {
444            if ev_abi.is_indexed(i as u8) {
445                continue;
446            }
447            let v = super::codec::decode_value_inplace(&p.ty, &mut slice)?;
448            data_values.push(v);
449        }
450        if !slice.is_empty() {
451            return Err(SdkError::InvalidResponse(format!(
452                "trailing {} bytes after decoding event data",
453                slice.len()
454            )));
455        }
456
457        Ok(DecodedEvent {
458            name: ev_abi.name.clone(),
459            indexed,
460            data: data_values,
461        })
462    }
463}
464
465#[cfg(test)]
466mod tests {
467    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
468
469    use super::*;
470    use crate::types::{
471        ContractType, EventAbi, FunctionAbi, FunctionAttrs, ParamAbi, ParamType, StateSchema,
472    };
473
474    fn sample_abi() -> ContractAbi {
475        ContractAbi {
476            pyde_abi_version: ContractAbi::V1_2,
477            contract_type: ContractType::Contract,
478            functions: vec![
479                FunctionAbi {
480                    selector: [1, 2, 3, 4],
481                    name: "get_balance".into(),
482                    attrs: FunctionAttrs::from_bits(FunctionAttrs::ENTRY | FunctionAttrs::VIEW),
483                    params: vec![ParamAbi {
484                        name: "of".into(),
485                        ty: ParamType::Address,
486                    }],
487                    returns: Some(ParamType::U128),
488                },
489                FunctionAbi {
490                    selector: [5, 6, 7, 8],
491                    name: "transfer".into(),
492                    attrs: FunctionAttrs::from_bits(FunctionAttrs::ENTRY),
493                    params: vec![
494                        ParamAbi {
495                            name: "to".into(),
496                            ty: ParamType::Address,
497                        },
498                        ParamAbi {
499                            name: "amount".into(),
500                            ty: ParamType::U128,
501                        },
502                    ],
503                    returns: None,
504                },
505            ],
506            state_schema_hash: [0u8; 32],
507            constructor_index: None,
508            fallback_index: None,
509            receive_index: None,
510            name: "Token".into(),
511            version: "0.1.0".into(),
512            events: vec![EventAbi {
513                name: "Transferred".into(),
514                params: vec![
515                    ParamAbi {
516                        name: "from".into(),
517                        ty: ParamType::Address,
518                    },
519                    ParamAbi {
520                        name: "to".into(),
521                        ty: ParamType::Address,
522                    },
523                    ParamAbi {
524                        name: "amount".into(),
525                        ty: ParamType::U128,
526                    },
527                ],
528                indexed_mask: 0b011,
529            }],
530            parachain_imports: vec![],
531            state_schema: StateSchema::empty(),
532            types: vec![],
533        }
534    }
535
536    #[test]
537    fn event_signature_topic_is_stable() {
538        let ev = EventAbi {
539            name: "Transfer".into(),
540            params: vec![
541                ParamAbi {
542                    name: "from".into(),
543                    ty: ParamType::Address,
544                },
545                ParamAbi {
546                    name: "to".into(),
547                    ty: ParamType::Address,
548                },
549                ParamAbi {
550                    name: "amount".into(),
551                    ty: ParamType::U128,
552                },
553            ],
554            indexed_mask: 0b011,
555        };
556        let topic = event_signature_topic(&ev);
557        let expected = blake3::hash(b"Transfer(address,address,uint128)");
558        assert_eq!(topic, *expected.as_bytes());
559    }
560
561    #[test]
562    fn function_lookup_rejects_unknown() {
563        // We don't need a live provider for this — build directly.
564        let abi = sample_abi();
565        let bad = abi.function_by_name("nope");
566        assert!(bad.is_none());
567        let good = abi.function_by_name("transfer");
568        assert!(good.is_some());
569    }
570
571    #[test]
572    fn canonical_event_signature_format() {
573        let mut s = String::new();
574        write_canonical_type(&mut s, &ParamType::Vec(Box::new(ParamType::U64)));
575        assert_eq!(s, "uint64[]");
576        let mut s = String::new();
577        write_canonical_type(
578            &mut s,
579            &ParamType::Map {
580                key: Box::new(ParamType::String),
581                value: Box::new(ParamType::U128),
582            },
583        );
584        assert_eq!(s, "map<string,uint128>");
585        let mut s = String::new();
586        write_canonical_type(&mut s, &ParamType::FixedBytes(8));
587        assert_eq!(s, "bytes8");
588        let mut s = String::new();
589        write_canonical_type(&mut s, &ParamType::Option(Box::new(ParamType::Bool)));
590        assert_eq!(s, "option<bool>");
591    }
592}