Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: request_swap_deposit_address_with_affiliates refund address is consistent with destination address type #5360

Merged
merged 9 commits into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 8 additions & 21 deletions api/lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ use cf_chains::{
dot::PolkadotAccountId,
evm::to_evm_address,
sol::SolAddress,
CcmChannelMetadata, ChannelRefundParametersGeneric, ForeignChain, ForeignChainAddress,
CcmChannelMetadata, ChannelRefundParametersEncoded, ChannelRefundParametersGeneric,
ForeignChain, ForeignChainAddress,
};
pub use cf_primitives::{AccountRole, Affiliates, Asset, BasisPoints, ChannelId, SemVer};
use cf_primitives::{AssetAmount, BlockNumber, DcaParameters, NetworkEnvironment, Price};
use cf_primitives::{AssetAmount, BlockNumber, DcaParameters, NetworkEnvironment};
use pallet_cf_account_roles::MAX_LENGTH_FOR_VANITY_NAME;
use pallet_cf_governance::ExecutionMode;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -340,12 +341,7 @@ impl fmt::Display for AddressString {
}
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RefundParameters {
pub retry_duration: BlockNumber,
pub refund_address: AddressString,
pub min_price: Price,
}
pub type RefundParameters = ChannelRefundParametersGeneric<AddressString>;

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SwapDepositAddress {
Expand All @@ -354,7 +350,7 @@ pub struct SwapDepositAddress {
pub channel_id: ChannelId,
pub source_chain_expiry_block: NumberOrHex,
pub channel_opening_fee: U256,
pub refund_parameters: Option<ChannelRefundParametersGeneric<AddressString>>,
pub refund_parameters: Option<RefundParameters>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
Expand Down Expand Up @@ -403,12 +399,6 @@ pub trait BrokerApi: SignedExtrinsicApi + StorageApi + Sized + Send + Sync + 'st
) -> Result<SwapDepositAddress> {
let destination_address =
destination_address.try_parse_to_encoded_address(destination_asset.into())?;
let block_hash = self.base_rpc_api().latest_finalized_block_hash().await?;
let network: NetworkEnvironment = self
.storage_value::<pallet_cf_environment::ChainflipNetworkEnvironment<state_chain_runtime::Runtime>>(
block_hash,
)
.await?;
let (_tx_hash, events, header, ..) = self
.submit_signed_extrinsic_with_dry_run(
pallet_cf_swapping::Call::request_swap_deposit_address_with_affiliates {
Expand All @@ -420,15 +410,12 @@ pub trait BrokerApi: SignedExtrinsicApi + StorageApi + Sized + Send + Sync + 'st
boost_fee: boost_fee.unwrap_or_default(),
affiliate_fees: affiliate_fees.unwrap_or_default(),
refund_parameters: refund_parameters
.map(|rpc_params| {
Ok::<_, anyhow::Error>(ChannelRefundParametersGeneric {
.map(|rpc_params: ChannelRefundParametersGeneric<AddressString>| {
Ok::<_, anyhow::Error>(ChannelRefundParametersEncoded {
retry_duration: rpc_params.retry_duration,
refund_address: rpc_params
.refund_address
.try_parse_to_foreign_chain_address(
source_asset.into(),
network,
)?,
.try_parse_to_encoded_address(source_asset.into())?,
min_price: rpc_params.min_price,
})
})
Expand Down
2 changes: 1 addition & 1 deletion bouncer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"prettier:write": "prettier --write ."
},
"dependencies": {
"@chainflip/cli": "1.8.0-cf-parameters-rename.5",
"@chainflip/cli": "1.8.0-rc.1",
"@chainflip/utils": "^0.4.0",
"@coral-xyz/anchor": "^0.30.1",
"@iarna/toml": "^2.2.5",
Expand Down
10 changes: 5 additions & 5 deletions bouncer/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ const requestSwapDepositAddress = async (
const eventMatcher = chainflip.events.swapping.SwapDepositAddressReady;

const unsubscribe = await chainflip.tx.swapping
.requestSwapDepositAddressWithAffiliates(...broker.buildExtrinsicPayload(params, 'backspin'))
.requestSwapDepositAddressWithAffiliates(...broker.buildExtrinsicPayload(params))
.signAndSend(account, { nonce: getNonce() }, (result) => {
if (!result.isInBlock) return;

Expand Down
10 changes: 10 additions & 0 deletions state-chain/chains/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -827,6 +827,16 @@ impl<A: Clone> ChannelRefundParametersGeneric<A> {
min_price: self.min_price,
}
}
pub fn try_map_address<B, F: FnOnce(A) -> Result<B, sp_runtime::DispatchError>>(
&self,
f: F,
) -> Result<ChannelRefundParametersGeneric<B>, sp_runtime::DispatchError> {
Ok(ChannelRefundParametersGeneric {
retry_duration: self.retry_duration,
refund_address: f(self.refund_address.clone())?,
min_price: self.min_price,
})
}
}

pub enum RequiresSignatureRefresh<C: ChainCrypto, Api: ApiCall<C>> {
Expand Down
22 changes: 17 additions & 5 deletions state-chain/pallets/cf-swapping/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -683,6 +683,8 @@ pub mod pallet {
SwapRequestDurationTooLong,
/// Invalid DCA parameters.
InvalidDcaParameters,
/// The provided Refund address cannot be decoded into ForeignChainAddress.
InvalidRefundAddress,
}

#[pallet::genesis_config]
Expand Down Expand Up @@ -953,7 +955,7 @@ pub mod pallet {
/// ## Events
///
/// - [SwapDepositAddressReady](Event::SwapDepositAddressReady)
#[pallet::call_index(10)]
#[pallet::call_index(11)]
#[pallet::weight(T::WeightInfo::request_swap_deposit_address_with_affiliates())]
pub fn request_swap_deposit_address_with_affiliates(
origin: OriginFor<T>,
Expand All @@ -964,7 +966,7 @@ pub mod pallet {
channel_metadata: Option<CcmChannelMetadata>,
boost_fee: BasisPoints,
affiliate_fees: Affiliates<T::AccountId>,
refund_parameters: Option<ChannelRefundParameters>,
refund_parameters: Option<ChannelRefundParametersEncoded>,
dca_parameters: Option<DcaParameters>,
) -> DispatchResult {
let broker = T::AccountRoleRegistry::ensure_broker(origin)?;
Expand Down Expand Up @@ -994,6 +996,17 @@ pub mod pallet {
)
.map_err(address_error_to_pallet_error::<T>)?;

// Convert the refund parameter from `EncodedAddress` into `ForeignChainAddress` type.
let refund_params_internal = refund_parameters
.clone()
.map(|params| {
params.try_map_address(|addr| {
T::AddressConverter::try_from_encoded_address(addr)
.map_err(|_| Error::<T>::InvalidRefundAddress.into())
})
})
.transpose()?;

if let Some(ccm) = channel_metadata.as_ref() {
let destination_chain: ForeignChain = destination_asset.into();
ensure!(destination_chain.ccm_support(), Error::<T>::CcmUnsupportedForTargetChain);
Expand All @@ -1019,7 +1032,7 @@ pub mod pallet {
broker,
channel_metadata.clone(),
boost_fee,
refund_parameters.clone(),
refund_params_internal,
dca_parameters.clone(),
)?;

Expand All @@ -1035,8 +1048,7 @@ pub mod pallet {
boost_fee,
channel_opening_fee,
affiliate_fees,
refund_parameters: refund_parameters
.map(|params| params.map_address(T::AddressConverter::to_encoded_address)),
refund_parameters,
dca_parameters,
});

Expand Down
6 changes: 3 additions & 3 deletions state-chain/pallets/cf-swapping/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1021,9 +1021,9 @@ fn swaps_get_retried_after_failure() {
#[test]
fn deposit_address_ready_event_contains_correct_parameters() {
new_test_ext().execute_with(|| {
let refund_parameters = ChannelRefundParameters {
let refund_parameters = ChannelRefundParametersEncoded {
retry_duration: 10,
refund_address: ForeignChainAddress::Eth([10; 20].into()),
refund_address: EncodedAddress::Eth([10; 20]),
min_price: 100.into(),
};

Expand All @@ -1049,7 +1049,7 @@ fn deposit_address_ready_event_contains_correct_parameters() {
refund_parameters: Some(ref refund_params_in_event),
dca_parameters: Some(ref dca_params_in_event),
..
}) if refund_params_in_event == &refund_parameters.map_address(MockAddressConverter::to_encoded_address) && dca_params_in_event == &dca_parameters
}) if *refund_params_in_event == refund_parameters && dca_params_in_event == &dca_parameters
);
});
}
Expand Down
Loading