11from asyncio import CancelledError
22from dataclasses import dataclass
3- from typing import Callable , Dict , Optional , Set , TYPE_CHECKING
3+ from decimal import Decimal
4+ from typing import Awaitable , Callable , Dict , Optional , Set , TYPE_CHECKING
45import sys
56
67from yapapi import events
@@ -20,6 +21,11 @@ class AgreementData:
2021 paid : bool = False
2122
2223
24+ import logging
25+
26+ logger = logging .getLogger (__name__ )
27+
28+
2329class InvoiceManager :
2430 def __init__ (self ):
2531 self ._agreement_data : Dict [str , AgreementData ] = {}
@@ -71,7 +77,10 @@ def set_payable(self, agreement_id: str) -> None:
7177 self ._agreement_data [agreement_id ].payable = True
7278
7379 async def attempt_payment (
74- self , agreement_id : str , get_allocation : Callable [["Invoice" ], "Allocation" ]
80+ self ,
81+ agreement_id : str ,
82+ get_allocation : Callable [["Invoice" ], "Allocation" ],
83+ get_accepted_amount : Callable [["Invoice" ], Awaitable [Decimal ]],
7584 ) -> bool :
7685 ad = self ._agreement_data .get (agreement_id )
7786 if not ad or not ad .invoice or not ad .payable or ad .paid :
@@ -80,12 +89,23 @@ async def attempt_payment(
8089 invoice = ad .invoice
8190 try :
8291 allocation = get_allocation (invoice )
83- await invoice .accept (amount = invoice .amount , allocation = allocation )
84- ad .job .emit (
85- events .InvoiceAccepted ,
86- agreement = ad .agreement ,
87- invoice = invoice ,
88- )
92+ accepted_amount = await get_accepted_amount (invoice )
93+ if accepted_amount >= Decimal (invoice .amount ):
94+ await invoice .accept (amount = accepted_amount , allocation = allocation )
95+ ad .job .emit (
96+ events .InvoiceAccepted ,
97+ agreement = ad .agreement ,
98+ invoice = invoice ,
99+ )
100+ else :
101+ # We should reject the invoice, but it's not implemented in yagna,
102+ # so we just ignore it now
103+ logger .warning (
104+ "Ignored invoice %s for %s, we accept only %s" ,
105+ invoice .invoice_id ,
106+ invoice .amount ,
107+ accepted_amount ,
108+ )
89109 except CancelledError :
90110 raise
91111 except Exception :
0 commit comments