A variational approach to the financial problem with insolvencies and analysis of the contagion