1use std::{collections::HashMap, path::PathBuf, str::FromStr};
2
3use crate::{
4 api::DebugApi,
5 executor::debug::{
6 ContractContainer, ContractDebugInstance, ContractDebugStack, ContractDebugWhiteboxLambda,
7 },
8 multiversx_sc::{
9 codec::{TopDecode, TopEncode},
10 contract_base::{CallableContract, ContractBase},
11 types::{heap::Address, EsdtLocalRole},
12 },
13 scenario_model::{Account, BytesValue, ScCallStep, SetStateStep},
14 testing_framework::raw_converter::bytes_to_hex,
15 ScenarioWorld,
16};
17use multiversx_chain_scenario_format::interpret_trait::InterpretableFrom;
18use multiversx_chain_vm::host::context::{TxFunctionName, TxResult};
19use multiversx_sc::types::{BigUint, H256};
20use num_traits::Zero;
21
22use super::{
23 tx_mandos::{ScCallMandos, TxExpectMandos},
24 AddressFactory, MandosGenerator, ScQueryMandos,
25};
26
27pub use multiversx_chain_vm::host::context::TxTokenTransfer;
28
29#[derive(Clone)]
30pub struct ContractObjWrapper<
31 CB: ContractBase<Api = DebugApi> + CallableContract + 'static,
32 ContractObjBuilder: 'static + Copy + Fn() -> CB,
33> {
34 pub(crate) address: Address,
35 pub(crate) obj_builder: ContractObjBuilder,
36}
37
38impl<CB, ContractObjBuilder> ContractObjWrapper<CB, ContractObjBuilder>
39where
40 CB: ContractBase<Api = DebugApi> + CallableContract + 'static,
41 ContractObjBuilder: 'static + Copy + Fn() -> CB,
42{
43 pub(crate) fn new(address: Address, obj_builder: ContractObjBuilder) -> Self {
44 ContractObjWrapper {
45 address,
46 obj_builder,
47 }
48 }
49
50 pub fn address_ref(&self) -> &Address {
51 &self.address
52 }
53}
54
55pub struct BlockchainStateWrapper {
56 world: ScenarioWorld,
57 address_factory: AddressFactory,
58 address_to_code_path: HashMap<Address, Vec<u8>>,
59 current_tx_id: u64,
60 workspace_path: PathBuf,
61}
62
63impl BlockchainStateWrapper {
64 #[allow(clippy::new_without_default)]
65 pub fn new() -> Self {
66 let mut current_dir = std::env::current_dir().unwrap();
67 current_dir.push(PathBuf::from_str("scenarios/").unwrap());
68
69 let mut world = ScenarioWorld::debugger();
70 world.start_trace();
71
72 BlockchainStateWrapper {
73 world,
74 address_factory: AddressFactory::new(),
75 address_to_code_path: HashMap::new(),
76 current_tx_id: 0,
77 workspace_path: current_dir,
78 }
79 }
80
81 pub fn write_mandos_output(mut self, file_name: &str) {
82 let mut full_path = self.workspace_path;
83 full_path.push(file_name);
84
85 if let Some(trace) = &mut self.world.get_mut_debugger_backend().trace {
86 trace.write_scenario_trace(&full_path);
87 }
88 }
89
90 pub fn check_egld_balance(&self, address: &Address, expected_balance: &num_bigint::BigUint) {
91 let actual_balance = match &self.world.get_state().accounts.get(address) {
92 Some(acc) => acc.egld_balance.clone(),
93 None => num_bigint::BigUint::zero(),
94 };
95
96 assert!(
97 expected_balance == &actual_balance,
98 "EGLD balance mismatch for address {}\n Expected: {}\n Have: {}\n",
99 address_to_hex(address),
100 expected_balance,
101 actual_balance
102 );
103 }
104
105 pub fn check_esdt_balance(
106 &self,
107 address: &Address,
108 token_id: &[u8],
109 expected_balance: &num_bigint::BigUint,
110 ) {
111 let actual_balance = match &self.world.get_state().accounts.get(address) {
112 Some(acc) => acc.esdt.get_esdt_balance(token_id, 0),
113 None => num_bigint::BigUint::zero(),
114 };
115
116 assert!(
117 expected_balance == &actual_balance,
118 "ESDT balance mismatch for address {}\n Token: {}\n Expected: {}\n Have: {}\n",
119 address_to_hex(address),
120 String::from_utf8(token_id.to_vec()).unwrap(),
121 expected_balance,
122 actual_balance
123 );
124 }
125
126 pub fn check_nft_balance<T>(
127 &self,
128 address: &Address,
129 token_id: &[u8],
130 nonce: u64,
131 expected_balance: &num_bigint::BigUint,
132 opt_expected_attributes: Option<&T>,
133 ) where
134 T: TopEncode + TopDecode + PartialEq + core::fmt::Debug,
135 {
136 let (actual_balance, actual_attributes_serialized) =
137 match &self.world.get_state().accounts.get(address) {
138 Some(acc) => {
139 let esdt_data = acc.esdt.get_by_identifier_or_default(token_id);
140 let opt_instance = esdt_data.instances.get_by_nonce(nonce);
141
142 match opt_instance {
143 Some(instance) => (
144 instance.balance.clone(),
145 instance.metadata.attributes.clone(),
146 ),
147 None => (num_bigint::BigUint::zero(), Vec::new()),
148 }
149 }
150 None => (num_bigint::BigUint::zero(), Vec::new()),
151 };
152
153 assert!(
154 expected_balance == &actual_balance,
155 "ESDT NFT balance mismatch for address {}\n Token: {}, nonce: {}\n Expected: {}\n Have: {}\n",
156 address_to_hex(address),
157 String::from_utf8(token_id.to_vec()).unwrap(),
158 nonce,
159 expected_balance,
160 actual_balance
161 );
162
163 if let Some(expected_attributes) = opt_expected_attributes {
164 let actual_attributes = T::top_decode(actual_attributes_serialized).unwrap();
165 assert!(
166 expected_attributes == &actual_attributes,
167 "ESDT NFT attributes mismatch for address {}\n Token: {}, nonce: {}\n Expected: {:?}\n Have: {:?}\n",
168 address_to_hex(address),
169 String::from_utf8(token_id.to_vec()).unwrap(),
170 nonce,
171 expected_attributes,
172 actual_attributes,
173 );
174 }
175 }
176}
177
178impl BlockchainStateWrapper {
179 pub fn create_user_account(&mut self, egld_balance: &num_bigint::BigUint) -> Address {
180 let address = self.address_factory.new_address();
181 self.world
182 .create_account_raw(&address, BigUint::from(egld_balance));
183
184 address
185 }
186
187 pub fn create_user_account_fixed_address(
188 &mut self,
189 address: &Address,
190 egld_balance: &num_bigint::BigUint,
191 ) {
192 self.world
193 .create_account_raw(address, BigUint::from(egld_balance));
194 }
195
196 pub fn create_sc_account<CB, ContractObjBuilder>(
197 &mut self,
198 egld_balance: &num_bigint::BigUint,
199 owner: Option<&Address>,
200 obj_builder: ContractObjBuilder,
201 contract_wasm_path: &str,
202 ) -> ContractObjWrapper<CB, ContractObjBuilder>
203 where
204 CB: ContractBase<Api = DebugApi> + CallableContract + 'static,
205 ContractObjBuilder: 'static + Copy + Fn() -> CB,
206 {
207 let address = self.address_factory.new_sc_address();
208 self.create_sc_account_fixed_address(
209 &address,
210 egld_balance,
211 owner,
212 obj_builder,
213 contract_wasm_path,
214 )
215 }
216
217 pub fn create_sc_account_fixed_address<CB, ContractObjBuilder>(
218 &mut self,
219 address: &Address,
220 egld_balance: &num_bigint::BigUint,
221 owner: Option<&Address>,
222 obj_builder: ContractObjBuilder,
223 contract_wasm_path: &str,
224 ) -> ContractObjWrapper<CB, ContractObjBuilder>
225 where
226 CB: ContractBase<Api = DebugApi> + CallableContract + 'static,
227 ContractObjBuilder: 'static + Copy + Fn() -> CB,
228 {
229 if !address.is_smart_contract_address() {
230 panic!("Invalid SC Address: {:?}", address_to_hex(address))
231 }
232
233 let mut wasm_full_path = std::env::current_dir().unwrap();
234 wasm_full_path.push(PathBuf::from_str(contract_wasm_path).unwrap());
235
236 let path_diff =
237 pathdiff::diff_paths(wasm_full_path.clone(), self.workspace_path.clone()).unwrap();
238 let path_str = path_diff.to_str().unwrap();
239
240 let contract_code_expr_str = format!("file:{path_str}");
241 let contract_code_expr = BytesValue::interpret_from(
242 contract_code_expr_str.clone(),
243 &self.world.interpreter_context(),
244 );
245
246 let mut account = Account::new()
247 .balance(egld_balance)
248 .code(contract_code_expr.clone());
249 if let Some(owner) = owner {
250 account = account.owner(owner);
251 }
252
253 self.world
254 .set_state_step(SetStateStep::new().put_account(address, account));
255
256 self.address_to_code_path
257 .insert(address.clone(), contract_code_expr_str.into_bytes());
258
259 let contains_contract = self
260 .world
261 .get_mut_debugger_backend()
262 .vm_runner
263 .contract_map_ref
264 .lock()
265 .contains_contract(contract_code_expr.value.as_slice());
266 if !contains_contract {
267 let contract_obj = create_contract_obj_box(obj_builder);
268
269 self.world
270 .get_mut_debugger_backend()
271 .vm_runner
272 .contract_map_ref
273 .lock()
274 .register_contract(
275 contract_code_expr.value,
276 ContractContainer::new(contract_obj, None, false),
277 );
278 }
279
280 ContractObjWrapper::new(address.clone(), obj_builder)
281 }
282
283 pub fn create_account_raw(
284 &mut self,
285 address: &Address,
286 egld_balance: &num_bigint::BigUint,
287 _owner: Option<&Address>,
288 _sc_identifier: Option<Vec<u8>>,
289 _sc_mandos_path_expr: Option<Vec<u8>>,
290 ) {
291 self.world
292 .create_account_raw(address, BigUint::from(egld_balance));
293 }
294
295 pub fn prepare_deploy_from_sc<CB, ContractObjBuilder>(
298 &mut self,
299 deployer: &Address,
300 obj_builder: ContractObjBuilder,
301 ) -> ContractObjWrapper<CB, ContractObjBuilder>
302 where
303 CB: ContractBase<Api = DebugApi> + CallableContract + 'static,
304 ContractObjBuilder: 'static + Copy + Fn() -> CB,
305 {
306 let deployer_acc = self
307 .world
308 .get_state()
309 .accounts
310 .get(deployer)
311 .unwrap()
312 .clone();
313
314 let new_sc_address = self.address_factory.new_sc_address();
315 self.world.get_mut_state().put_new_address(
316 deployer.clone(),
317 deployer_acc.nonce,
318 new_sc_address.clone(),
319 );
320
321 ContractObjWrapper::new(new_sc_address, obj_builder)
322 }
323
324 pub fn upgrade_wrapper<OldCB, OldContractObjBuilder, NewCB, NewContractObjBuilder>(
325 &self,
326 old_wrapper: ContractObjWrapper<OldCB, OldContractObjBuilder>,
327 new_builder: NewContractObjBuilder,
328 ) -> ContractObjWrapper<NewCB, NewContractObjBuilder>
329 where
330 OldCB: ContractBase<Api = DebugApi> + CallableContract + 'static,
331 OldContractObjBuilder: 'static + Copy + Fn() -> OldCB,
332 NewCB: ContractBase<Api = DebugApi> + CallableContract + 'static,
333 NewContractObjBuilder: 'static + Copy + Fn() -> NewCB,
334 {
335 ContractObjWrapper::new(old_wrapper.address, new_builder)
336 }
337
338 pub fn set_egld_balance(&mut self, address: &Address, balance: &num_bigint::BigUint) {
339 self.world.set_egld_balance(address, BigUint::from(balance));
340 }
341
342 pub fn set_esdt_balance(
343 &mut self,
344 address: &Address,
345 token_id: &[u8],
346 balance: &num_bigint::BigUint,
347 ) {
348 self.world
349 .set_esdt_balance(address, token_id, BigUint::from(balance));
350 }
351
352 pub fn set_nft_balance<T: TopEncode>(
353 &mut self,
354 address: &Address,
355 token_id: &[u8],
356 nonce: u64,
357 balance: &num_bigint::BigUint,
358 attributes: &T,
359 ) {
360 self.world.set_nft_balance_all_properties(
361 address,
362 token_id,
363 nonce,
364 BigUint::from(balance),
365 attributes,
366 0,
367 None::<Address>,
368 None,
369 None,
370 &[],
371 );
372 }
373
374 pub fn set_developer_rewards(
375 &mut self,
376 address: &Address,
377 developer_rewards: num_bigint::BigUint,
378 ) {
379 self.world
380 .set_developer_rewards(address, &developer_rewards);
381 }
382
383 #[allow(clippy::too_many_arguments)]
384 pub fn set_nft_balance_all_properties<T: TopEncode>(
385 &mut self,
386 address: &Address,
387 token_id: &[u8],
388 nonce: u64,
389 balance: &num_bigint::BigUint,
390 attributes: &T,
391 royalties: u64,
392 creator: Option<&Address>,
393 name: Option<&[u8]>,
394 hash: Option<&[u8]>,
395 uris: &[Vec<u8>],
396 ) {
397 self.world.set_nft_balance_all_properties(
398 address,
399 token_id,
400 nonce,
401 BigUint::from(balance),
402 attributes,
403 royalties,
404 creator,
405 name,
406 hash,
407 uris,
408 );
409 }
410
411 pub fn set_esdt_local_roles(
412 &mut self,
413 address: &Address,
414 token_id: &[u8],
415 roles: &[EsdtLocalRole],
416 ) {
417 self.world.set_esdt_local_roles(address, token_id, roles);
418 }
419
420 pub fn set_block_epoch(&mut self, block_epoch: u64) {
421 self.world
422 .set_state_step(SetStateStep::new().block_epoch(block_epoch));
423 }
424
425 pub fn set_block_nonce(&mut self, block_nonce: u64) {
426 self.world
427 .set_state_step(SetStateStep::new().block_nonce(block_nonce));
428 }
429
430 pub fn set_block_random_seed(&mut self, block_random_seed: &[u8; 48]) {
431 self.world
432 .set_state_step(SetStateStep::new().block_random_seed(block_random_seed.as_slice()));
433 }
434
435 pub fn set_block_round(&mut self, block_round: u64) {
436 self.world
437 .set_state_step(SetStateStep::new().block_round(block_round));
438 }
439
440 pub fn set_block_timestamp(&mut self, block_timestamp: u64) {
441 self.world
442 .set_state_step(SetStateStep::new().block_timestamp(block_timestamp));
443 }
444
445 pub fn set_block_timestamp_ms(&mut self, block_timestamp_ms: u64) {
446 self.world
447 .set_state_step(SetStateStep::new().block_timestamp_ms(block_timestamp_ms));
448 }
449
450 pub fn set_prev_block_epoch(&mut self, block_epoch: u64) {
451 self.world
452 .set_state_step(SetStateStep::new().prev_block_epoch(block_epoch));
453 }
454
455 pub fn set_prev_block_nonce(&mut self, block_nonce: u64) {
456 self.world
457 .set_state_step(SetStateStep::new().prev_block_nonce(block_nonce));
458 }
459
460 pub fn set_prev_block_random_seed(&mut self, block_random_seed: &[u8; 48]) {
461 self.world.set_state_step(
462 SetStateStep::new().prev_block_random_seed(block_random_seed.as_slice()),
463 );
464 }
465
466 pub fn set_prev_block_round(&mut self, block_round: u64) {
467 self.world
468 .set_state_step(SetStateStep::new().prev_block_round(block_round));
469 }
470
471 pub fn set_prev_block_timestamp(&mut self, block_timestamp: u64) {
472 self.world
473 .set_state_step(SetStateStep::new().prev_block_timestamp(block_timestamp));
474 }
475
476 pub fn add_mandos_sc_call(
477 &mut self,
478 sc_call: ScCallMandos,
479 opt_expect: Option<TxExpectMandos>,
480 ) {
481 if let Some(trace) = &mut self.world.get_mut_debugger_backend().trace {
482 MandosGenerator::new(&mut trace.scenario_trace, &mut self.current_tx_id)
483 .create_tx(&sc_call, opt_expect.as_ref());
484 }
485 }
486
487 pub fn add_mandos_sc_query(
488 &mut self,
489 sc_query: ScQueryMandos,
490 opt_expect: Option<TxExpectMandos>,
491 ) {
492 if let Some(trace) = &mut self.world.get_mut_debugger_backend().trace {
493 MandosGenerator::new(&mut trace.scenario_trace, &mut self.current_tx_id)
494 .create_query(&sc_query, opt_expect.as_ref());
495 }
496 }
497
498 pub fn add_mandos_set_account(&mut self, address: &Address) {
499 if let Some(acc) = self.world.get_state().accounts.get(address).cloned() {
500 let opt_contract_path = self.address_to_code_path.get(address);
501 if let Some(trace) = &mut self.world.get_mut_debugger_backend().trace {
502 MandosGenerator::new(&mut trace.scenario_trace, &mut self.current_tx_id)
503 .set_account(&acc, opt_contract_path.cloned());
504 }
505 }
506 }
507
508 pub fn add_mandos_check_account(&mut self, address: &Address) {
509 if let Some(acc) = self.world.get_state().accounts.get(address).cloned() {
510 if let Some(trace) = &mut self.world.get_mut_debugger_backend().trace {
511 MandosGenerator::new(&mut trace.scenario_trace, &mut self.current_tx_id)
512 .check_account(&acc);
513 }
514 }
515 }
516}
517
518impl BlockchainStateWrapper {
519 pub fn execute_tx<CB, ContractObjBuilder, TxFn>(
520 &mut self,
521 caller: &Address,
522 sc_wrapper: &ContractObjWrapper<CB, ContractObjBuilder>,
523 egld_payment: &num_bigint::BigUint,
524 tx_fn: TxFn,
525 ) -> TxResult
526 where
527 CB: ContractBase<Api = DebugApi> + CallableContract + 'static,
528 ContractObjBuilder: 'static + Copy + Fn() -> CB,
529 TxFn: FnOnce(CB),
530 {
531 self.execute_tx_any(caller, sc_wrapper, egld_payment, Vec::new(), tx_fn)
532 }
533
534 pub fn execute_esdt_transfer<CB, ContractObjBuilder, TxFn>(
535 &mut self,
536 caller: &Address,
537 sc_wrapper: &ContractObjWrapper<CB, ContractObjBuilder>,
538 token_id: &[u8],
539 esdt_nonce: u64,
540 esdt_amount: &num_bigint::BigUint,
541 tx_fn: TxFn,
542 ) -> TxResult
543 where
544 CB: ContractBase<Api = DebugApi> + CallableContract + 'static,
545 ContractObjBuilder: 'static + Copy + Fn() -> CB,
546 TxFn: FnOnce(CB),
547 {
548 let esdt_transfer = vec![TxTokenTransfer {
549 token_identifier: token_id.to_vec(),
550 nonce: esdt_nonce,
551 value: esdt_amount.clone(),
552 }];
553 self.execute_tx_any(
554 caller,
555 sc_wrapper,
556 &num_bigint::BigUint::zero(),
557 esdt_transfer,
558 tx_fn,
559 )
560 }
561
562 pub fn execute_esdt_multi_transfer<CB, ContractObjBuilder, TxFn>(
563 &mut self,
564 caller: &Address,
565 sc_wrapper: &ContractObjWrapper<CB, ContractObjBuilder>,
566 esdt_transfers: &[TxTokenTransfer],
567 tx_fn: TxFn,
568 ) -> TxResult
569 where
570 CB: ContractBase<Api = DebugApi> + CallableContract + 'static,
571 ContractObjBuilder: 'static + Copy + Fn() -> CB,
572 TxFn: FnOnce(CB),
573 {
574 self.execute_tx_any(
575 caller,
576 sc_wrapper,
577 &num_bigint::BigUint::zero(),
578 esdt_transfers.to_vec(),
579 tx_fn,
580 )
581 }
582
583 pub fn execute_query<CB, ContractObjBuilder, TxFn>(
584 &mut self,
585 sc_wrapper: &ContractObjWrapper<CB, ContractObjBuilder>,
586 query_fn: TxFn,
587 ) -> TxResult
588 where
589 CB: ContractBase<Api = DebugApi> + CallableContract + 'static,
590 ContractObjBuilder: 'static + Copy + Fn() -> CB,
591 TxFn: FnOnce(CB),
592 {
593 self.execute_tx(
594 sc_wrapper.address_ref(),
595 sc_wrapper,
596 &num_bigint::BigUint::zero(),
597 query_fn,
598 )
599 }
600
601 fn execute_tx_any<CB, ContractObjBuilder, TxFn>(
603 &mut self,
604 caller: &Address,
605 sc_wrapper: &ContractObjWrapper<CB, ContractObjBuilder>,
606 egld_payment: &num_bigint::BigUint,
607 esdt_payments: Vec<TxTokenTransfer>,
608 tx_fn: TxFn,
609 ) -> TxResult
610 where
611 CB: ContractBase<Api = DebugApi> + CallableContract + 'static,
612 ContractObjBuilder: 'static + Copy + Fn() -> CB,
613 TxFn: FnOnce(CB),
614 {
615 let mut sc_call_step = ScCallStep::new()
616 .from(caller)
617 .to(sc_wrapper.address_ref())
618 .function(TxFunctionName::WHITEBOX_CALL.as_str())
619 .egld_value(egld_payment)
620 .gas_limit("100,000,000")
621 .no_expect();
622
623 sc_call_step.explicit_tx_hash = Some(H256::zero());
624
625 for esdt_payment in &esdt_payments {
626 sc_call_step = sc_call_step.esdt_transfer(
627 esdt_payment.token_identifier.as_slice(),
628 esdt_payment.nonce,
629 &esdt_payment.value,
630 );
631 }
632
633 let sc = (sc_wrapper.obj_builder)();
634 let tx_result = self
635 .world
636 .get_mut_debugger_backend()
637 .vm_runner
638 .perform_sc_call_lambda_and_check(
639 &sc_call_step,
640 ContractDebugWhiteboxLambda::new(TxFunctionName::WHITEBOX_LEGACY, || {
641 tx_fn(sc);
642 })
643 .panic_message(false),
644 );
645
646 tx_result
647 }
648
649 pub fn execute_in_managed_environment<T, F>(&self, f: F) -> T
653 where
654 F: FnOnce() -> T,
655 {
656 ContractDebugStack::static_push(ContractDebugInstance::dummy());
657 let result = f();
658 let _ = ContractDebugStack::static_pop();
659
660 result
661 }
662}
663
664impl BlockchainStateWrapper {
665 pub fn get_egld_balance(&self, address: &Address) -> num_bigint::BigUint {
666 match self.world.get_state().accounts.get(address) {
667 Some(acc) => acc.egld_balance.clone(),
668 None => panic!(
669 "get_egld_balance: Account {:?} does not exist",
670 address_to_hex(address)
671 ),
672 }
673 }
674
675 pub fn get_esdt_balance(
676 &self,
677 address: &Address,
678 token_id: &[u8],
679 token_nonce: u64,
680 ) -> num_bigint::BigUint {
681 match self.world.get_state().accounts.get(address) {
682 Some(acc) => acc.esdt.get_esdt_balance(token_id, token_nonce),
683 None => panic!(
684 "get_esdt_balance: Account {:?} does not exist",
685 address_to_hex(address)
686 ),
687 }
688 }
689
690 pub fn get_nft_attributes<T: TopDecode>(
691 &self,
692 address: &Address,
693 token_id: &[u8],
694 token_nonce: u64,
695 ) -> Option<T> {
696 match self.world.get_state().accounts.get(address) {
697 Some(acc) => match acc.esdt.get_by_identifier(token_id) {
698 Some(esdt_data) => esdt_data
699 .instances
700 .get_by_nonce(token_nonce)
701 .map(|inst| T::top_decode(inst.metadata.attributes.clone()).unwrap()),
702 None => None,
703 },
704 None => panic!(
705 "get_nft_attributes: Account {:?} does not exist",
706 address_to_hex(address)
707 ),
708 }
709 }
710
711 pub fn dump_state(&self) {
712 for address in self.world.get_state().accounts.keys() {
713 self.dump_state_for_account_hex_attributes(address);
714 println!();
715 }
716 }
717
718 #[inline]
719 pub fn dump_state_for_account_hex_attributes(&self, address: &Address) {
721 self.dump_state_for_account::<Vec<u8>>(address)
722 }
723
724 pub fn dump_state_for_account<AttributesType: 'static + TopDecode + core::fmt::Debug>(
726 &self,
727 address: &Address,
728 ) {
729 let account = match self.world.get_state().accounts.get(address) {
730 Some(acc) => acc,
731 None => panic!(
732 "dump_state_for_account: Account {:?} does not exist",
733 address_to_hex(address)
734 ),
735 };
736
737 println!("State for account: {:?}", address_to_hex(address));
738 println!("EGLD: {}", account.egld_balance);
739
740 if !account.esdt.is_empty() {
741 println!("ESDT Tokens:");
742 }
743 for (token_id, acc_esdt) in account.esdt.iter() {
744 let token_id_str = String::from_utf8(token_id.to_vec()).unwrap();
745 println!(" Token: {token_id_str}");
746
747 for (token_nonce, instance) in acc_esdt.instances.get_instances() {
748 if std::any::TypeId::of::<AttributesType>() == std::any::TypeId::of::<Vec<u8>>() {
749 print_token_balance_raw(
750 *token_nonce,
751 &instance.balance,
752 &instance.metadata.attributes,
753 );
754 } else {
755 match AttributesType::top_decode(&instance.metadata.attributes[..]) {
756 core::result::Result::Ok(attr) => {
757 print_token_balance_specialized(*token_nonce, &instance.balance, &attr)
758 }
759 core::result::Result::Err(_) => print_token_balance_raw(
760 *token_nonce,
761 &instance.balance,
762 &instance.metadata.attributes,
763 ),
764 }
765 }
766 }
767 }
768
769 if !account.storage.is_empty() {
770 println!();
771 println!("Storage: ");
772 }
773 for (key, value) in &account.storage {
774 let key_str = match String::from_utf8(key.to_vec()) {
775 core::result::Result::Ok(s) => s,
776 core::result::Result::Err(_) => bytes_to_hex(key),
777 };
778 let value_str = bytes_to_hex(value);
779
780 println!(" {key_str}: {value_str}");
781 }
782 }
783}
784
785fn address_to_hex(address: &Address) -> String {
786 hex::encode(address.as_bytes())
787}
788
789fn print_token_balance_raw(
790 token_nonce: u64,
791 token_balance: &num_bigint::BigUint,
792 attributes: &[u8],
793) {
794 println!(
795 " Nonce {}, balance: {}, attributes: {}",
796 token_nonce,
797 token_balance,
798 bytes_to_hex(attributes)
799 );
800}
801
802fn print_token_balance_specialized<T: core::fmt::Debug>(
803 token_nonce: u64,
804 token_balance: &num_bigint::BigUint,
805 attributes: &T,
806) {
807 println!(" Nonce {token_nonce}, balance: {token_balance}, attributes: {attributes:?}");
808}
809
810fn create_contract_obj_box<CB, ContractObjBuilder>(
811 func: ContractObjBuilder,
812) -> Box<dyn CallableContract>
813where
814 CB: ContractBase<Api = DebugApi> + CallableContract + 'static,
815 ContractObjBuilder: 'static + Fn() -> CB,
816{
817 let c_base = func();
818 Box::new(c_base)
819}