-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.lua
More file actions
1446 lines (1230 loc) · 41.7 KB
/
controller.lua
File metadata and controls
1446 lines (1230 loc) · 41.7 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local coroutine = require "coroutine"
local bint = require ".bint"(1024)
local utils = require ".utils"
local json = require "json"
local liquidations = {}
local assertions = {}
local scheduler = {}
local oracle = {}
local tokens = {}
local queue = {}
-- oToken module ID
Module = Module or "C6CQfrL29jZ-LYXV2lKn09d3pBIM6adDFwWqh2ICikM"
-- oracle id and tolerance
Oracle = Oracle or "4fVi8P-xSRWxZ0EE0EpltDe8WJJvcD9QyFXMqfk-1UQ"
MaxOracleDelay = MaxOracleDelay or 1200000
-- admin addresses
Owners = Owners or {}
-- liquidops logo tx id
ProtocolLogo = ProtocolLogo or ""
-- holds all the processes that are part of the protocol
-- a member consists of the following fields:
-- - id: string (this is the address of the collateral supported by LiquidOps)
-- - ticker: string (the ticker of the collateral)
-- - oToken: string (the address of the oToken process for the collateral)
-- - denomination: integer (the denomination of the collateral)
---@type Friend[]
Tokens = Tokens or {}
-- queue for operations that change the user's position
---@type { address: string, origin: string }[]
Queue = Queue or {}
-- current timestamp
Timestamp = Timestamp or 0
-- cached auctions (position wallet address, timestamp when discovered)
---@type table<string, number>
Auctions = Auctions or {}
-- maximum and minimum discount that can be applied to a loan in percentages
MaxDiscount = MaxDiscount or 5
MinDiscount = MinDiscount or 1
-- the period till the auction reaches the minimum discount (market price)
DiscountInterval = DiscountInterval or 1000 * 60 * 60 -- 1 hour
PrecisionFactor = 1000000
-- minimum liquidation percentage (a liquidator is required to liquidate at least this percentage of the total loan)
MinLiquidationThreshold = MinLiquidationThreshold or 20
---@alias TokenData { ticker: string, denomination: number }
---@alias PriceParam { ticker: string, quantity: Bint?, denomination: number }
---@alias CollateralBorrow { token: string, ticker: string, quantity: string }
---@alias QualifyingPosition { target: string, depts: CollateralBorrow[], collaterals: CollateralBorrow[], discount: string }
Handlers.add(
"setup-patching",
function () return "continue" end,
function (msg)
ao.send({
device = "patch@1.0",
["token-info"] = { name = "LiquidOps Controller" },
oracle = Oracle,
["discount-config"] = {
min = MinDiscount,
max = MaxDiscount,
interval = DiscountInterval
},
tokens = Tokens,
queue = Queue,
auctions = Auctions
})
end
)
Handlers.add(
"sync-timestamp",
function () return "continue" end,
function (msg) Timestamp = msg.Timestamp end
)
Handlers.add(
"info",
{ Action = "Info" },
function (msg)
msg.reply({
Name = "LiquidOps Controller",
Module = Module,
Oracle = Oracle,
["Max-Discount"] = tostring(MaxDiscount),
["Min-Discount"] = tostring(MinDiscount),
["Discount-Interval"] = tostring(DiscountInterval),
Data = json.encode(Tokens)
})
end
)
Handlers.add(
"sync-auctions",
Handlers.utils.hasMatchingTagOf("Action", { "Cron", "Get-Liquidations" }),
function (msg)
-- fetch prices first, so the processing of the positions won't be delayed
local rawPrices = oracle.sync()
-- generate position messages
---@type MessageParam[]
local positionMsgs = {}
for _, token in ipairs(Tokens) do
table.insert(positionMsgs, { Target = token.oToken, Action = "Positions" })
end
-- get all user positions
---@type Message[]
local rawPositions = scheduler.schedule(table.unpack(positionMsgs))
-- protocol positions in USD
---@type table<string, { liquidationLimit: Bint, borrowBalance: Bint, debts: CollateralBorrow[], collaterals: CollateralBorrow[] }>
local allPositions = {}
local zero = bint.zero()
-- add positions
for _, market in ipairs(rawPositions) do
---@type boolean, table<string, { Capacity: string, ["Borrow-Balance"]: string, Collateralization: string, ["Liquidation-Limit"]: string }>
local parsed, marketPositions = pcall(json.decode, market.Data)
assert(parsed, "Could not parse market data for " .. market.From)
local ticker = market.Tags["Collateral-Ticker"]
local denomination = tonumber(market.Tags["Collateral-Denomination"]) or 0
local collateral = utils.find(
function (t) return t.oToken == market.From end,
Tokens
)
-- add each position in the market by their usd value
for address, position in pairs(marketPositions) do
local posLiquidationLimit = bint(position["Liquidation-Limit"] or 0)
local posBorrowBalance = bint(position["Borrow-Balance"] or 0)
local hasCollateral = bint.ult(zero, posLiquidationLimit)
local hasLoan = bint.ult(zero, posBorrowBalance)
if hasCollateral or hasLoan then
allPositions[address] = allPositions[address] or {
liquidationLimit = zero,
borrowBalance = zero,
debts = {},
collaterals = {}
}
-- add liquidation limit
if hasCollateral and collateral ~= nil then
allPositions[address].liquidationLimit = allPositions[address].liquidationLimit + oracle.getValue(
rawPrices,
posLiquidationLimit,
ticker,
denomination
)
table.insert(allPositions[address].collaterals, {
token = collateral.id,
ticker = ticker,
quantity = position.Collateralization
})
end
-- add borrow balance
if hasLoan and collateral ~= nil then
allPositions[address].borrowBalance = allPositions[address].borrowBalance + oracle.getValue(
rawPrices,
posBorrowBalance,
ticker,
denomination
)
table.insert(allPositions[address].debts, {
token = collateral.id,
ticker = ticker,
quantity = position["Borrow-Balance"]
})
end
end
end
end
---@type QualifyingPosition[]
local qualifyingPositions = {}
-- now find the positions that can be auctioned
-- and update existing auctions
for address, position in pairs(allPositions) do
-- check if the position can be liquidated
if bint.ult(position.liquidationLimit, position.borrowBalance) then
-- add auction
liquidations.addAuction(address, msg.Timestamp)
-- calculate discount
local discount = tokens.getDiscount(address)
if msg.Tags.Action == "Get-Liquidations" then
table.insert(qualifyingPositions, {
target = address,
debts = position.debts,
collaterals = position.collaterals,
discount = discount
})
end
else
-- remove auction, it is no longer necessary
liquidations.removeAuction(address)
end
end
if msg.Tags.Action == "Get-Liquidations" then
msg.reply({
Data = json.encode({
liquidations = qualifyingPositions,
tokens = Tokens,
maxDiscount = MaxDiscount,
minDiscount = MinDiscount,
discountInterval = DiscountInterval,
prices = rawPrices,
precisionFactor = PrecisionFactor
})
})
end
end
)
-- Verify if the caller of an admin function is
-- authorized to run this action
---@param action string Accepted action
---@return PatternFunction
function assertions.isAdminAction(action)
return function (msg)
if msg.From ~= ao.env.Process.Id and not utils.includes(msg.From, Owners) then
return false
end
return msg.Tags.Action == action
end
end
Handlers.add(
"list",
assertions.isAdminAction("List"),
function (msg)
-- token to be listed
local token = msg.Tags.Token
assert(
assertions.isAddress(token),
"Invalid token address"
)
assert(
utils.find(function (t) return t.id == token end, Tokens) == nil,
"Token already listed"
)
-- check configuration
local liquidationThreshold = tonumber(msg.Tags["Liquidation-Threshold"])
local collateralFactor = tonumber(msg.Tags["Collateral-Factor"])
local reserveFactor = tonumber(msg.Tags["Reserve-Factor"])
local baseRate = tonumber(msg.Tags["Base-Rate"])
local initRate = tonumber(msg.Tags["Init-Rate"])
local jumpRate = tonumber(msg.Tags["Jump-Rate"])
local cooldownPeriod = tonumber(msg.Tags["Cooldown-Period"])
local kinkParam = tonumber(msg.Tags["Kink-Param"])
assert(
collateralFactor ~= nil and type(collateralFactor) == "number",
"Invalid collateral factor"
)
assert(
collateralFactor // 1 == collateralFactor and collateralFactor >= 0 and collateralFactor <= 100,
"Collateral factor has to be a whole percentage between 0 and 100"
)
assert(
liquidationThreshold ~= nil and type(liquidationThreshold) == "number",
"Invalid liquidation threshold"
)
assert(
liquidationThreshold // 1 == liquidationThreshold and liquidationThreshold >= 0 and liquidationThreshold <= 100,
"Liquidation threshold has to be a whole percentage between 0 and 100"
)
assert(
liquidationThreshold > collateralFactor or liquidationThreshold == 0 and collateralFactor == 0,
"Liquidation threshold must be greater than the collateral factor"
)
assert(
reserveFactor ~= nil and type(reserveFactor) == "number",
"Invalid reserve factor"
)
assert(
reserveFactor // 1 == reserveFactor and reserveFactor >= 0 and reserveFactor <= 100,
"Reserve factor has to be a whole percentage between 0 and 100"
)
assert(
baseRate ~= nil and assertions.isValidNumber(baseRate),
"Invalid base rate"
)
assert(
initRate ~= nil and assertions.isValidNumber(initRate),
"Invalid init rate"
)
assert(
jumpRate ~= nil and assertions.isValidNumber(jumpRate),
"Invalid jump rate"
)
assert(
assertions.isTokenQuantity(msg.Tags["Value-Limit"]),
"Invalid value limit"
)
assert(
cooldownPeriod ~= nil and assertions.isValidInteger(cooldownPeriod),
"Invalid cooldown period"
)
assert(
kinkParam ~= nil and type(kinkParam) == "number",
"Invalid kink parameter"
)
assert(
kinkParam // 1 == kinkParam and kinkParam >= 0 and kinkParam <= 100,
"Kink parameter has to be a whole percentage between 0 and 100"
)
-- check if token is supported
local supported, info = tokens.isSupported(token)
assert(supported, "Token not supported by the protocol")
-- spawn logo
local logo = msg.Tags.Logo or info.Tags.Logo
-- the oToken configuration
local config = {
Name = "LiquidOps " .. tostring(info.Tags.Name or info.Tags.Ticker or ""),
["Collateral-Id"] = token,
["Collateral-Ticker"] = info.Tags.Ticker,
["Collateral-Name"] = info.Tags.Name,
["Collateral-Denomination"] = info.Tags.Denomination,
["Collateral-Factor"] = msg.Tags["Collateral-Factor"],
["Liquidation-Threshold"] = tostring(liquidationThreshold),
["Reserve-Factor"] = tostring(reserveFactor),
["Base-Rate"] = msg.Tags["Base-Rate"],
["Init-Rate"] = msg.Tags["Init-Rate"],
["Jump-Rate"] = msg.Tags["Jump-Rate"],
["Kink-Param"] = msg.Tags["Kink-Param"],
["Value-Limit"] = msg.Tags["Value-Limit"],
["Cooldown-Period"] = msg.Tags["Cooldown-Period"],
Oracle = Oracle,
["Oracle-Delay-Tolerance"] = tostring(MaxOracleDelay),
Logo = logo,
Authority = ao.authorities[1],
Friends = json.encode(Tokens)
}
-- spawn new oToken process
local spawnResult = ao.spawn(Module, config).receive()
local spawnedID = spawnResult.Tags.Process
-- notify all other tokens
for _, t in ipairs(Tokens) do
if t.oToken ~= spawnedID then
ao.send({
Target = t.oToken,
Action = "Add-Friend",
Friend = spawnedID,
Token = token,
Ticker = info.Tags.Ticker,
Denomination = info.Tags.Denomination
})
end
end
-- add token to tokens list
table.insert(Tokens, {
id = token,
ticker = info.Tags.Ticker,
oToken = spawnedID,
denomination = tonumber(info.Tags.Denomination) or 0
})
msg.reply({
Action = "Token-Listed",
Token = token,
["Spawned-Id"] = spawnedID,
Data = json.encode(config)
})
end
)
Handlers.add(
"unlist",
assertions.isAdminAction("Unlist"),
function (msg)
-- token to be removed
local token = msg.Tags.Token
assert(
assertions.isAddress(token),
"Invalid token address"
)
-- find token index
---@type integer|nil
local idx = utils.find(
function (t) return t.id == token end,
Tokens
)
assert(type(idx) == "number", "Token is not listed")
-- id of the oToken for this token
local oToken = Tokens[idx].oToken
-- unlist
table.remove(Tokens, idx)
-- notify all other oTokens
for _, t in ipairs(Tokens) do
ao.send({
Target = t.oToken,
Action = "Remove-Friend",
Friend = oToken
})
end
msg.reply({
Action = "Token-Unlisted",
Token = token,
["Removed-Id"] = oToken
})
end
)
Handlers.add(
"batch-update",
assertions.isAdminAction("Batch-Update"),
function (msg)
-- check if update is already in progress
assert(not UpdateInProgress, "An update is already in progress")
-- allow skipping oTokens
local skip = msg.Tags.Skip and json.decode(msg.Tags.Skip)
-- generate update msgs
---@type MessageParam[]
local updateMsgs = {}
for _, t in ipairs(Tokens) do
if not skip or utils.includes(t.oToken, skip) then
table.insert(updateMsgs, {
Target = t.oToken,
Action = "Update",
Data = msg.Data
})
end
end
-- set updating in progress. this will halt interactions
-- by making the queue check always return true for any
-- address
UpdateInProgress = true
-- request updates
---@type Message[]
local updates = scheduler.schedule(table.unpack(updateMsgs))
UpdateInProgress = false
-- filter failed updates
local failed = utils.filter(
---@param res Message
function (res) return res.Tags.Error ~= nil or res.Tags.Updated ~= "true" end,
updates
)
-- reply with results
msg.reply({
Updated = tostring(#Tokens - #failed),
Failed = tostring(#failed),
Data = json.encode(utils.map(
---@param res Message
function (res) return res.From end,
failed
))
})
end
)
Handlers.add(
"get-tokens",
{ Action = "Get-Tokens" },
function (msg)
msg.reply({
Data = json.encode(Tokens)
})
end
)
Handlers.add(
"get-oracle",
{ Action = "Get-Oracle" },
function (msg)
msg.reply({ Oracle = Oracle })
end
)
Handlers.add(
"refund-invalid",
function (msg)
return msg.Tags.Action == "Credit-Notice" and
msg.Tags["X-Action"] ~= "Liquidate"
end,
function (msg)
ao.send({
Target = msg.From,
Action = "Transfer",
Quantity = msg.Tags.Quantity,
Recipient = msg.Tags.Sender,
["X-Action"] = "Refund",
["X-Refund-Reason"] = "This process does not accept the transferred token " .. msg.From
})
end
)
Handlers.add(
"liquidate",
{ Action = "Credit-Notice", ["X-Action"] = "Liquidate" },
function (msg)
-- liquidation target
local target = msg.Tags["X-Target"]
-- liquidator address
local liquidator = msg.Tags.Sender
-- token to be liquidated, currently lent to the target
-- (the token that is paying for the loan = transferred token)
local liquidatedToken = msg.From
-- the token that the liquidator will earn for
-- paying off the loan
-- the user has to have a position in this token
local rewardToken = msg.Tags["X-Reward-Token"]
-- prepare liquidation, check required environment
local success, errorMsg, expectedRewardQty, oTokensParticipating, removeWhenDone = pcall(function ()
assert(
assertions.isAddress(target) and target ~= liquidator,
"Invalid liquidation target"
)
assert(
assertions.isAddress(liquidator),
"Invalid liquidator address"
)
assert(
assertions.isAddress(rewardToken),
"Invalid reward token address"
)
assert(
assertions.isTokenQuantity(msg.Tags.Quantity),
"Invalid transfer quantity"
)
assert(
assertions.isTokenQuantity(msg.Tags["X-Min-Expected-Quantity"]),
"Invalid minimum expected quantity"
)
-- try to find the liquidated token, the reward token and
-- generate the position messages in one loop for efficiency
---@type { liquidated: string; reward: string; }
local oTokensParticipating = {}
---@type MessageParam[]
local positionMsgs = {}
for _, t in ipairs(Tokens) do
if t.id == liquidatedToken then oTokensParticipating.liquidated = t.oToken end
if t.id == rewardToken then oTokensParticipating.reward = t.oToken end
table.insert(positionMsgs, {
Target = t.oToken,
Action = "Position",
Recipient = target
})
end
assert(
oTokensParticipating.liquidated ~= nil,
"Cannot liquidate the incoming token as it is not listed"
)
assert(
oTokensParticipating.reward ~= nil,
"Cannot liquidate for the reward token as it is not listed"
)
-- fetch prices first so the user positions won't be outdated
local prices = oracle.sync()
-- check user position
---@type Message[]
local positions = scheduler.schedule(table.unpack(positionMsgs))
-- check queue
assert(
not queue.isQueued(target),
"User is queued for an operation"
)
-- get tokens that need a price fetch
local zero = bint.zero()
---@type PriceParam[], PriceParam[]
local liquidationLimits, borrowBalances = {}, {}
-- symbols to sync
---@type string[]
local symbols = {}
-- incoming and outgoing token data
---@type TokenData, TokenData
local inTokenData, outTokenData = {}, {}
-- the total collateral of the desired reward token
-- in the user's position for the reward token
local availableRewardQty = zero
-- the total borrow of the liquidated token in the
-- user's position
local availableLiquidateQty = zero
-- check if the user has any open positions (active loans)
local hasOpenPosition = false
-- populate capacities, symbols, incoming/outgoing token data and collateral qty
for _, pos in ipairs(positions) do
local symbol = pos.Tags["Collateral-Ticker"]
local denomination = tonumber(pos.Tags["Collateral-Denomination"]) or 0
-- convert quantities
local liquidationLimit = bint(pos.Tags["Liquidation-Limit"] or 0)
local borrowBalance = bint(pos.Tags["Borrow-Balance"] or 0)
if pos.From == oTokensParticipating.liquidated then
inTokenData = { ticker = symbol, denomination = denomination }
availableLiquidateQty = borrowBalance
end
if pos.From == oTokensParticipating.reward then
outTokenData = { ticker = symbol, denomination = denomination }
availableRewardQty = bint(pos.Tags.Collateralization or 0)
end
-- only sync if there is a position
if bint.ult(zero, borrowBalance) or bint.ult(zero, liquidationLimit) then
table.insert(symbols, symbol)
table.insert(borrowBalances, {
ticker = symbol,
quantity = borrowBalance,
denomination = denomination
})
table.insert(liquidationLimits, {
ticker = symbol,
quantity = liquidationLimit,
denomination = denomination
})
end
-- update user position indicator
if bint.ult(zero, borrowBalance) then
hasOpenPosition = true
end
end
assert(
inTokenData.ticker ~= nil and inTokenData.denomination ~= nil,
"Incoming token data not found"
)
assert(
outTokenData.ticker ~= nil and outTokenData.denomination ~= nil,
"Outgoing token data not found"
)
assert(
bint.ult(zero, availableRewardQty),
"No available reward quantity"
)
assert(
bint.ult(zero, availableLiquidateQty),
"No available liquidate quantity"
)
-- check if the user has any open positions
if not hasOpenPosition then
-- remove from auctions if present
liquidations.removeAuction(target)
-- error and trigger refund
error("User does not have an active loan")
end
-- ensure "liquidation-limit / borrow-balance < 1"
-- this means that the user is eligible for liquidation
local totalLiquidationLimit = utils.reduce(
function (acc, curr) return acc + curr.value end,
zero,
oracle.getValues(prices, liquidationLimits)
)
local totalBorrowBalance = utils.reduce(
function (acc, curr) return acc + curr.value end,
zero,
oracle.getValues(prices, borrowBalances)
)
assert(
bint.ult(totalLiquidationLimit, totalBorrowBalance),
"Target not eligible for liquidation"
)
-- get token quantities
local inQty = bint(msg.Tags.Quantity)
-- USD value of the liquidation
local usdValue = oracle.getValue(
prices,
inQty,
inTokenData.ticker,
inTokenData.denomination
)
-- ensure that at least the minimum threshold is reached
-- when repaying the loan or the liquidator is repaying the
-- full amount, in case the total value of the loan they're
-- repaying is under 20% of the user's loans' total value
assert(
bint.ule(availableLiquidateQty, inQty) or bint.ule(
bint.udiv(
totalBorrowBalance * bint(MinLiquidationThreshold * 100 // 1),
bint(100 * 100)
),
usdValue
),
"Liquidators are required to repay at least " ..
tostring(MinLiquidationThreshold) ..
"% of the total loan or the entire loan of a token"
)
-- market value of the liquidation
local marketValueInQty = oracle.getValueInToken(
{
ticker = inTokenData.ticker,
quantity = inQty,
denomination = inTokenData.denomination
},
outTokenData,
prices
)
-- make sure that the user's position is enough to pay the liquidator
-- (at least the market value of the tokens)
assert(
bint.ule(marketValueInQty, availableRewardQty),
"The user does not have enough tokens in their position for this liquidation"
)
-- apply auction
local discount = tokens.getDiscount(target)
-- update the expected reward quantity using the discount
local expectedRewardQty = marketValueInQty
if discount > 0 then
expectedRewardQty = bint.udiv(
expectedRewardQty * bint(100 * PrecisionFactor + discount),
bint(100 * PrecisionFactor)
)
end
-- if the discount is higher than the position in the
-- reward token, we need to update it with the maximum
-- possible amount
if bint.ult(availableRewardQty, expectedRewardQty) then
expectedRewardQty = availableRewardQty
end
-- the minimum quantity expected by the user
local minExpectedRewardQty = bint(msg.Tags["X-Min-Expected-Quantity"] or 0)
-- make sure the user is receiving at least
-- the minimum amount of tokens they're expecting
assert(
bint.ule(minExpectedRewardQty, expectedRewardQty),
"Could not meet the defined slippage"
)
-- check queue
assert(
not queue.isQueued(target),
"User is already queued for liquidation"
)
-- whether or not to remove the auction after this liquidation is complete.
-- this checks if the position becomes healthy after the liquidation
local removeWhenDone = bint.ule(
totalBorrowBalance - oracle.getValue(prices, bint.min(inQty, availableLiquidateQty), inTokenData.ticker, inTokenData.denomination),
totalLiquidationLimit - oracle.getValue(prices, expectedRewardQty, outTokenData.ticker, outTokenData.denomination)
)
return "", expectedRewardQty, oTokensParticipating, removeWhenDone
end)
-- check if liquidation is possible
if not success then
-- signal error
ao.send({
Target = liquidator,
Action = "Liquidate-Error",
Error = string.gsub(errorMsg, "%[[%w_.\" ]*%]:%d*: ", "")
})
-- refund
return ao.send({
Target = msg.From,
Action = "Transfer",
Quantity = msg.Tags.Quantity,
Recipient = liquidator
})
end
-- since a liquidation is possible for the target
-- we add it to the list of discovered auctions
liquidations.addAuction(target, msg.Timestamp)
-- queue the liquidation at this point, because
-- the user position has been checked, so the liquidation is valid
-- we don't want anyone to be able to liquidate from this point
queue.add(target, ao.id)
-- TODO: timeout here? (what if this doesn't return in time, the liquidation remains in a pending state)
-- TODO: this timeout can be done with a Handler that removed this coroutine
-- liquidation reference to identify the result
-- (we cannot use .receive() here, since both the target
-- and the default response reference will change, because
-- of the chained messages)
local liquidationReference = msg.Id .. "-" .. liquidator
-- liquidate the loan
ao.send({
Target = liquidatedToken,
Action = "Transfer",
Quantity = msg.Tags.Quantity,
Recipient = oTokensParticipating.liquidated,
["X-Action"] = "Liquidate-Borrow",
["X-Liquidator"] = liquidator,
["X-Liquidation-Target"] = target,
["X-Reward-Market"] = oTokensParticipating.reward,
["X-Reward-Quantity"] = tostring(expectedRewardQty),
["X-Liquidation-Reference"] = liquidationReference
})
-- wait for result
local loanLiquidationRes = Handlers.receive({
From = oTokensParticipating.liquidated,
["Liquidation-Reference"] = liquidationReference
})
-- remove from queue (discard result - if we get to this point, the user should be queued by the controller)
queue.remove(target, ao.id)
-- check loan liquidation result
-- (at this point, we do not need to refund the user
-- because the oToken process handles that)
if loanLiquidationRes.Tags.Error or loanLiquidationRes.Tags.Action ~= "Liquidate-Borrow-Confirmation" then
return ao.send({
Target = liquidator,
Action = "Liquidate-Error",
Error = loanLiquidationRes.Tags.Error
})
end
-- if the auction is done (no more loans to liquidate)
-- we need to remove it from the discovered auctions
if removeWhenDone then
liquidations.removeAuction(target)
end
-- send confirmation to the liquidator
ao.send({
Target = liquidator,
Action = "Liquidate-Confirmation",
["Liquidation-Target"] = target,
["From-Quantity"] = msg.Tags.Quantity,
["From-Token"] = liquidatedToken,
["To-Quantity"] = tostring(expectedRewardQty),
["To-Token"] = rewardToken
})
-- send notice to the target
ao.send({
Target = target,
Action = "Liquidate-Notice",
["From-Quantity"] = msg.Tags.Quantity,
["To-Quantity"] = tostring(expectedRewardQty)
})
end
)
Handlers.add(
"add-queue",
function (msg)
if msg.Action ~= "Add-To-Queue" then return false end
return utils.find(
function (t) return t.oToken == msg.From end,
Tokens
) ~= nil
end,
function (msg)
local user = msg.Tags.User
-- validate address
if not assertions.isAddress(user) then
return msg.reply({ Error = "Invalid user address" })
end
-- check if the user has already been added
if queue.isQueued(user) or UpdateInProgress then
return msg.reply({ Error = "User already queued" })
end
-- add to queue
queue.add(user, msg.From)
msg.reply({ ["Queued-User"] = user })
end
)
Handlers.add(
"remove-queue",
function (msg)
if msg.Action ~= "Remove-From-Queue" then return false end
return utils.find(
function (t) return t.oToken == msg.From end,
Tokens
) ~= nil
end,
function (msg)
local user = msg.Tags.User
-- validate address
if not assertions.isAddress(user) then
return msg.reply({ Error = "Invalid user address" })
end
-- try to remove the user from the queue
local res = queue.remove(user, msg.From)
if res ~= "removed" then
return msg.reply({
Error = res == "not_queued" and
"The user is not queued" or
"The user was queued from another origin"
})
end
-- reply with confirmation
msg.reply({ ["Unqueued-User"] = user })
end
)
Handlers.add(
"check-queue",
{ Action = "Check-Queue-For" },
function (msg)
local user = msg.Tags.User
-- validate address
if not assertions.isAddress(user) then
return msg.reply({ ["In-Queue"] = "false" })
end
-- the user is queued if they're either in the collateral
-- or the liquidation queues
return msg.reply({
["In-Queue"] = json.encode(queue.isQueued(user) or UpdateInProgress)
})
end
)
Handlers.add(
"get-auctions",
{ Action = "Get-Auctions" },
function (msg)
msg.reply({
["Initial-Discount"] = tostring(MaxDiscount),