code: def clear_if_finalized(
          iteration: TransitionResult,
          channelidentifiers_to_channels: ChannelMap,
  ) -> TransitionResult[MediatorTransferState]:
      
      state = cast(MediatorTransferState, iteration.new_state)
  
      if state is None:
          return iteration
  
      # Only clear the task if all channels have the lock cleared.
      secrethash = state.secrethash
      for pair in state.transfers_pair:
          payer_channel = get_payer_channel(channelidentifiers_to_channels, pair)
          if payer_channel and channel.is_lock_pending(payer_channel.partner_state, secrethash):
              return iteration
  
          payee_channel = get_payee_channel(channelidentifiers_to_channels, pair)
          if payee_channel and channel.is_lock_pending(payee_channel.our_state, secrethash):
              return iteration
  
      if state.waiting_transfer:
          waiting_transfer = state.waiting_transfer.transfer
          waiting_channel_identifier = waiting_transfer.balance_proof.channel_identifier
          waiting_channel = channelidentifiers_to_channels.get(waiting_channel_identifier)
  
          if waiting_channel and channel.is_lock_pending(waiting_channel.partner_state, secrethash):
              return iteration
  
      return TransitionResult(None, iteration.events)
docs: Clear the mediator task if all the locks have been finalized.
  
      A lock is considered finalized if it has been removed from the merkle tree
      offchain, either because the transfer was unlocked or expired, or because the
      channel was settled on chain and therefore the channel is removed.