1use crate::{
21 BalanceOf, Config, H160, U256, deposit_payment::Funds, exec::MomentOf, mock::MockHandler,
22 storage::WriteOutcome, transient_storage::TransientStorage,
23};
24use alloc::{boxed::Box, fmt::Debug, string::String, vec::Vec};
25use codec::{Decode, Encode, MaxEncodedLen};
26use core::cell::RefCell;
27use frame_support::{DefaultNoBound, traits::tokens::Balance, weights::Weight};
28use pallet_revive_types::runtime_api::{
29 CodeV1, ContractResultV1, EthTransactInfoV1, ExecReturnValueV1, InstantiateReturnValueV1,
30 StorageDepositV1,
31};
32use pallet_revive_uapi::ReturnFlags;
33use scale_info::TypeInfo;
34use sp_core::Get;
35use sp_runtime::{
36 DispatchError,
37 traits::{One, Saturating, Zero},
38};
39
40#[derive(Clone, Eq, PartialEq, Debug)]
51pub struct ContractResult<R, Balance> {
52 pub weight_consumed: Weight,
54 pub weight_required: Weight,
68 pub storage_deposit: StorageDeposit<Balance>,
75 pub max_storage_deposit: StorageDeposit<Balance>,
86 pub gas_consumed: Balance,
88 pub result: Result<R, DispatchError>,
90}
91
92impl<R: Default, B: Balance> Default for ContractResult<R, B> {
93 fn default() -> Self {
94 Self {
95 weight_consumed: Default::default(),
96 weight_required: Default::default(),
97 storage_deposit: Default::default(),
98 max_storage_deposit: Default::default(),
99 gas_consumed: Default::default(),
100 result: Ok(Default::default()),
101 }
102 }
103}
104
105impl<R, RV1, Balance> From<ContractResult<R, Balance>> for ContractResultV1<RV1, Balance>
106where
107 RV1: From<R>,
108{
109 fn from(value: ContractResult<R, Balance>) -> Self {
110 Self {
111 weight_consumed: value.weight_consumed,
112 weight_required: value.weight_required,
113 storage_deposit: value.storage_deposit.into(),
114 max_storage_deposit: value.max_storage_deposit.into(),
115 gas_consumed: value.gas_consumed,
116 result: value.result.map(Into::into),
117 }
118 }
119}
120
121#[derive(Clone, Eq, PartialEq, Default, Debug)]
123pub struct EthTransactInfo<Balance> {
124 pub weight_required: Weight,
128 pub storage_deposit: Balance,
130 pub max_storage_deposit: Balance,
135 pub eth_gas: U256,
137 pub data: Vec<u8>,
139}
140
141impl<Balance> From<EthTransactInfo<Balance>> for EthTransactInfoV1<Balance> {
142 fn from(value: EthTransactInfo<Balance>) -> Self {
143 Self {
144 weight_required: value.weight_required,
145 storage_deposit: value.storage_deposit,
146 max_storage_deposit: value.max_storage_deposit,
147 eth_gas: value.eth_gas,
148 data: value.data,
149 }
150 }
151}
152
153#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)]
155pub enum EthTransactError {
156 Data(Vec<u8>),
157 Message(String),
158}
159
160#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)]
161pub enum BalanceConversionError {
163 Value,
165 Dust,
167}
168
169#[derive(Default, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Debug)]
172pub struct BalanceWithDust<Balance> {
173 value: Balance,
175 dust: u32,
178}
179
180impl<Balance> From<Balance> for BalanceWithDust<Balance> {
181 fn from(value: Balance) -> Self {
182 Self { value, dust: 0 }
183 }
184}
185
186impl<Balance> BalanceWithDust<Balance> {
187 pub fn deconstruct(self) -> (Balance, u32) {
189 (self.value, self.dust)
190 }
191
192 pub fn new_unchecked<T: Config>(value: Balance, dust: u32) -> Self {
194 debug_assert!(dust < T::NativeToEthRatio::get());
195 Self { value, dust }
196 }
197
198 pub fn from_value<T: Config>(
200 value: U256,
201 ) -> Result<BalanceWithDust<BalanceOf<T>>, BalanceConversionError> {
202 if value.is_zero() {
203 return Ok(Default::default());
204 }
205
206 let (quotient, remainder) = value.div_mod(T::NativeToEthRatio::get().into());
207 let value = quotient.try_into().map_err(|_| BalanceConversionError::Value)?;
208 let dust = remainder.try_into().map_err(|_| BalanceConversionError::Dust)?;
209
210 Ok(BalanceWithDust { value, dust })
211 }
212}
213
214impl<Balance: Zero + One + Saturating> BalanceWithDust<Balance> {
215 pub fn is_zero(&self) -> bool {
217 self.value.is_zero() && self.dust == 0
218 }
219
220 pub fn into_rounded_balance(self) -> Balance {
222 if self.dust == 0 { self.value } else { self.value.saturating_add(Balance::one()) }
223 }
224}
225
226pub type CodeUploadResult<Balance> = Result<CodeUploadReturnValue<Balance>, DispatchError>;
228
229pub type GetStorageResult = Result<Option<Vec<u8>>, ContractAccessError>;
231
232pub type SetStorageResult = Result<WriteOutcome, ContractAccessError>;
234
235#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, MaxEncodedLen, Debug, TypeInfo)]
237pub enum ContractAccessError {
238 DoesntExist,
240 KeyDecodingFailed,
242 StorageWriteFailed(DispatchError),
244}
245
246#[derive(Clone, PartialEq, Eq, Debug, Default)]
248pub struct ExecReturnValue {
249 pub flags: ReturnFlags,
251 pub data: Vec<u8>,
253}
254
255impl ExecReturnValue {
256 pub fn did_revert(&self) -> bool {
258 self.flags.contains(ReturnFlags::REVERT)
259 }
260}
261
262impl From<ExecReturnValue> for ExecReturnValueV1 {
263 fn from(value: ExecReturnValue) -> Self {
264 Self { flags: value.flags, data: value.data }
265 }
266}
267
268#[derive(Clone, PartialEq, Eq, Debug, Default)]
270pub struct InstantiateReturnValue {
271 pub result: ExecReturnValue,
273 pub addr: H160,
275}
276
277impl From<InstantiateReturnValue> for InstantiateReturnValueV1 {
278 fn from(value: InstantiateReturnValue) -> Self {
279 Self { result: value.result.into(), addr: value.addr }
280 }
281}
282
283#[derive(Clone, PartialEq, Eq, Encode, Decode, MaxEncodedLen, Debug, TypeInfo)]
285pub struct CodeUploadReturnValue<Balance> {
286 pub code_hash: sp_core::H256,
288 pub deposit: Balance,
290}
291
292impl<Balance> From<CodeUploadReturnValue<Balance>>
293 for pallet_revive_types::runtime_api::CodeUploadReturnValueV1<Balance>
294{
295 fn from(value: CodeUploadReturnValue<Balance>) -> Self {
296 Self { code_hash: value.code_hash, deposit: value.deposit }
297 }
298}
299
300#[derive(Clone, Eq, PartialEq, Debug)]
302pub enum Code {
303 Upload(Vec<u8>),
305 Existing(sp_core::H256),
307}
308
309impl From<CodeV1> for Code {
310 fn from(value: CodeV1) -> Self {
311 match value {
312 CodeV1::Upload(code) => Self::Upload(code),
313 CodeV1::Existing(code_hash) => Self::Existing(code_hash),
314 }
315 }
316}
317
318#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
320pub enum StorageDeposit<Balance> {
321 Refund(Balance),
326 Charge(Balance),
331}
332
333impl<Balance> From<StorageDeposit<Balance>> for StorageDepositV1<Balance> {
334 fn from(value: StorageDeposit<Balance>) -> Self {
335 match value {
336 StorageDeposit::Refund(amount) => Self::Refund(amount),
337 StorageDeposit::Charge(amount) => Self::Charge(amount),
338 }
339 }
340}
341
342impl<T, Balance> ContractResult<T, Balance> {
343 pub fn map_result<V>(self, map_fn: impl FnOnce(T) -> V) -> ContractResult<V, Balance> {
344 ContractResult {
345 weight_consumed: self.weight_consumed,
346 weight_required: self.weight_required,
347 storage_deposit: self.storage_deposit,
348 max_storage_deposit: self.max_storage_deposit,
349 gas_consumed: self.gas_consumed,
350 result: self.result.map(map_fn),
351 }
352 }
353}
354
355impl<Balance: Zero> Default for StorageDeposit<Balance> {
356 fn default() -> Self {
357 Self::Charge(Zero::zero())
358 }
359}
360
361impl<Balance: Zero + Copy> StorageDeposit<Balance> {
362 pub fn charge_or_zero(&self) -> Balance {
364 match self {
365 Self::Charge(amount) => *amount,
366 Self::Refund(_) => Zero::zero(),
367 }
368 }
369
370 pub fn is_zero(&self) -> bool {
371 match self {
372 Self::Charge(amount) => amount.is_zero(),
373 Self::Refund(amount) => amount.is_zero(),
374 }
375 }
376}
377
378impl<Balance> StorageDeposit<Balance>
379where
380 Balance: frame_support::traits::tokens::Balance + Saturating + Ord + Copy,
381{
382 pub fn saturating_add(&self, rhs: &Self) -> Self {
384 use StorageDeposit::*;
385 match (self, rhs) {
386 (Charge(lhs), Charge(rhs)) => Charge(lhs.saturating_add(*rhs)),
387 (Refund(lhs), Refund(rhs)) => Refund(lhs.saturating_add(*rhs)),
388 (Charge(lhs), Refund(rhs)) => {
389 if lhs >= rhs {
390 Charge(lhs.saturating_sub(*rhs))
391 } else {
392 Refund(rhs.saturating_sub(*lhs))
393 }
394 },
395 (Refund(lhs), Charge(rhs)) => {
396 if lhs > rhs {
397 Refund(lhs.saturating_sub(*rhs))
398 } else {
399 Charge(rhs.saturating_sub(*lhs))
400 }
401 },
402 }
403 }
404
405 pub fn saturating_sub(&self, rhs: &Self) -> Self {
407 use StorageDeposit::*;
408 match (self, rhs) {
409 (Charge(lhs), Refund(rhs)) => Charge(lhs.saturating_add(*rhs)),
410 (Refund(lhs), Charge(rhs)) => Refund(lhs.saturating_add(*rhs)),
411 (Charge(lhs), Charge(rhs)) => {
412 if lhs >= rhs {
413 Charge(lhs.saturating_sub(*rhs))
414 } else {
415 Refund(rhs.saturating_sub(*lhs))
416 }
417 },
418 (Refund(lhs), Refund(rhs)) => {
419 if lhs > rhs {
420 Refund(lhs.saturating_sub(*rhs))
421 } else {
422 Charge(rhs.saturating_sub(*lhs))
423 }
424 },
425 }
426 }
427
428 pub fn available(&self, limit: &Balance) -> Option<Balance> {
435 use StorageDeposit::*;
436 match self {
437 Charge(amount) => limit.checked_sub(amount),
438 Refund(amount) => Some(limit.saturating_add(*amount)),
439 }
440 }
441}
442
443#[derive(DefaultNoBound)]
445pub struct ExecConfig<T: Config> {
446 pub bump_nonce: bool,
463 pub collect_deposit_from_hold: Option<(u32, Weight)>,
468 pub effective_gas_price: Option<U256>,
472 pub is_dry_run: Option<DryRunConfigurations<MomentOf<T>>>,
475 pub mock_handler: Option<Box<dyn MockHandler<T>>>,
479 pub test_env_transient_storage: Option<RefCell<TransientStorage<T>>>,
484}
485
486impl<T: Config> ExecConfig<T> {
487 pub fn new_substrate_tx() -> Self {
489 Self {
490 bump_nonce: true,
491 collect_deposit_from_hold: None,
492 effective_gas_price: None,
493 is_dry_run: None,
494 mock_handler: None,
495 test_env_transient_storage: None,
496 }
497 }
498
499 pub fn new_substrate_tx_without_bump() -> Self {
500 Self {
501 bump_nonce: false,
502 collect_deposit_from_hold: None,
503 effective_gas_price: None,
504 mock_handler: None,
505 is_dry_run: None,
506 test_env_transient_storage: None,
507 }
508 }
509
510 pub fn new_eth_tx(effective_gas_price: U256, encoded_len: u32, base_weight: Weight) -> Self {
512 Self {
513 bump_nonce: false,
514 collect_deposit_from_hold: Some((encoded_len, base_weight)),
515 effective_gas_price: Some(effective_gas_price),
516 mock_handler: None,
517 is_dry_run: None,
518 test_env_transient_storage: None,
519 }
520 }
521
522 pub fn with_dry_run(mut self, timestamp_override: impl Into<Option<MomentOf<T>>>) -> Self {
524 self.is_dry_run =
525 Some(DryRunConfigurations { timestamp_override: timestamp_override.into() });
526 self
527 }
528
529 pub fn funds<'a>(&self, account: &'a T::AccountId) -> Funds<'a, T::AccountId> {
533 if self.collect_deposit_from_hold.is_some() {
534 Funds::TxFee(account)
535 } else {
536 Funds::Balance(account)
537 }
538 }
539
540 #[cfg(test)]
542 pub fn clone(&self) -> Self {
543 Self {
544 bump_nonce: self.bump_nonce,
545 collect_deposit_from_hold: self.collect_deposit_from_hold,
546 effective_gas_price: self.effective_gas_price,
547 is_dry_run: self.is_dry_run.clone(),
548 mock_handler: None,
549 test_env_transient_storage: None,
550 }
551 }
552}
553
554#[derive(Clone)]
555pub struct DryRunConfigurations<Moment> {
556 pub timestamp_override: Option<Moment>,
557}
558
559#[must_use = "You must handle whether the code was removed or not."]
561pub enum CodeRemoved {
562 No,
564 Yes,
566}