From 6bdf4a1ca89c783ca33ef3ed7d02c42cac2259c5 Mon Sep 17 00:00:00 2001 From: Dmitry Novikov Date: Mon, 4 Dec 2023 17:05:42 +0100 Subject: [PATCH] Use `cast` everywhere if possible --- common/src/benchmarking.rs | 2 +- common/src/storage/primitives/key.rs | 5 +- lazy-pages/interface/src/lib.rs | 4 +- pallets/gas/src/tests.rs | 2 +- pallets/gear-debug/src/lib.rs | 9 +-- pallets/gear-debug/src/tests/mod.rs | 2 +- pallets/gear-scheduler/src/tests.rs | 6 +- pallets/gear-voucher/src/benchmarking.rs | 6 +- pallets/gear-voucher/src/tests.rs | 4 +- pallets/gear/rpc/src/lib.rs | 13 ++- pallets/gear/src/benchmarking/mod.rs | 24 +++--- pallets/gear/src/benchmarking/syscalls.rs | 8 +- .../gear/src/benchmarking/tests/lazy_pages.rs | 10 +-- .../benchmarking/tests/syscalls_integrity.rs | 12 +-- pallets/gear/src/benchmarking/utils.rs | 20 +++-- pallets/gear/src/internal.rs | 14 ++-- pallets/gear/src/lib.rs | 46 ++++------- pallets/gear/src/manager/journal.rs | 9 +-- pallets/gear/src/manager/mod.rs | 17 ++-- pallets/gear/src/queue.rs | 6 +- pallets/gear/src/runtime_api.rs | 13 ++- pallets/gear/src/tests.rs | 80 ++++++++----------- pallets/payment/src/tests.rs | 21 +++-- 23 files changed, 139 insertions(+), 194 deletions(-) diff --git a/common/src/benchmarking.rs b/common/src/benchmarking.rs index a8042a9456d..9d9cd19902a 100644 --- a/common/src/benchmarking.rs +++ b/common/src/benchmarking.rs @@ -29,7 +29,7 @@ use sp_std::borrow::ToOwned; pub fn account(name: &'static str, index: u32, seed: u32) -> AccountId { let entropy = (name, index, seed).using_encoded(blake2_256); - AccountId::from_origin(H256::from_slice(&entropy[..])) + H256::from_slice(&entropy[..]).cast() } // A wasm module that allocates `$num_pages` of memory in `init` function. diff --git a/common/src/storage/primitives/key.rs b/common/src/storage/primitives/key.rs index e840e13ce78..facc438981b 100644 --- a/common/src/storage/primitives/key.rs +++ b/common/src/storage/primitives/key.rs @@ -54,10 +54,7 @@ impl KeyFor for MailboxKeyGen { type Value = UserStoredMessage; fn key_for(value: &Self::Value) -> Self::Key { - ( - T::from_origin(value.destination().into_origin()), - value.id(), - ) + (value.destination().cast(), value.id()) } } diff --git a/lazy-pages/interface/src/lib.rs b/lazy-pages/interface/src/lib.rs index ef0d7d73f87..d9dc7232280 100644 --- a/lazy-pages/interface/src/lib.rs +++ b/lazy-pages/interface/src/lib.rs @@ -24,7 +24,6 @@ extern crate alloc; use byteorder::{ByteOrder, LittleEndian}; use core::fmt; -use gear_common::Origin; use gear_core::{ ids::ProgramId, memory::{HostPointer, Memory, MemoryInterval}, @@ -75,10 +74,9 @@ pub fn init_for_program( wasm_mem_size: mem.size().raw(), stack_end: stack_end.map(|p| p.raw()), program_key: { - let program_id = <[u8; 32]>::from(program_id.into_origin()); let memory_infix = memory_infix.inner().to_le_bytes(); - [&program_id[..], &memory_infix[..]].concat() + [program_id.as_ref(), memory_infix.as_ref()].concat() }, globals_config, weights, diff --git a/pallets/gas/src/tests.rs b/pallets/gas/src/tests.rs index e9edc9cdbc7..96aa29c6895 100644 --- a/pallets/gas/src/tests.rs +++ b/pallets/gas/src/tests.rs @@ -31,7 +31,7 @@ type Gas = as common::GasProvider>::GasTree; type GasTree = GasNodes; fn random_node_id() -> MessageId { - MessageId::from_origin(H256::random()) + H256::random().cast() } const MULTIPLIER: GasMultiplier = GasMultiplier::ValuePerGas(25); diff --git a/pallets/gear-debug/src/lib.rs b/pallets/gear-debug/src/lib.rs index 7e699474be1..adb4a05837d 100644 --- a/pallets/gear-debug/src/lib.rs +++ b/pallets/gear-debug/src/lib.rs @@ -37,7 +37,7 @@ pub mod pallet { use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*}; use frame_system::pallet_prelude::*; use gear_core::{ - ids::{CodeId, ProgramId}, + ids::ProgramId, memory::PageBuf, message::{StoredDispatch, StoredMessage}, pages::{GearPage, PageU32Size, WasmPage}, @@ -184,8 +184,8 @@ pub mod pallet { let message = StoredMessage::new( msg.id(), - ProgramId::from_origin(source), - ProgramId::from_origin(destination), + source.cast(), + destination.cast(), (*msg.payload_bytes()).to_vec().try_into().unwrap(), msg.value(), msg.details(), @@ -211,8 +211,7 @@ pub mod pallet { } } }; - let code_id = CodeId::from_origin(active.code_hash); - let static_pages = match T::CodeStorage::get_code(code_id) { + let static_pages = match T::CodeStorage::get_code(active.code_hash.cast()) { Some(code) => code.static_pages(), None => WasmPage::zero(), }; diff --git a/pallets/gear-debug/src/tests/mod.rs b/pallets/gear-debug/src/tests/mod.rs index 9017791a2e0..5362f09a1bf 100644 --- a/pallets/gear-debug/src/tests/mod.rs +++ b/pallets/gear-debug/src/tests/mod.rs @@ -952,7 +952,7 @@ fn disabled_program_rent() { let block_count = 2_000u32; let rent = RentCostPerBlockOf::::get() * u128::from(block_count); - let pay_rent_account_id = AccountId::from_origin(pay_rent_id.into_origin()); + let pay_rent_account_id = pay_rent_id.cast::(); let balance_before = Balances::free_balance(pay_rent_account_id); assert_ok!(Gear::send_message( RuntimeOrigin::signed(1), diff --git a/pallets/gear-scheduler/src/tests.rs b/pallets/gear-scheduler/src/tests.rs index 14f9143f61f..6b025001248 100644 --- a/pallets/gear-scheduler/src/tests.rs +++ b/pallets/gear-scheduler/src/tests.rs @@ -51,9 +51,9 @@ fn dispatch_from(src: impl Into) -> StoredDispatch { StoredDispatch::new( DispatchKind::Handle, StoredMessage::new( - MessageId::from_origin(H256::random().into_origin()), + H256::random().cast(), src.into(), - ProgramId::from_origin(H256::random().into_origin()), + H256::random().cast(), Default::default(), 0, None, @@ -111,7 +111,7 @@ fn out_of_rent_reply_exists( mid: impl Into, pid: impl Into, ) -> bool { - let src = ProgramId::from_origin(user_id.into_origin()); + let src = user_id.cast(); let mid = mid.into(); let pid = pid.into(); diff --git a/pallets/gear-voucher/src/benchmarking.rs b/pallets/gear-voucher/src/benchmarking.rs index 38aac81bf34..29f1caadfd9 100644 --- a/pallets/gear-voucher/src/benchmarking.rs +++ b/pallets/gear-voucher/src/benchmarking.rs @@ -41,9 +41,9 @@ benchmarks! { 100_000_000_000_000_u128.unique_saturated_into() ); let holder = benchmarking::account::("caller", 0, 1); - let program_id = ProgramId::from_origin( - benchmarking::account::("program", 0, 100).into_origin() - ); + let program_id = + benchmarking::account::("program", 0, 100).cast() + ; let holder_lookup = T::Lookup::unlookup(holder.clone()); }: _(RawOrigin::Signed(issuer), holder_lookup, program_id, 10_000_000_000_000_u128.unique_saturated_into()) diff --git a/pallets/gear-voucher/src/tests.rs b/pallets/gear-voucher/src/tests.rs index a46cfe97ac4..b3d47736fb2 100644 --- a/pallets/gear-voucher/src/tests.rs +++ b/pallets/gear-voucher/src/tests.rs @@ -25,7 +25,7 @@ use primitive_types::H256; #[test] fn voucher_issue_works() { new_test_ext().execute_with(|| { - let program_id = ProgramId::from_origin(H256::from(b"some//quasy//random//program//id")); + let program_id = H256::from(b"some//quasy//random//program//id").cast(); let synthesized = Voucher::voucher_account_id(&BOB, &program_id); assert_ok!(Voucher::issue( @@ -55,7 +55,7 @@ fn voucher_issue_works() { #[test] fn voucher_redemption_works() { new_test_ext().execute_with(|| { - let program_id = ProgramId::from_origin(H256::from(b"some//quasy//random//program//id")); + let program_id = H256::from(b"some//quasy//random//program//id").cast(); let synthesized = Voucher::voucher_account_id(&BOB, &program_id); assert_ok!(Voucher::issue( diff --git a/pallets/gear/rpc/src/lib.rs b/pallets/gear/rpc/src/lib.rs index 3f7b72c4bdb..7e85786071f 100644 --- a/pallets/gear/rpc/src/lib.rs +++ b/pallets/gear/rpc/src/lib.rs @@ -24,7 +24,6 @@ #![doc(html_favicon_url = "https://gear-tech.io/favicons/favicon.ico")] use gear_common::Origin; -use gear_core::ids::{CodeId, MessageId, ProgramId}; use gear_core_errors::*; use jsonrpsee::{ core::{async_trait, Error as JsonRpseeError, RpcResult}, @@ -272,7 +271,7 @@ where let GasInfo { min_limit, .. } = self.calculate_gas_info( at_hash, source, - HandleKind::InitByHash(CodeId::from_origin(code_id)), + HandleKind::InitByHash(code_id.cast()), payload.to_vec(), value, allow_other_panics, @@ -282,7 +281,7 @@ where self.calculate_gas_info( at_hash, source, - HandleKind::InitByHash(CodeId::from_origin(code_id)), + HandleKind::InitByHash(code_id.cast()), payload.to_vec(), value, allow_other_panics, @@ -336,7 +335,7 @@ where let GasInfo { min_limit, .. } = self.calculate_gas_info( at_hash, source, - HandleKind::Handle(ProgramId::from_origin(dest)), + HandleKind::Handle(dest.cast()), payload.to_vec(), value, allow_other_panics, @@ -346,7 +345,7 @@ where self.calculate_gas_info( at_hash, source, - HandleKind::Handle(ProgramId::from_origin(dest)), + HandleKind::Handle(dest.cast()), payload.to_vec(), value, allow_other_panics, @@ -369,7 +368,7 @@ where at_hash, source, HandleKind::Reply( - MessageId::from_origin(message_id), + message_id.cast(), ReplyCode::Success(SuccessReplyReason::Manual), ), payload.to_vec(), @@ -382,7 +381,7 @@ where at_hash, source, HandleKind::Reply( - MessageId::from_origin(message_id), + message_id.cast(), ReplyCode::Success(SuccessReplyReason::Manual), ), payload.to_vec(), diff --git a/pallets/gear/src/benchmarking/mod.rs b/pallets/gear/src/benchmarking/mod.rs index b911e5bcc97..dc640bb61c4 100644 --- a/pallets/gear/src/benchmarking/mod.rs +++ b/pallets/gear/src/benchmarking/mod.rs @@ -283,7 +283,7 @@ where RawOrigin::Signed(caller).into(), program_id, program.allocations, - CodeId::from_origin(program.code_hash), + program.code_hash.cast(), ) .expect("failed to start resume session"); @@ -469,8 +469,8 @@ benchmarks! { let program_id = benchmarking::account::("program", 0, 100); CurrencyOf::::deposit_creating(&program_id, 100_000_000_000_000_u128.unique_saturated_into()); let code = benchmarking::generate_wasm2(16.into()).unwrap(); - benchmarking::set_program::, _>(ProgramId::from_origin(program_id.clone().into_origin()), code, 1.into()); - let original_message_id = MessageId::from_origin(benchmarking::account::("message", 0, 100).into_origin()); + benchmarking::set_program::, _>(program_id.clone().cast(), code, 1.into()); + let original_message_id = benchmarking::account::("message", 0, 100).cast(); let gas_limit = 50000; let value = 10000u32.into(); let multiplier = ::GasMultiplier::get(); @@ -479,8 +479,8 @@ benchmarks! { GearBank::::deposit_value(&program_id, value, true).unwrap_or_else(|e| unreachable!("Gear bank error: {e:?}")); MailboxOf::::insert(gear_core::message::StoredMessage::new( original_message_id, - ProgramId::from_origin(program_id.into_origin()), - ProgramId::from_origin(caller.clone().into_origin()), + program_id.cast(), + caller.clone().cast(), Default::default(), value.unique_saturated_into(), None, @@ -531,7 +531,7 @@ benchmarks! { .try_into() .expect("program should be active"); ProgramStorageOf::::pause_program(program_id, 100u32.into()).unwrap(); - }: _(RawOrigin::Signed(caller.clone()), program_id, program.allocations, CodeId::from_origin(program.code_hash)) + }: _(RawOrigin::Signed(caller.clone()), program_id, program.allocations, program.code_hash.cast()) verify { assert!(ProgramStorageOf::::paused_program_exists(&program_id)); assert!( @@ -695,7 +695,7 @@ benchmarks! { let caller = benchmarking::account("caller", 0, 0); CurrencyOf::::deposit_creating(&caller, 100_000_000_000_000_u128.unique_saturated_into()); let minimum_balance = CurrencyOf::::minimum_balance(); - let program_id = ProgramId::from_origin(benchmarking::account::("program", 0, 100).into_origin()); + let program_id = benchmarking::account::("program", 0, 100).cast(); let code = benchmarking::generate_wasm2(16.into()).unwrap(); benchmarking::set_program::, _>(program_id, code, 1.into()); let payload = vec![0_u8; p as usize]; @@ -714,8 +714,8 @@ benchmarks! { let program_id = benchmarking::account::("program", 0, 100); CurrencyOf::::deposit_creating(&program_id, 100_000_000_000_000_u128.unique_saturated_into()); let code = benchmarking::generate_wasm2(16.into()).unwrap(); - benchmarking::set_program::, _>(ProgramId::from_origin(program_id.clone().into_origin()), code, 1.into()); - let original_message_id = MessageId::from_origin(benchmarking::account::("message", 0, 100).into_origin()); + benchmarking::set_program::, _>(program_id.clone().cast(), code, 1.into()); + let original_message_id = benchmarking::account::("message", 0, 100).cast(); let gas_limit = 50000; let value = (p % 2).into(); let multiplier = ::GasMultiplier::get(); @@ -724,8 +724,8 @@ benchmarks! { GearBank::::deposit_value(&program_id, value, true).unwrap_or_else(|e| unreachable!("Gear bank error: {e:?}")); MailboxOf::::insert(gear_core::message::StoredMessage::new( original_message_id, - ProgramId::from_origin(program_id.into_origin()), - ProgramId::from_origin(caller.clone().into_origin()), + program_id.cast(), + caller.clone().cast(), Default::default(), value.unique_saturated_into(), None, @@ -2851,7 +2851,7 @@ benchmarks! { let (user, message_id) = tasks::remove_from_mailbox::(); let mut ext_manager = ExtManager::::default(); }: { - ext_manager.remove_from_mailbox(T::AccountId::from_origin(user.into_origin()), message_id); + ext_manager.remove_from_mailbox(user.cast(), message_id); } tasks_pause_program { diff --git a/pallets/gear/src/benchmarking/syscalls.rs b/pallets/gear/src/benchmarking/syscalls.rs index 411b1a55476..1128b56eca5 100644 --- a/pallets/gear/src/benchmarking/syscalls.rs +++ b/pallets/gear/src/benchmarking/syscalls.rs @@ -107,7 +107,7 @@ where let instance = Program::::new(module.into(), vec![])?; utils::prepare_exec::( instance.caller.into_origin(), - HandleKind::Handle(ProgramId::from_origin(instance.addr)), + HandleKind::Handle(instance.addr.cast()), vec![], PrepareConfig { value: value.into(), @@ -159,7 +159,7 @@ where let instance = Program::::new(module.into(), vec![])?; utils::prepare_exec::( instance.caller.into_origin(), - HandleKind::Handle(ProgramId::from_origin(instance.addr)), + HandleKind::Handle(instance.addr.cast()), vec![], PrepareConfig { value: value.into(), @@ -176,7 +176,7 @@ where let instance = Program::::new(module.into(), vec![])?; // insert gas reservation slots - let program_id = ProgramId::from_origin(instance.addr); + let program_id = instance.addr.cast(); ProgramStorageOf::::update_active_program(program_id, |program| { for x in 0..repetitions { program.gas_reservation_map.insert( @@ -205,7 +205,7 @@ where let instance = Program::::new(module.into(), vec![])?; utils::prepare_exec::( instance.caller.into_origin(), - HandleKind::Handle(ProgramId::from_origin(instance.addr)), + HandleKind::Handle(instance.addr.cast()), vec![0xff; MAX_PAYLOAD_LEN as usize], Default::default(), ) diff --git a/pallets/gear/src/benchmarking/tests/lazy_pages.rs b/pallets/gear/src/benchmarking/tests/lazy_pages.rs index be56fe5ad50..b324e6628ef 100644 --- a/pallets/gear/src/benchmarking/tests/lazy_pages.rs +++ b/pallets/gear/src/benchmarking/tests/lazy_pages.rs @@ -270,7 +270,7 @@ where }; let instance = Program::::new(module.into(), vec![]).unwrap(); let source = instance.caller.into_origin(); - let program_id = ProgramId::from_origin(instance.addr); + let program_id = instance.addr.cast(); // Append data in storage for some pages. for page in (0..rng.gen_range(0..MAX_PAGES_WITH_DATA)) @@ -369,7 +369,7 @@ where let instance = instance.clone(); let mut exec = common_utils::prepare_exec::( instance.caller.into_origin(), - HandleKind::Handle(ProgramId::from_origin(instance.addr)), + HandleKind::Handle(instance.addr.cast()), vec![], Default::default(), ) @@ -529,7 +529,7 @@ where let gas_burned = { let mut exec = common_utils::prepare_exec::( source, - HandleKind::Handle(ProgramId::from_origin(origin)), + HandleKind::Handle(origin.cast()), vec![], Default::default(), ) @@ -563,7 +563,7 @@ where { let mut exec = common_utils::prepare_exec::( source, - HandleKind::Handle(ProgramId::from_origin(origin)), + HandleKind::Handle(origin.cast()), vec![], PrepareConfig { gas_limit: gas_burned, @@ -601,7 +601,7 @@ where { let mut exec = common_utils::prepare_exec::( source, - HandleKind::Handle(ProgramId::from_origin(origin)), + HandleKind::Handle(origin.cast()), vec![], PrepareConfig { gas_allowance: gas_burned, diff --git a/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs b/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs index f5a8bca4b8e..379734d72c1 100644 --- a/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs +++ b/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs @@ -364,7 +364,7 @@ where let expected_mid = MessageId::generate_reply(next_user_mid); let post_test = move || { - let source = ProgramId::from_origin(default_sender.into_origin()); + let source = default_sender.cast(); assert!(SystemPallet::::events().into_iter().any(|e| { let bytes = e.event.encode(); let Ok(gear_event): Result, _> = Event::decode(&mut bytes[1..].as_ref()) else { return false }; @@ -694,7 +694,7 @@ where let expected_mid = MessageId::generate_reply(next_user_mid); let post_test = move || { - let source = ProgramId::from_origin(default_sender.into_origin()); + let source = default_sender.cast(); assert!(SystemPallet::::events().into_iter().any(|e| { let bytes = e.event.encode(); let Ok(gear_event): Result, _> = Event::decode(&mut bytes[1..].as_ref()) else { return false }; @@ -725,7 +725,7 @@ where let message = payload.clone().into(); let post_test = move || { - let source = ProgramId::from_origin(default_sender.into_origin()); + let source = default_sender.cast(); assert!(SystemPallet::::events().into_iter().any(|e| { let bytes = e.event.encode(); let Ok(gear_event): Result, _> = Event::decode(&mut bytes[1..].as_ref()) else { return false }; @@ -752,7 +752,7 @@ where let message = payload.clone().into(); let post_test = move || { - let source = ProgramId::from_origin(default_sender.into_origin()); + let source = default_sender.cast(); assert!(SystemPallet::::events().into_iter().any(|e| { let bytes = e.event.encode(); let Ok(gear_event): Result, _> = Event::decode(&mut bytes[1..].as_ref()) else { return false }; @@ -1090,8 +1090,8 @@ where // Manually reset the storage Gear::::reset(); CurrencyOf::::slash( - &Id::from_origin(tester_pid.into_origin()), - CurrencyOf::::free_balance(&Id::from_origin(tester_pid.into_origin())), + &tester_pid.cast(), + CurrencyOf::::free_balance(&tester_pid.cast()), ); } diff --git a/pallets/gear/src/benchmarking/utils.rs b/pallets/gear/src/benchmarking/utils.rs index 7bf78a1fa5c..e17a4e5c9f1 100644 --- a/pallets/gear/src/benchmarking/utils.rs +++ b/pallets/gear/src/benchmarking/utils.rs @@ -157,7 +157,7 @@ where DispatchKind::Init, Message::new( root_message_id, - ProgramId::from_origin(source), + source.cast(), program_id, payload.try_into()?, Some(u64::MAX), @@ -183,7 +183,7 @@ where DispatchKind::Init, Message::new( root_message_id, - ProgramId::from_origin(source), + source.cast(), program_id, payload.try_into()?, Some(u64::MAX), @@ -196,7 +196,7 @@ where DispatchKind::Handle, Message::new( root_message_id, - ProgramId::from_origin(source), + source.cast(), dest, payload.try_into()?, Some(u64::MAX), @@ -205,14 +205,13 @@ where ), ), HandleKind::Reply(msg_id, exit_code) => { - let (msg, _bn) = - MailboxOf::::remove(::from_origin(source), msg_id) - .map_err(|_| "Internal error: unable to find message in mailbox")?; + let (msg, _bn) = MailboxOf::::remove(source.cast(), msg_id) + .map_err(|_| "Internal error: unable to find message in mailbox")?; Dispatch::new( DispatchKind::Reply, Message::new( root_message_id, - ProgramId::from_origin(source), + source.cast(), msg.source(), payload.try_into()?, Some(u64::MAX), @@ -222,14 +221,13 @@ where ) } HandleKind::Signal(msg_id, status_code) => { - let (msg, _bn) = - MailboxOf::::remove(::from_origin(source), msg_id) - .map_err(|_| "Internal error: unable to find message in mailbox")?; + let (msg, _bn) = MailboxOf::::remove(source.cast(), msg_id) + .map_err(|_| "Internal error: unable to find message in mailbox")?; Dispatch::new( DispatchKind::Signal, Message::new( root_message_id, - ProgramId::from_origin(source), + source.cast(), msg.source(), payload.try_into()?, Some(u64::MAX), diff --git a/pallets/gear/src/internal.rs b/pallets/gear/src/internal.rs index 7a25243946f..af4cc41d665 100644 --- a/pallets/gear/src/internal.rs +++ b/pallets/gear/src/internal.rs @@ -466,8 +466,8 @@ where Self::consume_and_retrieve(mailboxed.id()); // Taking data for funds transfer. - let user_id = ::from_origin(mailboxed.destination().into_origin()); - let from = ::from_origin(mailboxed.source().into_origin()); + let user_id = mailboxed.destination().cast(); + let from = mailboxed.source().cast(); // Transferring reserved funds, associated with the message. GearBank::::transfer_value(&from, &user_id, mailboxed.value().unique_saturated_into()) @@ -528,7 +528,7 @@ where .unwrap_or_else(|| origin_msg.into()); // Taking data for funds manipulations. - let from = ::from_origin(dispatch.source().into_origin()); + let from = dispatch.source().cast(); let value = dispatch.value().unique_saturated_into(); // `HoldBound` builder. @@ -731,8 +731,8 @@ where .unwrap_or_else(|_| unreachable!("Signal message sent to user")); // Taking data for funds manipulations. - let from = ::from_origin(message.source().into_origin()); - let to = ::from_origin(message.destination().into_origin()); + let from = message.source().cast(); + let to = message.destination().cast(); let value = message.value().unique_saturated_into(); // If gas limit can cover threshold, message will be added to mailbox, @@ -842,8 +842,8 @@ where }; // Taking data for funds manipulations. - let from = ::from_origin(message.source().into_origin()); - let to = ::from_origin(message.destination().into_origin()); + let from = message.source().cast(); + let to = message.destination().cast(); let value = message.value().unique_saturated_into(); // If gas limit can cover threshold, message will be added to mailbox, diff --git a/pallets/gear/src/lib.rs b/pallets/gear/src/lib.rs index 28ede177994..e343210ebca 100644 --- a/pallets/gear/src/lib.rs +++ b/pallets/gear/src/lib.rs @@ -632,9 +632,7 @@ pub mod pallet { ); let message = InitMessage::from_packet(message_id, packet); - let dispatch = message - .into_dispatch(ProgramId::from_origin(origin)) - .into_stored(); + let dispatch = message.into_dispatch(origin.cast()).into_stored(); QueueOf::::queue(dispatch) .unwrap_or_else(|e| unreachable!("Messages storage corrupted: {e:?}")); @@ -681,13 +679,11 @@ pub mod pallet { argument: Option>, gas_allowance: Option, ) -> Result, Vec> { - let program_id = ProgramId::from_origin(program_id.into_origin()); - let fn_name = String::from_utf8(fn_name) .map_err(|_| "Non-utf8 function name".as_bytes().to_vec())?; Self::read_state_using_wasm_impl( - program_id, + program_id.cast(), payload, fn_name, wasm, @@ -702,18 +698,15 @@ pub mod pallet { payload: Vec, gas_allowance: Option, ) -> Result, Vec> { - let program_id = ProgramId::from_origin(program_id.into_origin()); - - Self::read_state_impl(program_id, payload, gas_allowance).map_err(String::into_bytes) + Self::read_state_impl(program_id.cast(), payload, gas_allowance) + .map_err(String::into_bytes) } pub fn read_metahash( program_id: H256, gas_allowance: Option, ) -> Result> { - let program_id = ProgramId::from_origin(program_id.into_origin()); - - Self::read_metahash_impl(program_id, gas_allowance).map_err(String::into_bytes) + Self::read_metahash_impl(program_id.cast(), gas_allowance).map_err(String::into_bytes) } #[cfg(not(test))] @@ -895,9 +888,8 @@ pub mod pallet { let nonce = SentOf::::get(); SentOf::::increase(); let block_number = >::block_number().unique_saturated_into(); - let user_id = ProgramId::from_origin(user_id); - MessageId::generate_from_user(block_number, user_id, nonce.into()) + MessageId::generate_from_user(block_number, user_id.cast(), nonce.into()) } /// Delayed tasks processing. @@ -1240,9 +1232,7 @@ pub mod pallet { ); let message = InitMessage::from_packet(message_id, packet); - let dispatch = message - .into_dispatch(ProgramId::from_origin(origin)) - .into_stored(); + let dispatch = message.into_dispatch(origin.cast()).into_stored(); let event = Event::MessageQueued { id: dispatch.id(), @@ -1563,11 +1553,8 @@ pub mod pallet { Self::create(origin.clone(), message.id(), 0, true); // Converting reply message into appropriate type for queueing. - let dispatch = message.into_stored_dispatch( - ProgramId::from_origin(origin.into_origin()), - mailboxed.source(), - mailboxed.id(), - ); + let dispatch = + message.into_stored_dispatch(origin.cast(), mailboxed.source(), mailboxed.id()); // Queueing dispatch. QueueOf::::queue(dispatch) @@ -1881,7 +1868,7 @@ pub mod pallet { Self::create(external_node, message.id(), gas_limit, false); - let message = message.into_stored_dispatch(ProgramId::from_origin(origin)); + let message = message.into_stored_dispatch(origin.cast()); Self::deposit_event(Event::MessageQueued { id: message.id(), @@ -1893,7 +1880,7 @@ pub mod pallet { QueueOf::::queue(message) .unwrap_or_else(|e| unreachable!("Messages storage corrupted: {e:?}")); } else { - let message = message.into_stored(ProgramId::from_origin(origin)); + let message = message.into_stored(origin.cast()); let message: UserMessage = message .try_into() .unwrap_or_else(|_| unreachable!("Signal message sent to user")); @@ -1906,9 +1893,7 @@ pub mod pallet { CurrencyOf::::transfer( &who, - &::AccountId::from_origin( - message.destination().into_origin(), - ), + &message.destination().cast(), value.unique_saturated_into(), existence_requirement, )?; @@ -1991,11 +1976,8 @@ pub mod pallet { ); // Converting reply message into appropriate type for queueing. - let dispatch = message.into_stored_dispatch( - ProgramId::from_origin(origin.clone().into_origin()), - destination, - mailboxed.id(), - ); + let dispatch = + message.into_stored_dispatch(origin.clone().cast(), destination, mailboxed.id()); // Pre-generating appropriate event to avoid dispatch cloning. let event = Event::MessageQueued { diff --git a/pallets/gear/src/manager/journal.rs b/pallets/gear/src/manager/journal.rs index 79a60a0f110..6bbd2c5f566 100644 --- a/pallets/gear/src/manager/journal.rs +++ b/pallets/gear/src/manager/journal.rs @@ -230,7 +230,7 @@ where if dispatch.value() != 0 { GearBank::::deposit_value( - &::from_origin(dispatch.source().into_origin()), + &dispatch.source().cast(), dispatch.value().unique_saturated_into(), false, ) @@ -375,9 +375,8 @@ where } fn send_value(&mut self, from: ProgramId, to: Option, value: u128) { - let to = Pallet::::inheritor_for(to.unwrap_or(from)); - let to = ::from_origin(to.into_origin()); - let from = ::from_origin(from.into_origin()); + let to = Pallet::::inheritor_for(to.unwrap_or(from)).cast(); + let from = from.cast(); let value = value.unique_saturated_into(); GearBank::::transfer_value(&from, &to, value) @@ -539,7 +538,7 @@ where } fn pay_program_rent(&mut self, payer: ProgramId, program_id: ProgramId, block_count: u32) { - let from = ::from_origin(payer.into_origin()); + let from = payer.cast(); let block_count = block_count.unique_saturated_into(); ProgramStorageOf::::update_active_program(program_id, |program| { diff --git a/pallets/gear/src/manager/mod.rs b/pallets/gear/src/manager/mod.rs index 4973d70a7f6..b18ce498ce3 100644 --- a/pallets/gear/src/manager/mod.rs +++ b/pallets/gear/src/manager/mod.rs @@ -223,11 +223,9 @@ where /// program with `id` doesn't exist or it's terminated pub fn get_actor(&self, id: ProgramId) -> Option { let active: ActiveProgram<_> = ProgramStorageOf::::get_program(id)?.try_into().ok()?; - let code_id = CodeId::from_origin(active.code_hash); + let code_id = active.code_hash.cast(); - let balance = - CurrencyOf::::free_balance(&::from_origin(id.into_origin())) - .unique_saturated_into(); + let balance = CurrencyOf::::free_balance(&id.cast()).unique_saturated_into(); Some(Actor { balance, @@ -257,7 +255,7 @@ where // // Code can exist without program, but the latter can't exist without code. debug_assert!( - T::CodeStorage::exists(CodeId::from_origin(code_info.id)), + T::CodeStorage::exists(code_info.id.cast()), "Program set must be called only when code exists", ); @@ -377,14 +375,13 @@ where ) { ProgramStorageOf::::remove_program_pages(program_id, memory_infix); - let program_account = &::from_origin(program_id.into_origin()); - let balance = CurrencyOf::::free_balance(program_account); + let program_account = program_id.cast(); + let balance = CurrencyOf::::free_balance(&program_account); if !balance.is_zero() { - let destination = Pallet::::inheritor_for(value_destination); - let destination = ::from_origin(destination.into_origin()); + let destination = Pallet::::inheritor_for(value_destination).cast(); CurrencyOf::::transfer( - program_account, + &program_account, &destination, balance, ExistenceRequirement::AllowDeath, diff --git a/pallets/gear/src/queue.rs b/pallets/gear/src/queue.rs index 5cb06f554c7..9f23ea851ad 100644 --- a/pallets/gear/src/queue.rs +++ b/pallets/gear/src/queue.rs @@ -202,9 +202,7 @@ where let dispatch_id = dispatch.id(); let dispatch_reply = dispatch.reply_details().is_some(); - let balance = CurrencyOf::::free_balance(&::from_origin( - program_id.into_origin(), - )); + let balance = CurrencyOf::::free_balance(&program_id.cast()); let get_actor_data = |precharged_dispatch: PrechargedDispatch| { // At this point gas counters should be changed accordingly so fetch the program data. @@ -296,7 +294,7 @@ where ActorResult::Data(Some(ExecutableActorData { allocations: program.allocations, - code_id: CodeId::from_origin(program.code_hash), + code_id: program.code_hash.cast(), code_exports: program.code_exports, static_pages: program.static_pages, initialized: matches!(program.state, ProgramState::Initialized), diff --git a/pallets/gear/src/runtime_api.rs b/pallets/gear/src/runtime_api.rs index 8885c6d44ff..e92627c7845 100644 --- a/pallets/gear/src/runtime_api.rs +++ b/pallets/gear/src/runtime_api.rs @@ -56,7 +56,7 @@ where ) -> Result> { Self::enable_lazy_pages(); - let account = ::from_origin(source); + let account = source.cast(); let balance = CurrencyOf::::free_balance(&account); let max_balance: BalanceOf = ::GasMultiplier::get() @@ -150,9 +150,7 @@ where let dispatch_id = queued_dispatch.id(); let dispatch_reply = queued_dispatch.reply_details().is_some(); - let balance = CurrencyOf::::free_balance(&::from_origin( - actor_id.into_origin(), - )); + let balance = CurrencyOf::::free_balance(&actor_id.cast()); let get_actor_data = |precharged_dispatch: PrechargedDispatch| { // At this point gas counters should be changed accordingly so fetch the program data. @@ -219,8 +217,8 @@ where match note { JournalNote::SendDispatch { dispatch, .. } => { - let destination = - T::AccountId::from_origin(dispatch.destination().into_origin()); + let destination = dispatch.destination().cast(); + if MailboxOf::::contains(&destination, &dispatch.id()) && from_main_chain(dispatch.id())? { @@ -275,8 +273,7 @@ where let program = ActiveProgram::try_from(program) .map_err(|e| format!("Get active program error: {e:?}"))?; - let code_id = CodeId::from_origin(program.code_hash); - let instrumented_code = T::CodeStorage::get_code(code_id) + let instrumented_code = T::CodeStorage::get_code(program.code_hash.cast()) .ok_or_else(|| String::from("Failed to get code for given program id"))?; Ok(CodeWithMemoryData { diff --git a/pallets/gear/src/tests.rs b/pallets/gear/src/tests.rs index 63cfa56dfc9..1aac7754b9d 100644 --- a/pallets/gear/src/tests.rs +++ b/pallets/gear/src/tests.rs @@ -2623,11 +2623,8 @@ fn mailbox_rent_out_of_rent() { let user_2_balance = Balances::free_balance(USER_2); assert_eq!(GearBank::::account_total(&USER_2), 0); - let prog_balance = Balances::free_balance(AccountId::from_origin(sender.into_origin())); - assert_eq!( - GearBank::::account_total(&AccountId::from_origin(sender.into_origin())), - 0 - ); + let prog_balance = Balances::free_balance(sender.cast::()); + assert_eq!(GearBank::::account_total(&sender.cast()), 0); let (_, gas_info) = utils::calculate_handle_and_send_with_extra( USER_1, @@ -2717,16 +2714,12 @@ fn mailbox_rent_claimed() { let user_2_balance = Balances::free_balance(USER_2); assert_eq!(GearBank::::account_total(&USER_2), 0); - - let prog_balance = Balances::free_balance(AccountId::from_origin(sender.into_origin())); - assert_eq!( - GearBank::::account_total(&AccountId::from_origin(sender.into_origin())), - 0 - ); + let prog_balance = Balances::free_balance(sender.cast::()); + assert_eq!(GearBank::::account_total(&sender.cast()), 0); let (_, gas_info) = utils::calculate_handle_and_send_with_extra( USER_1, - sender, + sender.cast(), data.request(USER_2.into_origin()).encode(), Some(data.extra_gas), 0, @@ -2807,11 +2800,8 @@ fn mailbox_sending_instant_transfer() { let user_2_balance = Balances::free_balance(USER_2); assert_eq!(GearBank::::account_total(&USER_2), 0); - let prog_balance = Balances::free_balance(AccountId::from_origin(sender.into_origin())); - assert_eq!( - GearBank::::account_total(&AccountId::from_origin(sender.into_origin())), - 0 - ); + let prog_balance = Balances::free_balance(sender.cast::()); + assert_eq!(GearBank::::account_total(&sender.cast()), 0); let payload = if let Some(gas_limit) = gas_limit { TestData::gasful(gas_limit, value) @@ -3006,7 +2996,7 @@ fn mailbox_threshold_works() { let check_result = |sufficient: bool| -> MessageId { run_to_next_block(None); - let mailbox_key = AccountId::from_origin(USER_1.into_origin()); + let mailbox_key = USER_1.cast(); let message_id = get_last_message_id(); if sufficient { @@ -4371,7 +4361,7 @@ fn send_reply_works() { // Top up program's account balance by 2000 to allow user claim 1000 from mailbox assert_ok!(>::transfer( &USER_1, - &AccountId::from_origin(prog_id.into_origin()), + &prog_id.cast(), 2000, frame_support::traits::ExistenceRequirement::AllowDeath )); @@ -4414,7 +4404,7 @@ fn send_reply_failure_to_claim_from_mailbox() { assert_noop!( Gear::send_reply( RuntimeOrigin::signed(USER_1), - MessageId::from_origin(5.into_origin()), // non existent `reply_to_id` + 5.cast(), // non existent `reply_to_id` EMPTY_PAYLOAD.to_vec(), DEFAULT_GAS_LIMIT, 0, @@ -4462,7 +4452,7 @@ fn send_reply_value_claiming_works() { let send_to_program_amount = locked_value * 2; assert_ok!(>::transfer( &USER_1, - &AccountId::from_origin(prog_id.into_origin()), + &prog_id.cast(), send_to_program_amount, frame_support::traits::ExistenceRequirement::AllowDeath )); @@ -4747,8 +4737,7 @@ fn test_code_submission_pass() { init_logger(); new_test_ext().execute_with(|| { let code = ProgramCodeKind::Default.to_bytes(); - let code_hash = generate_code_hash(&code).into(); - let code_id = CodeId::from_origin(code_hash); + let code_id = CodeId::generate(&code); assert_ok!(Gear::upload_code( RuntimeOrigin::signed(USER_1), @@ -4812,7 +4801,7 @@ fn test_code_is_not_submitted_twice_after_program_submission() { init_logger(); new_test_ext().execute_with(|| { let code = ProgramCodeKind::Default.to_bytes(); - let code_id = generate_code_hash(&code).into(); + let code_id = CodeId::generate(&code); // First submit program, which will set code and metadata assert_ok!(Gear::upload_program( @@ -4850,8 +4839,7 @@ fn test_code_is_not_reset_within_program_submission() { init_logger(); new_test_ext().execute_with(|| { let code = ProgramCodeKind::Default.to_bytes(); - let code_hash = generate_code_hash(&code).into(); - let code_id = CodeId::from_origin(code_hash); + let code_id = CodeId::generate(&code); // First submit code assert_ok!(Gear::upload_code( @@ -6961,7 +6949,7 @@ fn resume_program_works() { RuntimeOrigin::signed(USER_1), program_id, program.allocations.clone(), - CodeId::from_origin(program.code_hash), + program.code_hash.cast(), )); assert_ne!( old_nonce, @@ -6972,7 +6960,7 @@ fn resume_program_works() { RuntimeOrigin::signed(USER_3), program_id, program.allocations.clone(), - CodeId::from_origin(program.code_hash), + program.code_hash.cast(), )); let (session_id, session_end_block, ..) = get_last_session(); @@ -6982,7 +6970,7 @@ fn resume_program_works() { RuntimeOrigin::signed(USER_2), program_id, program.allocations, - CodeId::from_origin(program.code_hash), + program.code_hash.cast(), )); let (session_id_2, session_end_block_2, ..) = get_last_session(); @@ -7355,7 +7343,7 @@ fn pay_program_rent_syscall_works() { ); // attempt to pay rent for not existing program - let pay_rent_account_id = AccountId::from_origin(pay_rent_id.into_origin()); + let pay_rent_account_id = pay_rent_id.cast::(); let balance_before = Balances::free_balance(pay_rent_account_id); assert_ok!(Gear::send_message( @@ -8283,12 +8271,12 @@ fn gas_spent_precalculated() { run_to_block(2, None); let get_program_code = |pid| { - let code_id = CodeId::from_origin( - ProgramStorageOf::::get_program(pid) - .and_then(|program| common::ActiveProgram::try_from(program).ok()) - .expect("program must exist") - .code_hash, - ); + let code_id = ProgramStorageOf::::get_program(pid) + .and_then(|program| common::ActiveProgram::try_from(program).ok()) + .expect("program must exist") + .code_hash + .cast(); + ::CodeStorage::get_code(code_id).unwrap() }; @@ -8531,8 +8519,7 @@ fn test_create_program_with_value_lt_ed() { // programs deployed by user and by program assert_init_success(2); - let origin_msg_id = - MessageId::generate_from_user(1, ProgramId::from_origin(USER_1.into_origin()), 0); + let origin_msg_id = MessageId::generate_from_user(1, USER_1.cast(), 0); let msg1_mailbox = MessageId::generate_outgoing(origin_msg_id, 0); let msg2_mailbox = MessageId::generate_outgoing(origin_msg_id, 1); assert!(MailboxOf::::contains(&msg_receiver_1, &msg1_mailbox)); @@ -9131,11 +9118,8 @@ fn free_storage_hold_on_scheduler_overwhelm() { let user_2_balance = Balances::free_balance(USER_2); assert_eq!(GearBank::::account_total(&USER_2), 0); - let prog_balance = Balances::free_balance(AccountId::from_origin(sender.into_origin())); - assert_eq!( - GearBank::::account_total(&AccountId::from_origin(sender.into_origin())), - 0 - ); + let prog_balance = Balances::free_balance(sender.cast::()); + assert_eq!(GearBank::::account_total(&sender.cast()), 0); let (_, gas_info) = utils::calculate_handle_and_send_with_extra( USER_1, @@ -10427,7 +10411,7 @@ fn missing_functions_are_not_executed() { let locked_value = 1_000; assert_ok!(>::transfer( &USER_1, - &AccountId::from_origin(program_id.into_origin()), + &program_id.cast(), locked_value, frame_support::traits::ExistenceRequirement::AllowDeath )); @@ -14406,7 +14390,7 @@ fn send_gasless_reply_works() { // Top up program's account balance with some funds CurrencyOf::::resolve_creating( - &AccountId::from_origin(prog_id.into_origin()), + &prog_id.cast(), CurrencyOf::::issue(2_000_u128), ); @@ -14714,7 +14698,7 @@ fn test_send_to_terminated_from_program() { init_logger(); new_test_ext().execute_with(|| { - let user_1_bytes = ProgramId::from_origin(USER_1.into_origin()).into_bytes(); + let user_1_bytes = USER_1.into_origin().to_fixed_bytes(); // Dies in init let init = Calls::builder().panic("Die in init"); @@ -15308,7 +15292,7 @@ mod utils { free: impl Into>, reserved: impl Into>, ) { - let account_id = AccountId::from_origin(origin.into_origin()); + let account_id = origin.cast(); assert_eq!(Balances::free_balance(account_id), free.into()); assert_eq!( GearBank::::account_total(&account_id), @@ -15483,7 +15467,7 @@ mod utils { // If value can't be reserved, message is skipped. assert_ok!(>::transfer( &sender, - &AccountId::from_origin(program_id.into_origin()), + &program_id.cast(), locked_value, frame_support::traits::ExistenceRequirement::AllowDeath )); diff --git a/pallets/payment/src/tests.rs b/pallets/payment/src/tests.rs index 067c4db71a4..c468452e1e1 100644 --- a/pallets/payment/src/tests.rs +++ b/pallets/payment/src/tests.rs @@ -26,10 +26,7 @@ use frame_support::{ dispatch::{DispatchInfo, GetDispatchInfo, PostDispatchInfo}, weights::{Weight, WeightToFee}, }; -use gear_core::{ - ids::{MessageId, ProgramId}, - message::{Dispatch, DispatchKind, Message, StoredDispatch, UserStoredMessage}, -}; +use gear_core::message::{Dispatch, DispatchKind, Message, StoredDispatch, UserStoredMessage}; use pallet_transaction_payment::{FeeDetails, InclusionFee, Multiplier, RuntimeDispatchInfo}; use primitive_types::H256; use sp_runtime::{testing::TestXt, traits::SignedExtension, FixedPointNumber}; @@ -169,7 +166,7 @@ fn fee_rounding_error_bounded_by_multiplier() { // rounding error only arises for calls that do not affect MQ let call: &::RuntimeCall = &RuntimeCall::Gear(pallet_gear::Call::claim_value { - message_id: MessageId::from_origin(H256::from_low_u64_le(1)), + message_id: H256::from_low_u64_le(1).cast(), }); let weights = vec![ @@ -210,7 +207,7 @@ fn mq_size_affecting_fee_works() { let alice_initial_balance = Balances::free_balance(ALICE); let author_initial_balance = Balances::free_balance(BLOCK_AUTHOR); - let program_id = ProgramId::from_origin(H256::random()); + let program_id = H256::random().cast(); let call: &::RuntimeCall = &RuntimeCall::Gear(pallet_gear::Call::send_message { @@ -308,7 +305,7 @@ fn mq_size_not_affecting_fee_works() { let call: &::RuntimeCall = &RuntimeCall::Gear(pallet_gear::Call::claim_value { - message_id: MessageId::from_origin(H256::from_low_u64_le(1)), + message_id: H256::from_low_u64_le(1).cast(), }); let len = 100usize; @@ -393,7 +390,7 @@ fn mq_size_not_affecting_fee_works() { #[test] #[allow(clippy::let_unit_value)] fn query_info_and_fee_details_work() { - let program_id = ProgramId::from_origin(H256::random()); + let program_id = H256::random().cast(); let call_affecting_mq = RuntimeCall::Gear(pallet_gear::Call::send_message { destination: program_id, payload: Default::default(), @@ -568,7 +565,7 @@ fn fee_payer_replacement_works() { let author_initial_balance = Balances::free_balance(BLOCK_AUTHOR); let synthesized_initial_balance = Balances::free_balance(FEE_PAYER); - let program_id = ProgramId::from_origin(H256::random()); + let program_id = H256::random().cast(); let call: &::RuntimeCall = &RuntimeCall::GearVoucher(pallet_gear_voucher::Call::call { @@ -627,14 +624,14 @@ fn reply_with_voucher_pays_fee_from_voucher_ok() { let author_initial_balance = Balances::free_balance(BLOCK_AUTHOR); let bob_initial_balance = Balances::free_balance(BOB); - let msg_id = MessageId::from_origin(H256::random()); - let program_id = ProgramId::from_origin(H256::random()); + let msg_id = H256::random().cast(); + let program_id = H256::random().cast(); // Put message in BOB's mailbox assert_ok!(MailboxOf::::insert( UserStoredMessage::new( msg_id, program_id, - ProgramId::from_origin(BOB.into_origin()), + BOB.cast(), Default::default(), Default::default(), ),