-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathmargin_pool.move
More file actions
370 lines (328 loc) · 11.9 KB
/
Copy pathmargin_pool.move
File metadata and controls
370 lines (328 loc) · 11.9 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
module margin_trading::margin_pool;
use deepbook::math;
use margin_trading::{
margin_registry::{MarginRegistry, MaintainerCap, MarginPoolCap},
margin_state::{Self, State},
position_manager::{Self, PositionManager},
protocol_config::{InterestConfig, MarginPoolConfig, ProtocolConfig},
protocol_fees::{Self, ProtocolFees, Referral}
};
use std::type_name::{Self, TypeName};
use sui::{balance::{Self, Balance}, clock::Clock, coin::Coin, event, vec_set::{Self, VecSet}};
// === Errors ===
const ENotEnoughAssetInPool: u64 = 1;
const ESupplyCapExceeded: u64 = 2;
const EMaxPoolBorrowPercentageExceeded: u64 = 4;
const EDeepbookPoolAlreadyAllowed: u64 = 5;
const EDeepbookPoolNotAllowed: u64 = 6;
const EInvalidMarginPoolCap: u64 = 7;
const EBorrowAmountTooLow: u64 = 8;
const EInvalidRepayQuantity: u64 = 9;
// === Structs ===
public struct MarginPool<phantom Asset> has key, store {
id: UID,
vault: Balance<Asset>,
state: State,
config: ProtocolConfig,
protocol_fees: ProtocolFees,
positions: PositionManager,
allowed_deepbook_pools: VecSet<ID>,
}
// === Events ===
public struct MarginPoolCreated has copy, drop {
margin_pool_id: ID,
maintainer_cap_id: ID,
asset_type: TypeName,
config: ProtocolConfig,
timestamp: u64,
}
public struct DeepbookPoolUpdated has copy, drop {
margin_pool_id: ID,
deepbook_pool_id: ID,
pool_cap_id: ID,
enabled: bool,
timestamp: u64,
}
public struct InterestParamsUpdated has copy, drop {
margin_pool_id: ID,
pool_cap_id: ID,
interest_config: InterestConfig,
timestamp: u64,
}
public struct MarginPoolConfigUpdated has copy, drop {
margin_pool_id: ID,
pool_cap_id: ID,
margin_pool_config: MarginPoolConfig,
timestamp: u64,
}
public struct AssetSupplied has copy, drop {
margin_pool_id: ID,
asset_type: TypeName,
supplier: address,
supply_amount: u64,
supply_shares: u64,
timestamp: u64,
}
public struct AssetWithdrawn has copy, drop {
margin_pool_id: ID,
asset_type: TypeName,
supplier: address,
withdraw_amount: u64,
withdraw_shares: u64,
timestamp: u64,
}
// === Public Functions * ADMIN *===
/// Creates and registers a new margin pool. If a same asset pool already exists, abort.
/// Sends a `MarginPoolCap` to the pool creator. Returns the created margin pool id.
public fun create_margin_pool<Asset>(
registry: &mut MarginRegistry,
config: ProtocolConfig,
maintainer_cap: &MaintainerCap,
clock: &Clock,
ctx: &mut TxContext,
): ID {
let id = object::new(ctx);
let margin_pool_id = id.to_inner();
let margin_pool = MarginPool<Asset> {
id,
vault: balance::zero<Asset>(),
state: margin_state::default(clock),
config,
protocol_fees: protocol_fees::default_protocol_fees(ctx, clock),
positions: position_manager::create_position_manager(ctx),
allowed_deepbook_pools: vec_set::empty(),
};
transfer::share_object(margin_pool);
let asset_type = type_name::with_defining_ids<Asset>();
registry.register_margin_pool(asset_type, margin_pool_id, maintainer_cap, ctx);
let maintainer_cap_id = maintainer_cap.maintainer_cap_id();
event::emit(MarginPoolCreated {
margin_pool_id,
maintainer_cap_id,
asset_type,
config,
timestamp: clock.timestamp_ms(),
});
margin_pool_id
}
/// Allow a margin manager tied to a deepbook pool to borrow from the margin pool.
public fun enable_deepbook_pool_for_loan<Asset>(
self: &mut MarginPool<Asset>,
registry: &MarginRegistry,
deepbook_pool_id: ID,
margin_pool_cap: &MarginPoolCap,
clock: &Clock,
) {
registry.load_inner();
assert!(margin_pool_cap.margin_pool_id() == self.id(), EInvalidMarginPoolCap);
assert!(!self.allowed_deepbook_pools.contains(&deepbook_pool_id), EDeepbookPoolAlreadyAllowed);
self.allowed_deepbook_pools.insert(deepbook_pool_id);
event::emit(DeepbookPoolUpdated {
margin_pool_id: self.id(),
pool_cap_id: margin_pool_cap.pool_cap_id(),
deepbook_pool_id,
enabled: true,
timestamp: clock.timestamp_ms(),
});
}
/// Disable a margin manager tied to a deepbook pool from borrowing from the margin pool.
public fun disable_deepbook_pool_for_loan<Asset>(
self: &mut MarginPool<Asset>,
registry: &MarginRegistry,
deepbook_pool_id: ID,
margin_pool_cap: &MarginPoolCap,
clock: &Clock,
) {
registry.load_inner();
assert!(margin_pool_cap.margin_pool_id() == self.id(), EInvalidMarginPoolCap);
assert!(self.allowed_deepbook_pools.contains(&deepbook_pool_id), EDeepbookPoolNotAllowed);
self.allowed_deepbook_pools.remove(&deepbook_pool_id);
event::emit(DeepbookPoolUpdated {
margin_pool_id: self.id(),
pool_cap_id: margin_pool_cap.pool_cap_id(),
deepbook_pool_id,
enabled: false,
timestamp: clock.timestamp_ms(),
});
}
/// Updates interest params for the margin pool
public fun update_interest_params<Asset>(
self: &mut MarginPool<Asset>,
registry: &MarginRegistry,
interest_config: InterestConfig,
margin_pool_cap: &MarginPoolCap,
clock: &Clock,
) {
registry.load_inner();
assert!(margin_pool_cap.margin_pool_id() == self.id(), EInvalidMarginPoolCap);
self.config.set_interest_config(interest_config);
event::emit(InterestParamsUpdated {
margin_pool_id: self.id(),
pool_cap_id: margin_pool_cap.pool_cap_id(),
interest_config,
timestamp: clock.timestamp_ms(),
});
}
/// Updates margin pool config
public fun update_margin_pool_config<Asset>(
self: &mut MarginPool<Asset>,
registry: &MarginRegistry,
margin_pool_config: MarginPoolConfig,
margin_pool_cap: &MarginPoolCap,
clock: &Clock,
) {
registry.load_inner();
assert!(margin_pool_cap.margin_pool_id() == self.id(), EInvalidMarginPoolCap);
self.config.set_margin_pool_config(margin_pool_config);
event::emit(MarginPoolConfigUpdated {
margin_pool_id: self.id(),
pool_cap_id: margin_pool_cap.pool_cap_id(),
margin_pool_config,
timestamp: clock.timestamp_ms(),
});
}
// === Public Functions * LENDING * ===
/// Supply to the margin pool. Returns the new user supply amount.
public fun supply<Asset>(
self: &mut MarginPool<Asset>,
registry: &MarginRegistry,
coin: Coin<Asset>,
referral: Option<address>,
clock: &Clock,
ctx: &TxContext,
): u64 {
registry.load_inner();
let supply_amount = coin.value();
let (supply_shares, protocol_fees) = self
.state
.increase_supply(&self.config, supply_amount, clock);
self.protocol_fees.increase_fees_per_share(self.state.supply_shares(), protocol_fees);
let (total_user_supply, previous_referral) = self
.positions
.increase_user_supply(referral, supply_shares, ctx);
self.protocol_fees.decrease_shares(previous_referral, total_user_supply - supply_shares, clock);
self.protocol_fees.increase_shares(referral, total_user_supply, clock);
let balance = coin.into_balance();
self.vault.join(balance);
assert!(self.state.supply() <= self.config.supply_cap(), ESupplyCapExceeded);
event::emit(AssetSupplied {
margin_pool_id: self.id(),
asset_type: type_name::with_defining_ids<Asset>(),
supplier: ctx.sender(),
supply_amount,
supply_shares,
timestamp: clock.timestamp_ms(),
});
total_user_supply
}
/// Withdraw from the margin pool. Returns the withdrawn coin.
public fun withdraw<Asset>(
self: &mut MarginPool<Asset>,
registry: &MarginRegistry,
amount: Option<u64>,
clock: &Clock,
ctx: &mut TxContext,
): Coin<Asset> {
registry.load_inner();
let supplied_shares = self.positions.user_supply_shares(ctx);
let supplied_amount = self.state.supply_shares_to_amount(supplied_shares, &self.config, clock);
let withdraw_amount = amount.destroy_with_default(supplied_amount);
let withdraw_shares = math::mul(supplied_shares, math::div(withdraw_amount, supplied_amount));
let (_, protocol_fees) = self
.state
.decrease_supply_shares(&self.config, withdraw_shares, clock);
self.protocol_fees.increase_fees_per_share(self.state.supply_shares(), protocol_fees);
let (_, previous_referral) = self.positions.decrease_user_supply(withdraw_shares, ctx);
self.protocol_fees.decrease_shares(previous_referral, withdraw_shares, clock);
assert!(withdraw_amount <= self.vault.value(), ENotEnoughAssetInPool);
let coin = self.vault.split(withdraw_amount).into_coin(ctx);
event::emit(AssetWithdrawn {
margin_pool_id: self.id(),
asset_type: type_name::with_defining_ids<Asset>(),
supplier: ctx.sender(),
withdraw_amount,
withdraw_shares,
timestamp: clock.timestamp_ms(),
});
coin
}
/// Withdraw the referral fees.
public fun withdraw_referral_fees<Asset>(
self: &mut MarginPool<Asset>,
referral: &mut Referral,
clock: &Clock,
ctx: &mut TxContext,
): Coin<Asset> {
let referral_fees = self.protocol_fees.calculate_and_claim(referral, clock);
let coin = self.vault.split(referral_fees).into_coin(ctx);
coin
}
// === Public-View Functions ===
public fun deepbook_pool_allowed<Asset>(self: &MarginPool<Asset>, deepbook_pool_id: ID): bool {
self.allowed_deepbook_pools.contains(&deepbook_pool_id)
}
// === Public-Package Functions ===
/// Allows borrowing from the margin pool. Returns the borrowed coin.
public(package) fun borrow<Asset>(
self: &mut MarginPool<Asset>,
amount: u64,
clock: &Clock,
ctx: &mut TxContext,
): (Coin<Asset>, u64, u64) {
assert!(amount <= self.vault.value(), ENotEnoughAssetInPool);
assert!(amount >= self.config.min_borrow(), EBorrowAmountTooLow);
let (total_borrow, total_borrow_shares, protocol_fees) = self
.state
.increase_borrow(&self.config, amount, clock);
self.protocol_fees.increase_fees_per_share(self.state.supply_shares(), protocol_fees);
assert!(
self.state.utilization_rate() <= self.config.max_utilization_rate(),
EMaxPoolBorrowPercentageExceeded,
);
(self.vault.split(amount).into_coin(ctx), total_borrow, total_borrow_shares)
}
public(package) fun repay<Asset>(
self: &mut MarginPool<Asset>,
shares: u64,
coin: Coin<Asset>,
clock: &Clock,
) {
let (amount, protocol_fees) = self.state.decrease_borrow_shares(&self.config, shares, clock);
self.protocol_fees.increase_fees_per_share(self.state.supply_shares(), protocol_fees);
assert!(coin.value() == amount, EInvalidRepayQuantity);
self.vault.join(coin.into_balance());
}
// Repay a liquidation given some quantity of shares and a coin. If too much coin is given, then extra is used as reward.
// If not enough coin given, then the difference is recorded as default.
// Returns (applied amount repaid, reward given, and default recorded).
public(package) fun repay_liquidation<Asset>(
self: &mut MarginPool<Asset>,
shares: u64,
coin: Coin<Asset>,
clock: &Clock,
): (u64, u64, u64) {
let (amount, protocol_fees) = self.state.decrease_borrow_shares(&self.config, shares, clock); // decreased 48.545 shares, 97.087 USDC
self.protocol_fees.increase_fees_per_share(self.state.supply_shares(), protocol_fees);
let coin_value = coin.value(); // 100 USDC
let (reward, default) = if (coin_value > amount) {
self.state.increase_supply_absolute(coin_value - amount);
(coin_value - amount, 0)
} else {
self.state.decrease_supply_absolute(amount - coin_value);
(0, amount - coin_value)
};
self.vault.join(coin.into_balance());
(amount, reward, default)
}
public(package) fun borrow_shares_to_amount<Asset>(
self: &MarginPool<Asset>,
shares: u64,
clock: &Clock,
): u64 {
self.state.borrow_shares_to_amount(shares, &self.config, clock)
}
public(package) fun id<Asset>(self: &MarginPool<Asset>): ID {
self.id.to_inner()
}