Skip to content

Commit

Permalink
Mesh 1922 - Remove with_transaction (#1791)
Browse files Browse the repository at this point in the history
* Remove with_transaction - part 1

* Remove with_transaction - part 2

---------

Co-authored-by: Robert Gabriel Jakabosky <[email protected]>
  • Loading branch information
HenriqueNogara and Neopallium authored Feb 26, 2025
1 parent 08ae63f commit 90087f5
Show file tree
Hide file tree
Showing 6 changed files with 132 additions and 149 deletions.
39 changes: 18 additions & 21 deletions pallets/corporate-actions/src/distribution/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,8 @@ use pallet_identity::PermissionedCallOriginData;
use polymesh_common_utilities::protocol_fee::{ChargeProtocolFee, ProtocolOp};
use polymesh_primitives::asset::AssetId;
use polymesh_primitives::{
constants::currency::ONE_UNIT, storage_migration_ver, traits::PortfolioSubTrait,
with_transaction, Balance, EventDid, IdentityId, Moment, PortfolioId, PortfolioNumber,
SecondaryKey, WeightMeter,
constants::currency::ONE_UNIT, storage_migration_ver, traits::PortfolioSubTrait, Balance,
EventDid, IdentityId, Moment, PortfolioId, PortfolioNumber, SecondaryKey, WeightMeter,
};
use scale_info::TypeInfo;
use sp_runtime::traits::Zero;
Expand Down Expand Up @@ -583,24 +582,22 @@ impl<T: Config> Pallet<T> {
gain / ONE_UNIT * ONE_UNIT
};

with_transaction(|| {
// Unlock `benefit` of `currency` from the calling agent's portfolio.
Self::unlock(&dist, benefit)?;

// Transfer remainder (`gain`) to DID.
let to = PortfolioId::default_portfolio(holder);
let mut weight_meter = WeightMeter::max_limit_no_minimum();
<Asset<T>>::base_transfer(
dist.from,
to,
dist.currency,
gain,
None,
None,
actor.clone().risky_into_inner(),
&mut weight_meter,
)
})?;
// Unlock `benefit` of `currency` from the calling agent's portfolio.
Self::unlock(&dist, benefit)?;

// Transfer remainder (`gain`) to DID.
let to = PortfolioId::default_portfolio(holder);
let mut weight_meter = WeightMeter::max_limit_no_minimum();
<Asset<T>>::base_transfer(
dist.from,
to,
dist.currency,
gain,
None,
None,
actor.clone().risky_into_inner(),
&mut weight_meter,
)?;

// Note that DID was paid.
HolderPaid::<T>::insert((ca_id, holder), true);
Expand Down
103 changes: 49 additions & 54 deletions pallets/corporate-actions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ use pallet_identity::{Config as IdentityConfig, PermissionedCallOriginData};
use polymesh_common_utilities::checkpoint::ScheduleId;
use polymesh_primitives::asset::AssetId;
use polymesh_primitives::{
asset::CheckpointId, impl_checked_inc, storage_migration_ver, with_transaction, Balance,
DocumentId, EventDid, IdentityId, Moment, PortfolioNumber, GC_DID,
asset::CheckpointId, impl_checked_inc, storage_migration_ver, Balance, DocumentId, EventDid,
IdentityId, Moment, PortfolioNumber, GC_DID,
};
use polymesh_primitives_derive::VecU8StrongTyped;
use scale_info::TypeInfo;
Expand Down Expand Up @@ -827,31 +827,28 @@ pub mod pallet {
let agent = caller_did.for_event();
let mut ca = Self::ensure_ca_exists(ca_id)?;

with_transaction(|| -> DispatchResult {
// If provided, either use the existing CP ID or schedule one to be made.
Self::dec_strong_ref_count(ca_id, ca.record_date);
ca.record_date = record_date
.map(|date| Self::handle_record_date(caller_did, ca_id.asset_id, date))
.transpose()?;

// Ensure associated services allow changing the date.
match ca.kind {
CAKind::Other | CAKind::Reorganization => {}
CAKind::IssuerNotice => {
if let Some(range) = TimeRanges::<T>::get(ca_id) {
Self::ensure_record_date_before_start(&ca, range.start)?;
<Ballot<T>>::ensure_ballot_not_started(range)?;
}
// If provided, either use the existing CP ID or schedule one to be made.
Self::dec_strong_ref_count(ca_id, ca.record_date);
ca.record_date = record_date
.map(|date| Self::handle_record_date(caller_did, ca_id.asset_id, date))
.transpose()?;

// Ensure associated services allow changing the date.
match ca.kind {
CAKind::Other | CAKind::Reorganization => {}
CAKind::IssuerNotice => {
if let Some(range) = TimeRanges::<T>::get(ca_id) {
Self::ensure_record_date_before_start(&ca, range.start)?;
<Ballot<T>>::ensure_ballot_not_started(range)?;
}
CAKind::PredictableBenefit | CAKind::UnpredictableBenefit => {
if let Some(dist) = Distributions::<T>::get(ca_id) {
Self::ensure_record_date_before_start(&ca, dist.payment_at)?;
<Distribution<T>>::ensure_distribution_not_started(&dist)?;
}
}
CAKind::PredictableBenefit | CAKind::UnpredictableBenefit => {
if let Some(dist) = Distributions::<T>::get(ca_id) {
Self::ensure_record_date_before_start(&ca, dist.payment_at)?;
<Distribution<T>>::ensure_distribution_not_started(&dist)?;
}
}
Ok(())
})?;
}

// Commit changes + emit event.
CorporateActions::<T>::insert(ca_id.asset_id, ca_id.local_id, ca.clone());
Expand Down Expand Up @@ -890,31 +887,31 @@ pub mod pallet {
..
} = <ExternalAgents<T>>::ensure_agent_asset_perms(origin, asset_id)?;

with_transaction(|| {
let ca_id = Self::unsafe_initiate_corporate_action(
caller_did,
asset_id,
kind,
decl_date,
record_date,
details,
targets,
default_withholding_tax,
withholding_tax,
)?;

<distribution::Pallet<T>>::unverified_distribute(
caller_did,
secondary_key,
ca_id,
portfolio,
currency,
per_share,
amount,
payment_at,
expires_at,
)
})
let ca_id = Self::unsafe_initiate_corporate_action(
caller_did,
asset_id,
kind,
decl_date,
record_date,
details,
targets,
default_withholding_tax,
withholding_tax,
)?;

<distribution::Pallet<T>>::unverified_distribute(
caller_did,
secondary_key,
ca_id,
portfolio,
currency,
per_share,
amount,
payment_at,
expires_at,
)?;

Ok(())
}
}

Expand Down Expand Up @@ -1025,11 +1022,9 @@ impl<T: Config> Pallet<T> {
// If provided, either use the existing CP ID or schedule one to be made.
let record_date = record_date
.map(|date| {
with_transaction(|| -> Result<_, DispatchError> {
let rd = Self::handle_record_date(caller_did, asset_id, date)?;
ensure!(decl_date <= rd.date, Error::<T>::DeclDateAfterRecordDate);
Ok(rd)
})
let rd = Self::handle_record_date(caller_did, asset_id, date)?;
ensure!(decl_date <= rd.date, Error::<T>::DeclDateAfterRecordDate);
Ok::<RecordDate, DispatchError>(rd)
})
.transpose()?;

Expand Down
10 changes: 4 additions & 6 deletions pallets/external-agents/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,8 @@ use pallet_permissions::{CurrentDispatchableName, CurrentPalletName};
use polymesh_primitives::agent::{AGId, AgentGroup};
use polymesh_primitives::asset::AssetId;
use polymesh_primitives::{
extract_auth, storage_migration_ver, traits::AssetFnConfig, with_transaction,
AuthorizationData, EventDid, ExtrinsicPermissions, IdentityId, PalletPermissions, Signatory,
SubsetRestriction,
extract_auth, storage_migration_ver, traits::AssetFnConfig, AuthorizationData, EventDid,
ExtrinsicPermissions, IdentityId, PalletPermissions, Signatory, SubsetRestriction,
};
use sp_std::prelude::*;

Expand Down Expand Up @@ -376,9 +375,8 @@ pub mod pallet {
perms: ExtrinsicPermissions,
agent: IdentityId,
) -> DispatchResult {
with_transaction(|| {
Self::base_create_and_change_custom_group(origin, asset_id, perms, agent)
})
Self::base_create_and_change_custom_group(origin, asset_id, perms, agent)?;
Ok(())
}
}
}
Expand Down
33 changes: 14 additions & 19 deletions pallets/pips/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ use pallet_base::{ensure_opt_string_limited, try_next_post};
use pallet_identity::{Config as IdentityConfig, PermissionedCallOriginData};
use polymesh_common_utilities::protocol_fee::{ChargeProtocolFee, ProtocolOp};
use polymesh_primitives::constants::PIP_MAX_REPORTING_SIZE;
use polymesh_primitives::storage_migration_ver;
use polymesh_primitives::traits::group::GroupTrait;
use polymesh_primitives::traits::GovernanceGroupTrait;
use polymesh_primitives::{storage_migration_ver, with_transaction};
use polymesh_primitives::{Balance, IdentityId, MaybeBlock, Url};
use polymesh_primitives::{GC_DID, TECHNICAL_DID, UPGRADE_DID};
use polymesh_runtime_common::PipsEnactSnapshotMaximumWeight;
Expand Down Expand Up @@ -737,11 +737,8 @@ pub mod pallet {
);

// Lock the deposit + charge protocol fees.
// Both do check-modify so we need a transaction.
with_transaction(|| {
Self::increase_lock(proposer, deposit)?;
charge()
})?;
Self::increase_lock(proposer, deposit)?;
charge()?;
} else {
// Committee PIPs cannot have a deposit.
ensure!(deposit.is_zero(), Error::<T>::NotFromCommunity);
Expand Down Expand Up @@ -877,19 +874,17 @@ pub mod pallet {

let old_res = Self::aggregate_result(id);

with_transaction(|| {
// Reserve the deposit, or refund if needed.
let curr_deposit = Deposits::<T>::get(id, &voter)
.map(|d| d.amount)
.unwrap_or_default();
if deposit < curr_deposit {
Self::reduce_lock(&voter, curr_deposit - deposit)?;
} else {
Self::increase_lock(&voter, deposit - curr_deposit)?;
}
// Save the vote.
Self::unsafe_vote(id, voter.clone(), Vote(aye_or_nay, deposit))
})?;
// Reserve the deposit, or refund if needed.
let curr_deposit = Deposits::<T>::get(id, &voter)
.map(|d| d.amount)
.unwrap_or_default();
if deposit < curr_deposit {
Self::reduce_lock(&voter, curr_deposit - deposit)?;
} else {
Self::increase_lock(&voter, deposit - curr_deposit)?;
}
// Save the vote.
Self::unsafe_vote(id, voter.clone(), Vote(aye_or_nay, deposit))?;

// Adjust live queue.
Self::adjust_live_queue(id, old_res);
Expand Down
8 changes: 4 additions & 4 deletions pallets/settlement/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1371,12 +1371,12 @@ impl<T: Config> Pallet<T> {
amount,
..
} => T::Portfolio::lock_tokens(&sender, &asset_id, *amount),
Leg::NonFungible { sender, nfts, .. } => with_transaction(|| {
Leg::NonFungible { sender, nfts, .. } => {
for nft_id in nfts.ids() {
T::Portfolio::lock_nft(&sender, nfts.asset_id(), &nft_id)?;
}
Ok(())
}),
}
Leg::OffChain { .. } => Err(Error::<T>::OffChainAssetCantBeLocked.into()),
}
}
Expand All @@ -1389,12 +1389,12 @@ impl<T: Config> Pallet<T> {
amount,
..
} => T::Portfolio::unlock_tokens(&sender, &asset_id, *amount),
Leg::NonFungible { sender, nfts, .. } => with_transaction(|| {
Leg::NonFungible { sender, nfts, .. } => {
for nft_id in nfts.ids() {
T::Portfolio::unlock_nft(&sender, nfts.asset_id(), &nft_id)?;
}
Ok(())
}),
}
Leg::OffChain { .. } => Err(Error::<T>::OffChainAssetCantBeLocked.into()),
}
}
Expand Down
88 changes: 43 additions & 45 deletions pallets/sto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ use polymesh_primitives::asset::AssetId;
use polymesh_primitives::impl_checked_inc;
use polymesh_primitives::settlement::{Leg, ReceiptDetails, SettlementType, VenueId, VenueType};
use polymesh_primitives::{
storage_migration_ver, traits::PortfolioSubTrait, with_transaction, Balance, EventDid,
IdentityId, PortfolioId, WeightMeter,
storage_migration_ver, traits::PortfolioSubTrait, Balance, EventDid, IdentityId, PortfolioId,
WeightMeter,
};
use polymesh_primitives_derive::VecU8StrongTyped;

Expand Down Expand Up @@ -559,49 +559,47 @@ pub mod pallet {
},
];

with_transaction(|| {
<Portfolio<T>>::unlock_tokens(
&fundraiser.offering_portfolio,
&fundraiser.offering_asset,
purchase_amount,
)?;

let instruction_id = Settlement::<T>::base_add_instruction(
fundraiser.creator,
Some(fundraiser.venue_id),
SettlementType::SettleOnAffirmation,
None,
None,
legs,
None,
None,
)?;

let portfolios = [fundraiser.offering_portfolio, fundraiser.raising_portfolio]
.iter()
.copied()
.collect::<BTreeSet<_>>();
Settlement::<T>::unsafe_affirm_instruction(
fundraiser.creator,
instruction_id,
portfolios,
None,
None,
)?;

let portfolios = [investment_portfolio, funding_portfolio]
.iter()
.copied()
.collect::<BTreeSet<_>>();
Settlement::<T>::affirm_and_execute_instruction(
origin,
instruction_id,
receipt,
portfolios,
did,
&mut WeightMeter::max_limit_no_minimum(),
)
})?;
<Portfolio<T>>::unlock_tokens(
&fundraiser.offering_portfolio,
&fundraiser.offering_asset,
purchase_amount,
)?;

let instruction_id = Settlement::<T>::base_add_instruction(
fundraiser.creator,
Some(fundraiser.venue_id),
SettlementType::SettleOnAffirmation,
None,
None,
legs,
None,
None,
)?;

let portfolios = [fundraiser.offering_portfolio, fundraiser.raising_portfolio]
.iter()
.copied()
.collect::<BTreeSet<_>>();
Settlement::<T>::unsafe_affirm_instruction(
fundraiser.creator,
instruction_id,
portfolios,
None,
None,
)?;

let portfolios = [investment_portfolio, funding_portfolio]
.iter()
.copied()
.collect::<BTreeSet<_>>();
Settlement::<T>::affirm_and_execute_instruction(
origin,
instruction_id,
receipt,
portfolios,
did,
&mut WeightMeter::max_limit_no_minimum(),
)?;

for (id, amount) in purchases {
fundraiser.tiers[id].remaining -= amount;
Expand Down

0 comments on commit 90087f5

Please sign in to comment.