1use 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
23pub struct Contract {
29 address: Address,
30 abi: ContractAbi,
31 provider: Arc<dyn Provider>,
32}
33
34impl Contract {
35 #[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 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 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 #[must_use]
81 pub fn address(&self) -> Address {
82 self.address
83 }
84
85 #[must_use]
87 pub fn abi(&self) -> &ContractAbi {
88 &self.abi
89 }
90
91 #[must_use]
93 pub fn provider(&self) -> Arc<dyn Provider> {
94 Arc::clone(&self.provider)
95 }
96
97 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 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 #[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 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 #[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 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 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#[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 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 out.push_str(name);
357 }
358 }
359}
360
361#[derive(Debug, Clone)]
370pub struct DecodedEvent {
371 pub name: String,
373 pub indexed: Vec<[u8; 32]>,
379 pub data: Vec<Value>,
382}
383
384impl Contract {
385 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 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 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 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}