@@ -245,20 +245,26 @@ impl SharpyContract {
245245 payer. require_auth ( ) ;
246246 assert ! ( !payments. is_empty( ) , "payments must not be empty" ) ;
247247
248- let mut total: i128 = 0 ;
248+ // Phase 1: Validate all invoices and group totals by token
249+ let mut token_totals: Map < Address , i128 > = Map :: new ( & env) ;
249250 for p in payments. iter ( ) {
250251 let inv = load_invoice ( & env, p. invoice_id ) ;
251252 assert ! ( inv. status == InvoiceStatus :: Pending , "invoice is not pending" ) ;
252253 assert ! ( p. amount > 0 , "payment amount must be positive" ) ;
253254 let inv_total: i128 = inv. amounts . iter ( ) . sum ( ) ;
254255 assert ! ( inv. funded + p. amount <= inv_total, "payment exceeds remaining balance" ) ;
255- total += p. amount ;
256+ let token = inv. tokens . get ( 0 ) . expect ( "no token" ) ;
257+ let prev = token_totals. get ( token. clone ( ) ) . unwrap_or ( 0 ) ;
258+ token_totals. set ( token, prev + p. amount ) ;
256259 }
257260
258- let first = load_invoice ( & env, payments. get ( 0 ) . unwrap ( ) . invoice_id ) ;
259- let token_client = token:: Client :: new ( & env, & first. tokens . get ( 0 ) . expect ( "no token" ) ) ;
260- token_client. transfer ( & payer, & env. current_contract_address ( ) , & total) ;
261+ // Phase 2: Transfer tokens — one transfer per unique token
262+ for ( token, amount) in token_totals. iter ( ) {
263+ let token_client = token:: Client :: new ( & env, & token) ;
264+ token_client. transfer ( & payer, & env. current_contract_address ( ) , & amount) ;
265+ }
261266
267+ // Phase 3: Update each invoice's state
262268 for p in payments. iter ( ) {
263269 let mut inv = load_invoice ( & env, p. invoice_id ) ;
264270 inv. payments . push_back ( Payment { payer : payer. clone ( ) , amount : p. amount , tip : 0 } ) ;
0 commit comments