-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeFiProtocolInterface.py
More file actions
301 lines (250 loc) · 8.65 KB
/
DeFiProtocolInterface.py
File metadata and controls
301 lines (250 loc) · 8.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
"""
DeFiProtocolInterface.py
========================
Abstract Base Class that defines the EXACT contract all agents must use
to interact with the DeFi protocol.
This is the "Adapter Interface" in the Adapter Pattern. The real smart-contract
implementation and the MockDeFiProtocol both inherit from this class, so agents
are completely decoupled from the underlying blockchain state.
No agent should ever import MockDeFiProtocol directly.
"""
from abc import ABC, abstractmethod
from typing import Dict, List
class DeFiProtocolInterface(ABC):
"""
Abstract interface for a simplified DeFi protocol that combines:
- An Automated Market Maker (AMM) for token swaps
- A lending/borrowing module with health factors
All methods are pure interface definitions — no implementation here.
"""
# ------------------------------------------------------------------ #
# READ-ONLY STATE QUERIES #
# ------------------------------------------------------------------ #
@abstractmethod
def get_token_price(self) -> float:
"""
Returns the current AMM-derived price of ETH in USDC.
Formula (constant-product AMM):
price = reserve_usdc / reserve_eth
Returns:
float: Price of 1 ETH in USDC units.
"""
...
@abstractmethod
def get_oracle_price(self) -> float:
"""
Returns the current external oracle price of ETH in USDC.
This is independent of the AMM reserves — it represents the
'true' market price from an off-chain data source.
Returns:
float: Oracle price of 1 ETH in USDC units.
"""
...
@abstractmethod
def get_pool_liquidity(self) -> Dict[str, float]:
"""
Returns the current state of the AMM liquidity pool.
Returns:
dict: {
"reserve_usdc": float, # USDC held in the pool
"reserve_eth": float, # ETH held in the pool
"k": float, # constant product invariant
}
"""
...
@abstractmethod
def get_user_health_factor(self, address: str) -> float:
"""
Returns the collateralisation health factor for a borrower.
health_factor = (collateral_value_usdc * LTV_ratio) / total_debt_usdc
A health factor < 1.0 means the position is under-collateralised
and eligible for liquidation.
Args:
address (str): The borrower's unique address string.
Returns:
float: Health factor (> 1.0 = safe, < 1.0 = liquidatable).
Returns float('inf') if address has no debt.
"""
...
@abstractmethod
def has_bad_debt(self) -> bool:
"""
Returns True if any borrower position in the protocol has accrued bad debt.
Bad debt is defined as: (collateral_eth * oracle_price) < debt_usdc.
"""
...
@abstractmethod
def get_all_borrower_addresses(self) -> List[str]:
"""
Returns the list of all known borrower addresses in the protocol.
The Liquidator agent uses this to scan for unhealthy positions.
Returns:
List[str]: List of borrower address strings.
"""
...
# ------------------------------------------------------------------ #
# STATE-CHANGING ACTIONS #
# ------------------------------------------------------------------ #
@abstractmethod
def execute_swap(
self,
token_in: str,
amount_in: float,
caller_address: str,
) -> Dict[str, float]:
"""
Executes a token swap through the AMM.
Uses constant-product formula: (x + Δx)(y - Δy) = k
so Δy = (y * Δx) / (x + Δx)
Args:
token_in (str): "USDC" or "ETH" — the token being sold.
amount_in (float): Amount of token_in to sell.
caller_address(str): Address executing the swap (for logging).
Returns:
dict: {
"amount_out": float, # tokens received
"new_price": float, # AMM price after the swap
"price_impact": float, # % price change caused by this swap
}
"""
...
@abstractmethod
def execute_liquidation(
self,
borrower_address: str,
liquidator_address: str,
) -> Dict[str, float]:
"""
Liquidates an under-collateralised borrower position.
The liquidator repays the borrower's debt in exchange for a
liquidation bonus (usually 5–10% of the collateral).
Args:
borrower_address (str): The address to liquidate.
liquidator_address (str): The address performing the liquidation.
Returns:
dict: {
"debt_repaid": float,
"collateral_seized": float,
"liquidation_bonus": float,
}
"""
...
@abstractmethod
def execute_borrow(
self,
borrower_address: str,
amount_usdc: float,
) -> Dict[str, float]:
"""
Borrows USDC against the caller's existing ETH collateral.
Args:
borrower_address (str): The address taking the loan.
amount_usdc (float): Amount of USDC to borrow.
Returns:
dict: {
"borrowed_amount": float,
"new_health_factor": float, # updated health factor post-borrow
}
"""
...
@abstractmethod
def execute_deposit_collateral(
self,
borrower_address: str,
amount_eth: float,
) -> Dict[str, float]:
"""
Deposits ETH collateral into the protocol.
Args:
borrower_address (str): The address depositing collateral.
amount_eth (float): Amount of ETH to deposit.
Returns:
dict: {
"deposited_amount": float,
"new_health_factor": float,
}
"""
...
@abstractmethod
def execute_withdraw_collateral(
self,
borrower_address: str,
amount_eth: float,
) -> Dict[str, float]:
"""
Withdraws ETH collateral from the protocol, ensuring health factor remains >= 1.0.
Args:
borrower_address (str): The address withdrawing collateral.
amount_eth (float): Amount of ETH to withdraw.
Returns:
dict: {
"withdrawn_amount": float,
"new_health_factor": float,
}
"""
...
@abstractmethod
def execute_repay(
self,
borrower_address: str,
amount_usdc: float,
) -> Dict[str, float]:
"""
Repays USDC debt for a borrower.
Args:
borrower_address (str): The address repaying debt.
amount_usdc (float): Amount of USDC to repay.
Returns:
dict: {
"repaid_amount": float,
"new_health_factor": float,
}
"""
...
@abstractmethod
def execute_supply(
self,
supplier_address: str,
token: str,
amount: float,
) -> Dict[str, float]:
"""
Supplies liquidity to the protocol (adds to reserves).
Args:
supplier_address (str): The address supplying liquidity.
token (str): "USDC" or "ETH".
amount (float): Amount to supply.
Returns:
dict: {
"lp_tokens_minted": float, # LP share tokens received
"new_reserve": float, # updated reserve for that token
}
"""
...
@abstractmethod
def execute_withdraw(
self,
withdrawer_address: str,
fraction: float,
) -> Dict[str, float]:
"""
Withdraws liquidity from the protocol equivalent to the fraction of total pool.
Args:
withdrawer_address (str): The address withdrawing liquidity.
fraction (float): Fraction to withdraw (0.0 to 1.0)
Returns:
dict: {
"usdc_withdrawn": float,
"eth_withdrawn": float,
}
"""
...
@abstractmethod
def advance_oracle_price(self) -> float:
"""
Advances the oracle price by one time step (random walk).
Called once per model step BEFORE agents act.
Returns:
float: New oracle price after the step.
"""
...