diff --git a/fee-market/src/subtract_fee.rs b/fee-market/src/subtract_fee.rs index 9823c6f5..e559a0e2 100644 --- a/fee-market/src/subtract_fee.rs +++ b/fee-market/src/subtract_fee.rs @@ -5,12 +5,20 @@ use crate::fee_type::FeeType; multiversx_sc::imports!(); multiversx_sc::derive_imports!(); +const TOTAL_PERCENTAGE: usize = 10_000; + #[derive(TypeAbi, TopEncode, TopDecode)] pub struct FinalPayment { pub fee: EsdtTokenPayment, pub remaining_tokens: EsdtTokenPayment, } +#[derive(TopEncode, TopDecode, ManagedVecItem)] +pub struct AddressPercentagePair { + pub address: ManagedAddress, + pub percentage: usize, +} + pub struct SubtractPaymentArguments { pub fee_token: TokenIdentifier, pub per_transfer: BigUint, @@ -42,11 +50,52 @@ pub trait SubtractFeeModule: /// Percentages have to be between 0 and 10_000, and must all add up to 100% (i.e. 10_000) #[only_owner] + #[endpoint(distributeFees)] fn distribute_fees( &self, - _user_percentage_pairs: MultiValueEncoded>, + address_percentage_pairs: MultiValueEncoded>, ) { - todo!(); + let percentage_total = BigUint::from(TOTAL_PERCENTAGE); + + let mut percentage_sum = 0u64; + let mut pairs = ManagedVec::>::new(); + for pair in address_percentage_pairs { + let (address, percentage) = pair.into_tuple(); + pairs.push(AddressPercentagePair { + address, + percentage, + }); + percentage_sum += percentage as u64; + } + require!( + percentage_sum == TOTAL_PERCENTAGE as u64, + "Invalid percentage sum" + ); + + for token_id in self.tokens_for_fees().iter() { + let accumulated_fees = self.accumulated_fees(&token_id).get(); + if accumulated_fees == 0u32 { + continue; + } + + let mut remaining_fees = accumulated_fees.clone(); + + for pair in &pairs { + let amount_to_send = + &(&accumulated_fees * &BigUint::from(pair.percentage)) / &percentage_total; + + if amount_to_send > 0 { + remaining_fees -= &amount_to_send; + + self.send() + .direct_esdt(&pair.address, &token_id, 0, &amount_to_send); + } + } + + self.accumulated_fees(&token_id).set(&remaining_fees); + } + + self.tokens_for_fees().clear(); } #[payable("*")] diff --git a/fee-market/wasm/src/lib.rs b/fee-market/wasm/src/lib.rs index ca18a9da..1e8f6caa 100644 --- a/fee-market/wasm/src/lib.rs +++ b/fee-market/wasm/src/lib.rs @@ -5,9 +5,9 @@ //////////////////////////////////////////////////// // Init: 1 -// Endpoints: 12 +// Endpoints: 13 // Async Callback (empty): 1 -// Total number of exported functions: 14 +// Total number of exported functions: 15 #![no_std] #![allow(internal_features)] @@ -28,6 +28,7 @@ multiversx_sc_wasm_adapter::endpoints! { getTokenFee => token_fee addUsersToWhitelist => add_users_to_whitelist removeUsersFromWhitelist => remove_users_from_whitelist + distributeFees => distribute_fees subtractFee => subtract_fee getUsersWhitelist => users_whitelist addPairs => add_pairs