Skip to content

Commit

Permalink
Replace legacy pallet_contracts_primitives with local types (#1470)
Browse files Browse the repository at this point in the history
* Update `subxt` to `0.34`

* Update substrate deps

* Replace legacy pallet_contracts_primitives dependency

* Use local `StorageDeposit` type
  • Loading branch information
ascjones authored Jan 25, 2024
1 parent 1319a7f commit 55ea917
Show file tree
Hide file tree
Showing 11 changed files with 854 additions and 512 deletions.
1,103 changes: 643 additions & 460 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 3 additions & 4 deletions crates/cargo-contract/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,9 @@ crossterm = "0.27.0"

# dependencies for extrinsics (deploying and calling a contract)
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
subxt = "0.33.0"
sp-core = "22.0.0"
sp-weights = "21.0.0"
pallet-contracts-primitives = "25.0.0"
subxt = "0.34.0"
sp-core = "28.0.0"
sp-weights = "27.0.0"
hex = "0.4.3"

[build-dependencies]
Expand Down
7 changes: 4 additions & 3 deletions crates/cargo-contract/src/cmd/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use super::{
print_dry_running_status,
print_gas_required_success,
prompt_confirm_tx,
Balance,
CLIExtrinsicOpts,
MAX_KEY_COL_WIDTH,
};
Expand All @@ -36,12 +37,12 @@ use anyhow::{
};
use contract_build::name_value_println;
use contract_extrinsics::{
pallet_contracts_primitives::StorageDeposit,
BalanceVariant,
CallCommandBuilder,
CallExec,
DefaultConfig,
ExtrinsicOptsBuilder,
StorageDeposit,
};
use contract_transcode::Value;
use sp_weights::Weight;
Expand Down Expand Up @@ -123,7 +124,7 @@ impl CallCommand {
data: value,
gas_consumed: result.gas_consumed,
gas_required: result.gas_required,
storage_deposit: StorageDeposit::from(&result.storage_deposit),
storage_deposit: result.storage_deposit.clone(),
};
if self.output_json() {
println!("{}", dry_run_result.to_json()?);
Expand Down Expand Up @@ -245,7 +246,7 @@ pub struct CallDryRunResult {
pub gas_consumed: Weight,
pub gas_required: Weight,
/// Storage deposit after the operation
pub storage_deposit: StorageDeposit,
pub storage_deposit: StorageDeposit<Balance>,
}

impl CallDryRunResult {
Expand Down
2 changes: 1 addition & 1 deletion crates/cargo-contract/src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ use contract_build::{
};
pub(crate) use contract_extrinsics::ErrorVariant;
use contract_extrinsics::{
pallet_contracts_primitives::ContractResult,
Balance,
BalanceVariant,
};
use pallet_contracts_primitives::ContractResult;
use std::io::{
self,
Write,
Expand Down
12 changes: 6 additions & 6 deletions crates/extrinsics/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ serde_json = "1.0.111"
url = { version = "2.5.0", features = ["serde"] }
rust_decimal = "1.33"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
sp-core = "22.0.0"
sp-runtime = "25.0.0"
sp-weights = "21.0.0"
pallet-contracts-primitives = "25.0.0"
sp-core = "28.0.0"
sp-runtime = "31.0.0"
sp-weights = "27.0.0"
pallet-contracts-uapi = "5.0.0"
scale-info = "2.10.0"
subxt = "0.33.0"
subxt-signer = { version = "0.33.0", features = ["subxt", "sr25519"] }
subxt = "0.34.0"
subxt-signer = { version = "0.34.0", features = ["subxt", "sr25519"] }
hex = "0.4.3"
ink_metadata = "5.0.0-rc"

Expand Down
2 changes: 1 addition & 1 deletion crates/extrinsics/src/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use super::{
account_id,
events::DisplayEvents,
pallet_contracts_primitives::ContractExecResult,
state,
state_call,
submit_extrinsic,
Expand All @@ -40,7 +41,6 @@ use anyhow::{
anyhow,
Result,
};
use pallet_contracts_primitives::ContractExecResult;
use scale::Encode;
use sp_weights::Weight;
use subxt_signer::sr25519::Keypair;
Expand Down
11 changes: 6 additions & 5 deletions crates/extrinsics/src/instantiate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ use super::{
CodeStored,
ContractInstantiated,
},
pallet_contracts_primitives::{
ContractInstantiateResult,
StorageDeposit,
},
state,
state_call,
submit_extrinsic,
Expand All @@ -31,7 +35,6 @@ use super::{
DefaultConfig,
ErrorVariant,
Missing,
StorageDeposit,
TokenMetadata,
};
use crate::{
Expand All @@ -50,8 +53,6 @@ use anyhow::{
use contract_transcode::Value;
use subxt_signer::sr25519::Keypair;

use pallet_contracts_primitives::ContractInstantiateResult;

use core::marker::PhantomData;
use scale::Encode;
use sp_core::Bytes;
Expand Down Expand Up @@ -325,7 +326,7 @@ impl InstantiateExec {
reverted: ret_val.result.did_revert(),
gas_consumed: result.gas_consumed,
gas_required: result.gas_required,
storage_deposit: StorageDeposit::from(&result.storage_deposit),
storage_deposit: result.storage_deposit.clone(),
};
Ok(dry_run_result)
}
Expand Down Expand Up @@ -544,7 +545,7 @@ pub struct InstantiateDryRunResult {
pub gas_consumed: Weight,
pub gas_required: Weight,
/// Storage deposit after the operation
pub storage_deposit: StorageDeposit,
pub storage_deposit: StorageDeposit<Balance>,
}

impl InstantiateDryRunResult {
Expand Down
30 changes: 1 addition & 29 deletions crates/extrinsics/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ mod events;
mod extrinsic_calls;
mod extrinsic_opts;
mod instantiate;
pub mod pallet_contracts_primitives;
mod remove;
mod upload;

Expand Down Expand Up @@ -275,35 +276,6 @@ pub fn url_to_string(url: &url::Url) -> String {
}
}

/// Copy of `pallet_contracts_primitives::StorageDeposit` which implements `Serialize`,
/// required for json output.
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, serde::Serialize)]
pub enum StorageDeposit {
/// The transaction reduced storage consumption.
///
/// This means that the specified amount of balance was transferred from the involved
/// contracts to the call origin.
Refund(Balance),
/// The transaction increased overall storage usage.
///
/// This means that the specified amount of balance was transferred from the call
/// origin to the contracts involved.
Charge(Balance),
}

impl From<&pallet_contracts_primitives::StorageDeposit<Balance>> for StorageDeposit {
fn from(deposit: &pallet_contracts_primitives::StorageDeposit<Balance>) -> Self {
match deposit {
pallet_contracts_primitives::StorageDeposit::Refund(balance) => {
Self::Refund(*balance)
}
pallet_contracts_primitives::StorageDeposit::Charge(balance) => {
Self::Charge(*balance)
}
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
186 changes: 186 additions & 0 deletions crates/extrinsics/src/pallet_contracts_primitives.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
// Copyright 2018-2024 Parity Technologies (UK) Ltd.
// This file is part of cargo-contract.
//
// cargo-contract is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// cargo-contract is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with cargo-contract. If not, see <http://www.gnu.org/licenses/>.

use pallet_contracts_uapi::ReturnFlags;
use scale::{
Decode,
Encode,
MaxEncodedLen,
};
use scale_info::TypeInfo;
use sp_runtime::{
DispatchError,
RuntimeDebug,
};
use sp_weights::Weight;

// A copy of primitive types defined within `pallet_contracts`, required for RPC calls.

/// Result type of a `bare_call` or `bare_instantiate` call as well as
/// `ContractsApi::call` and `ContractsApi::instantiate`.
///
/// It contains the execution result together with some auxiliary information.
///
/// #Note
///
/// It has been extended to include `events` at the end of the struct while not bumping
/// the `ContractsApi` version. Therefore when SCALE decoding a `ContractResult` its
/// trailing data should be ignored to avoid any potential compatibility issues.
#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct ContractResult<R, Balance, EventRecord> {
/// How much weight was consumed during execution.
pub gas_consumed: Weight,
/// How much weight is required as gas limit in order to execute this call.
///
/// This value should be used to determine the weight limit for on-chain execution.
///
/// # Note
///
/// This can only different from [`Self::gas_consumed`] when weight pre charging
/// is used. Currently, only `seal_call_runtime` makes use of pre charging.
/// Additionally, any `seal_call` or `seal_instantiate` makes use of pre-charging
/// when a non-zero `gas_limit` argument is supplied.
pub gas_required: Weight,
/// How much balance was paid by the origin into the contract's deposit account in
/// order to pay for storage.
///
/// The storage deposit is never actually charged from the origin in case of
/// [`Self::result`] is `Err`. This is because on error all storage changes are
/// rolled back including the payment of the deposit.
pub storage_deposit: StorageDeposit<Balance>,
/// An optional debug message. This message is only filled when explicitly requested
/// by the code that calls into the contract. Otherwise it is empty.
///
/// The contained bytes are valid UTF-8. This is not declared as `String` because
/// this type is not allowed within the runtime.
///
/// Clients should not make any assumptions about the format of the buffer.
/// They should just display it as-is. It is **not** only a collection of log lines
/// provided by a contract but a formatted buffer with different sections.
///
/// # Note
///
/// The debug message is never generated during on-chain execution. It is reserved
/// for RPC calls.
pub debug_message: Vec<u8>,
/// The execution result of the wasm code.
pub result: R,
/// The events that were emitted during execution. It is an option as event
/// collection is optional.
pub events: Option<Vec<EventRecord>>,
}

/// Result type of a `bare_call` call as well as `ContractsApi::call`.
pub type ContractExecResult<Balance, EventRecord> =
ContractResult<Result<ExecReturnValue, DispatchError>, Balance, EventRecord>;

/// Result type of a `bare_instantiate` call as well as `ContractsApi::instantiate`.
pub type ContractInstantiateResult<AccountId, Balance, EventRecord> = ContractResult<
Result<InstantiateReturnValue<AccountId>, DispatchError>,
Balance,
EventRecord,
>;

/// Result type of a `bare_code_upload` call.
pub type CodeUploadResult<CodeHash, Balance> =
Result<CodeUploadReturnValue<CodeHash, Balance>, DispatchError>;

/// Result type of a `get_storage` call.
pub type GetStorageResult = Result<Option<Vec<u8>>, ContractAccessError>;

/// The possible errors that can happen querying the storage of a contract.
#[derive(
Copy, Clone, Eq, PartialEq, Encode, Decode, MaxEncodedLen, RuntimeDebug, TypeInfo,
)]
pub enum ContractAccessError {
/// The given address doesn't point to a contract.
DoesntExist,
/// Storage key cannot be decoded from the provided input data.
KeyDecodingFailed,
/// Storage is migrating. Try again later.
MigrationInProgress,
}

/// Output of a contract call or instantiation which ran to completion.
#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct ExecReturnValue {
/// Flags passed along by `seal_return`. Empty when `seal_return` was never called.
pub flags: ReturnFlags,
/// Buffer passed along by `seal_return`. Empty when `seal_return` was never called.
pub data: Vec<u8>,
}

impl ExecReturnValue {
/// The contract did revert all storage changes.
pub fn did_revert(&self) -> bool {
self.flags.contains(ReturnFlags::REVERT)
}
}

/// The result of a successful contract instantiation.
#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct InstantiateReturnValue<AccountId> {
/// The output of the called constructor.
pub result: ExecReturnValue,
/// The account id of the new contract.
pub account_id: AccountId,
}

/// The result of successfully uploading a contract.
#[derive(Clone, PartialEq, Eq, Encode, Decode, MaxEncodedLen, RuntimeDebug, TypeInfo)]
pub struct CodeUploadReturnValue<CodeHash, Balance> {
/// The key under which the new code is stored.
pub code_hash: CodeHash,
/// The deposit that was reserved at the caller. Is zero when the code already
/// existed.
pub deposit: Balance,
}

/// Reference to an existing code hash or a new wasm module.
#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)]
pub enum Code<Hash> {
/// A wasm module as raw bytes.
Upload(Vec<u8>),
/// The code hash of an on-chain wasm blob.
Existing(Hash),
}

/// The amount of balance that was either charged or refunded in order to pay for storage.
#[derive(
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Encode,
Decode,
MaxEncodedLen,
RuntimeDebug,
TypeInfo,
serde::Serialize,
)]
pub enum StorageDeposit<Balance> {
/// The transaction reduced storage consumption.
///
/// This means that the specified amount of balance was transferred from the involved
/// deposit accounts to the origin.
Refund(Balance),
/// The transaction increased storage consumption.
///
/// This means that the specified amount of balance was transferred from the origin
/// to the involved deposit accounts.
Charge(Balance),
}
2 changes: 1 addition & 1 deletion crates/extrinsics/src/upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use super::{
CodeStored,
DisplayEvents,
},
pallet_contracts_primitives::CodeUploadResult,
state,
state_call,
submit_extrinsic,
Expand All @@ -40,7 +41,6 @@ use crate::{
use anyhow::Result;
use contract_transcode::ContractMessageTranscoder;
use core::marker::PhantomData;
use pallet_contracts_primitives::CodeUploadResult;
use scale::Encode;
use subxt::{
backend::{
Expand Down
Loading

0 comments on commit 55ea917

Please sign in to comment.