Skip to content

Commit

Permalink
chore: merge from main
Browse files Browse the repository at this point in the history
  • Loading branch information
albert-llimos committed Jan 17, 2025
2 parents 66b7258 + 13433b5 commit 600fa90
Show file tree
Hide file tree
Showing 29 changed files with 290 additions and 184 deletions.
4 changes: 0 additions & 4 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,3 @@ Please conduct a thorough self-review before opening the PR.
## Summary

*Please include a succinct description of the purpose and content of the PR. What problem does it solve, and how? Link issues, discussions, other PRs, and anything else that will help the reviewer.*

#### Non-Breaking changes

If this PR includes non-breaking changes, select the `non-breaking` label. On merge, CI will automatically cherry-pick the commit to a PR against the release branch.
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ enum WitnessInformation {
destination_address: TrackerAddress,
ccm_deposit_metadata: Option<CcmDepositMetadata>,
deposit_details: Option<DepositDetails>,
broker_fee: Beneficiary<AccountId32>,
broker_fee: Option<Beneficiary<AccountId32>>,
affiliate_fees: Affiliates<AccountId32>,
refund_params: Option<ChannelRefundParameters<TrackerAddress>>,
dca_params: Option<DcaParameters>,
Expand Down Expand Up @@ -278,9 +278,9 @@ where
Beneficiary { account: affiliate_mapping.get(&affiliate.account).cloned()
.unwrap_or_else(|| {
log::warn!(
"Affiliate not found for short id {} on broker `{}`",
"Affiliate not found for short id {} on broker `{:?}`",
affiliate.account,
self.broker_fee.account,
self.broker_fee.as_ref().map(|Beneficiary { account, .. }| account),
);
AccountId32::from([0; 32])
}), bps: affiliate.bps }
Expand Down Expand Up @@ -400,9 +400,15 @@ where
<T::TargetChain as Chain>::DepositDetails: IntoDepositDetailsAnyChain,
StateChainClient: CfGetAffiliates + 'static + Send + Sync,
{
let affiliate_mapping = state_chain_client
.cf_get_affiliates(&deposit_witness.broker_fee.account)
.await?;
let affiliate_mapping = if let Some(broker_id) = deposit_witness
.broker_fee
.as_ref()
.map(|Beneficiary { account, .. }| account.clone())
{
state_chain_client.cf_get_affiliates(&broker_id).await?
} else {
Default::default()
};

let _ = deposit_witness
.into_witness_information(block_height, &affiliate_mapping, network)
Expand Down Expand Up @@ -919,7 +925,7 @@ mod tests {
)),
}),
deposit_details: Default::default(),
broker_fee: Beneficiary { account: AccountId32::new([0; 32]), bps: 10 },
broker_fee: Some(Beneficiary { account: AccountId32::new([0; 32]), bps: 10 }),
affiliate_fees: frame_support::BoundedVec::try_from(vec![Beneficiary {
account: affiliate_short_id,
bps: 10
Expand Down
19 changes: 12 additions & 7 deletions bouncer/shared/swapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
chainFromAsset,
getContractAddress,
ccmSupportedChains,
solCcmAdditionalDataCodec,
solVersionedCcmAdditionalDataCodec,
} from '../shared/utils';
import { BtcAddressType } from '../shared/new_btc_address';
import { CcmDepositMetadata } from '../shared/new_swap';
Expand All @@ -22,11 +22,11 @@ export function newSolanaCcmAdditionalData(maxAccounts: number) {

const fallbackAddress = Keypair.generate().publicKey.toBytes();

const remainingAccounts = [];
const numRemainingAccounts = Math.floor(Math.random() * maxAccounts);
const additionalAccounts = [];
const numAdditionalAccounts = Math.floor(Math.random() * maxAccounts);

for (let i = 0; i < numRemainingAccounts; i++) {
remainingAccounts.push({
for (let i = 0; i < numAdditionalAccounts; i++) {
additionalAccounts.push({
pubkey: Keypair.generate().publicKey.toBytes(),
is_writable: Math.random() < 0.5,
});
Expand All @@ -37,11 +37,16 @@ export function newSolanaCcmAdditionalData(maxAccounts: number) {
pubkey: new PublicKey(cfReceiverAddress).toBytes(),
is_writable: false,
},
remaining_accounts: remainingAccounts,
additional_accounts: additionalAccounts,
fallback_address: fallbackAddress,
};

return u8aToHex(solCcmAdditionalDataCodec.enc(ccmAdditionalData));
return u8aToHex(
solVersionedCcmAdditionalDataCodec.enc({
tag: 'V0',
value: ccmAdditionalData,
}),
);
}

// Generate random bytes. Setting a minimum length of 10 because very short messages can end up
Expand Down
33 changes: 18 additions & 15 deletions bouncer/shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
import Web3 from 'web3';
import { Connection, Keypair, PublicKey } from '@solana/web3.js';
import { hexToU8a, u8aToHex, BN } from '@polkadot/util';
import { Vector, bool, Struct, Bytes as TsBytes } from 'scale-ts';
import { Vector, bool, Struct, Enum, Bytes as TsBytes } from 'scale-ts';
import BigNumber from 'bignumber.js';
import { EventParser, BorshCoder } from '@coral-xyz/anchor';
import { ISubmittableResult } from '@polkadot/types/types';
Expand Down Expand Up @@ -63,12 +63,12 @@ const isSDKChain = (chain: Chain): chain is SDKChain => chain in chainConstants;

export const solanaNumberOfNonces = 10;

export const solCcmAdditionalDataCodec = Struct({
const solCcmAccountsCodec = Struct({
cf_receiver: Struct({
pubkey: TsBytes(32),
is_writable: bool,
}),
remaining_accounts: Vector(
additional_accounts: Vector(
Struct({
pubkey: TsBytes(32),
is_writable: bool,
Expand All @@ -77,6 +77,10 @@ export const solCcmAdditionalDataCodec = Struct({
fallback_address: TsBytes(32),
});

export const solVersionedCcmAdditionalDataCodec = Enum({
V0: solCcmAccountsCodec,
});

export function getContractAddress(chain: Chain, contract: string): string {
switch (chain) {
case 'Ethereum':
Expand Down Expand Up @@ -809,40 +813,39 @@ export async function observeSolanaCcmEvent(

// The message is being used as the main discriminator
if (matchEventName && matchSourceChain && matchMessage) {
const { remaining_accounts: expectedRemainingAccounts } = solCcmAdditionalDataCodec.dec(
messageMetadata.ccmAdditionalData!,
);
const { additional_accounts: expectedAdditionalAccounts } =
solVersionedCcmAdditionalDataCodec.dec(messageMetadata.ccmAdditionalData!).value;

if (
expectedRemainingAccounts.length !== event.data.remaining_is_writable.length ||
expectedRemainingAccounts.length !== event.data.remaining_pubkeys.length
expectedAdditionalAccounts.length !== event.data.remaining_is_writable.length ||
expectedAdditionalAccounts.length !== event.data.remaining_pubkeys.length
) {
throw new Error(
`Unexpected remaining accounts length: ${expectedRemainingAccounts.length}, expecting ${event.data.remaining_is_writable.length}, ${event.data.remaining_pubkeys.length}`,
`Unexpected additional accounts length: ${expectedAdditionalAccounts.length}, expecting ${event.data.remaining_is_writable.length}, ${event.data.remaining_pubkeys.length}`,
);
}

for (let index = 0; index < expectedRemainingAccounts.length; index++) {
for (let index = 0; index < expectedAdditionalAccounts.length; index++) {
if (
expectedRemainingAccounts[index].is_writable.toString() !==
expectedAdditionalAccounts[index].is_writable.toString() !==
event.data.remaining_is_writable[index].toString()
) {
throw new Error(
`Unexpected remaining account is_writable: ${event.data.remaining_is_writable[index]}, expecting ${expectedRemainingAccounts[index].is_writable}`,
`Unexpected additional account is_writable: ${event.data.remaining_is_writable[index]}, expecting ${expectedAdditionalAccounts[index].is_writable}`,
);
}
const expectedPubkey = new PublicKey(
expectedRemainingAccounts[index].pubkey,
expectedAdditionalAccounts[index].pubkey,
).toString();
if (expectedPubkey !== event.data.remaining_pubkeys[index].toString()) {
throw new Error(
`Unexpected remaining account pubkey: ${event.data.remaining_pubkeys[index].toString()}, expecting ${expectedPubkey}`,
`Unexpected additional account pubkey: ${event.data.remaining_pubkeys[index].toString()}, expecting ${expectedPubkey}`,
);
}
}

if (event.data.remaining_is_signer.some((value: boolean) => value === true)) {
throw new Error(`Expected all remaining accounts to be read-only`);
throw new Error(`Expected all additional accounts to be read-only`);
}

if (sourceAddress !== null) {
Expand Down
8 changes: 4 additions & 4 deletions engine/src/witness/btc/vault_swaps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,10 @@ pub fn try_extract_vault_swap_witness(
deposit_address: vault_address.clone(),
},
deposit_metadata: None, // No ccm for BTC (yet?)
broker_fee: Beneficiary {
broker_fee: Some(Beneficiary {
account: broker_id.clone(),
bps: data.parameters.broker_fee.into(),
},
}),
affiliate_fees: data
.parameters
.affiliates
Expand Down Expand Up @@ -320,10 +320,10 @@ mod tests {
amount: DEPOSIT_AMOUNT,
deposit_address: vault_deposit_address.clone(),
},
broker_fee: Beneficiary {
broker_fee: Some(Beneficiary {
account: BROKER,
bps: MOCK_SWAP_PARAMS.parameters.broker_fee.into()
},
}),
affiliate_fees: bounded_vec![MOCK_SWAP_PARAMS.parameters.affiliates[0].into()],
deposit_metadata: None,
refund_params: Some(ChannelRefundParametersDecoded {
Expand Down
6 changes: 1 addition & 5 deletions engine/src/witness/evm/vault.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,6 @@ macro_rules! vault_deposit_witness {
deposit_address: None,
}
} else {
use cf_primitives::Beneficiary;
VaultDepositWitness {
input_asset: $source_asset.try_into().expect("invalid asset for chain"),
output_asset: $dest_asset,
Expand All @@ -263,10 +262,7 @@ macro_rules! vault_deposit_witness {
deposit_metadata: $metadata,
tx_id: $tx_id,
deposit_details: DepositDetails { tx_hashes: Some(vec![$tx_id]) },
broker_fee: Beneficiary {
account: sp_runtime::AccountId32::new([0; 32]),
bps: 0,
},
broker_fee: None,
affiliate_fees: Default::default(),
boost_fee: 0,
dca_params: None,
Expand Down
19 changes: 8 additions & 11 deletions state-chain/cf-integration-tests/src/solana.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use super::*;
use cf_chains::{
address::{AddressConverter, AddressDerivationApi, EncodedAddress},
assets::{any::Asset, sol::Asset as SolAsset},
ccm_checker::CcmValidityError,
ccm_checker::{CcmValidityError, VersionedSolanaCcmAdditionalData},
sol::{
api::{SolanaApi, SolanaEnvironment, SolanaTransactionBuildingError},
sol_tx_core::sol_test_values,
Expand Down Expand Up @@ -378,10 +378,7 @@ fn vault_swap_deposit_witness(
deposit_metadata,
tx_id: Default::default(),
deposit_details: (),
broker_fee: cf_primitives::Beneficiary {
account: sp_runtime::AccountId32::new([0; 32]),
bps: 0,
},
broker_fee: None,
affiliate_fees: Default::default(),
refund_params: Some(REFUND_PARAMS),
dca_params: None,
Expand Down Expand Up @@ -490,14 +487,14 @@ fn solana_ccm_fails_with_invalid_input() {
channel_metadata: CcmChannelMetadata {
message: vec![0u8, 1u8, 2u8, 3u8].try_into().unwrap(),
gas_budget: 0u128,
ccm_additional_data: SolCcmAccounts {
ccm_additional_data: VersionedSolanaCcmAdditionalData::V0(SolCcmAccounts {
cf_receiver: SolCcmAddress { pubkey: receiver.into(), is_writable: true },
remaining_accounts: vec![
additional_accounts: vec![
SolCcmAddress { pubkey: SolPubkey([0x01; 32]), is_writable: false },
SolCcmAddress { pubkey: SolPubkey([0x02; 32]), is_writable: false },
],
fallback_address: FALLBACK_ADDRESS.into(),
}
})
.encode()
.try_into()
.unwrap(),
Expand Down Expand Up @@ -706,14 +703,14 @@ fn solana_ccm_execution_error_can_trigger_fallback() {
channel_metadata: CcmChannelMetadata {
message: vec![0u8, 1u8, 2u8, 3u8].try_into().unwrap(),
gas_budget: 1_000_000_000u128,
ccm_additional_data: SolCcmAccounts {
ccm_additional_data: VersionedSolanaCcmAdditionalData::V0(SolCcmAccounts {
cf_receiver: SolCcmAddress { pubkey: SolPubkey([0x10; 32]), is_writable: true },
remaining_accounts: vec![
additional_accounts: vec![
SolCcmAddress { pubkey: SolPubkey([0x01; 32]), is_writable: false },
SolCcmAddress { pubkey: SolPubkey([0x02; 32]), is_writable: false },
],
fallback_address: FALLBACK_ADDRESS.into(),
}
})
.encode()
.try_into()
.unwrap(),
Expand Down
5 changes: 1 addition & 4 deletions state-chain/cf-integration-tests/src/swapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -530,10 +530,7 @@ fn vault_swap_deposit_witness(
deposit_metadata: Some(ccm_deposit_metadata_mock()),
tx_id: Default::default(),
deposit_details: DepositDetails { tx_hashes: None },
broker_fee: cf_primitives::Beneficiary {
account: sp_runtime::AccountId32::new([0; 32]),
bps: 0,
},
broker_fee: None,
affiliate_fees: Default::default(),
refund_params: Some(ETH_REFUND_PARAMS),
dca_params: None,
Expand Down
Loading

0 comments on commit 600fa90

Please sign in to comment.