Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.lua
More file actions
Latest commit
1446 lines (1230 loc) · 41.7 KB
/
Copy pathcontroller.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
localcoroutine=require"coroutine"
localbint=require".bint"(1024)
localutils=require".utils"
localjson=require"json"
localliquidations= {}
localassertions= {}
localscheduler= {}
localoracle= {}
localtokens= {}
localqueue= {}
-- oToken module ID
Module=Moduleor"C6CQfrL29jZ-LYXV2lKn09d3pBIM6adDFwWqh2ICikM"
-- oracle id and tolerance
Oracle=Oracleor"4fVi8P-xSRWxZ0EE0EpltDe8WJJvcD9QyFXMqfk-1UQ"
MaxOracleDelay=MaxOracleDelayor1200000
-- admin addresses
Owners=Ownersor {}
-- liquidops logo tx id
ProtocolLogo=ProtocolLogoor""
-- 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)
---@typeFriend[]
Tokens=Tokensor {}
-- queue for operations that change the user's position
---@type{ address: string, origin: string }[]
Queue=Queueor {}
-- current timestamp
Timestamp=Timestampor0
-- cached auctions (position wallet address, timestamp when discovered)
---@typetable<string, number>
Auctions=Auctionsor {}
-- maximum and minimum discount that can be applied to a loan in percentages
MaxDiscount=MaxDiscountor5
MinDiscount=MinDiscountor1
-- the period till the auction reaches the minimum discount (market price)
DiscountInterval=DiscountIntervalor1000*60*60-- 1 hour
PrecisionFactor=1000000
-- minimum liquidation percentage (a liquidator is required to liquidate at least this percentage of the total loan)
MinLiquidationThreshold=MinLiquidationThresholdor20
---@aliasTokenData{ ticker: string, denomination: number }
---@aliasPriceParam{ ticker: string, quantity: Bint?, denomination: number }
---@aliasCollateralBorrow{ token: string, ticker: string, quantity: string }
---@aliasQualifyingPosition{ 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.Timestampend
)
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
localrawPrices=oracle.sync()
-- generate position messages
---@typeMessageParam[]
localpositionMsgs= {}
for_, tokeninipairs(Tokens) do
table.insert(positionMsgs, { Target=token.oToken, Action="Positions" })
end
-- get all user positions
---@typeMessage[]
localrawPositions=scheduler.schedule(table.unpack(positionMsgs))
-- protocol positions in USD
---@typetable<string, { liquidationLimit: Bint, borrowBalance: Bint, debts: CollateralBorrow[], collaterals: CollateralBorrow[] }>
localallPositions= {}
localzero=bint.zero()
-- add positions
for_, marketinipairs(rawPositions) do
---@typeboolean, table<string, { Capacity: string, ["Borrow-Balance"]: string, Collateralization: string, ["Liquidation-Limit"]: string }>
localparsed, marketPositions=pcall(json.decode, market.Data)
assert(parsed, "Could not parse market data for " ..market.From)
localticker=market.Tags["Collateral-Ticker"]
localdenomination=tonumber(market.Tags["Collateral-Denomination"]) or0
localcollateral=utils.find(
function (t) returnt.oToken==market.Fromend,
Tokens
)
-- add each position in the market by their usd value
foraddress, positioninpairs(marketPositions) do
localposLiquidationLimit=bint(position["Liquidation-Limit"] or0)
localposBorrowBalance=bint(position["Borrow-Balance"] or0)
localhasCollateral=bint.ult(zero, posLiquidationLimit)
localhasLoan=bint.ult(zero, posBorrowBalance)
ifhasCollateralorhasLoanthen
allPositions[address] =allPositions[address] or {
liquidationLimit=zero,
borrowBalance=zero,
debts= {},
collaterals= {}
}
-- add liquidation limit
ifhasCollateralandcollateral~=nilthen
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
ifhasLoanandcollateral~=nilthen
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
---@typeQualifyingPosition[]
localqualifyingPositions= {}
-- now find the positions that can be auctioned
-- and update existing auctions
foraddress, positioninpairs(allPositions) do
-- check if the position can be liquidated
ifbint.ult(position.liquidationLimit, position.borrowBalance) then
-- add auction
liquidations.addAuction(address, msg.Timestamp)
-- calculate discount
localdiscount=tokens.getDiscount(address)
ifmsg.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
ifmsg.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
---@paramactionstring Accepted action
---@returnPatternFunction
functionassertions.isAdminAction(action)
returnfunction (msg)
ifmsg.From~=ao.env.Process.Idandnotutils.includes(msg.From, Owners) then
returnfalse
end
returnmsg.Tags.Action==action
end
end
Handlers.add(
"list",
assertions.isAdminAction("List"),
function (msg)
-- token to be listed
localtoken=msg.Tags.Token
assert(
assertions.isAddress(token),
"Invalid token address"
)
assert(
utils.find(function (t) returnt.id==tokenend, Tokens) ==nil,
"Token already listed"
)
-- check configuration
localliquidationThreshold=tonumber(msg.Tags["Liquidation-Threshold"])
localcollateralFactor=tonumber(msg.Tags["Collateral-Factor"])
localreserveFactor=tonumber(msg.Tags["Reserve-Factor"])
localbaseRate=tonumber(msg.Tags["Base-Rate"])
localinitRate=tonumber(msg.Tags["Init-Rate"])
localjumpRate=tonumber(msg.Tags["Jump-Rate"])
localcooldownPeriod=tonumber(msg.Tags["Cooldown-Period"])
localkinkParam=tonumber(msg.Tags["Kink-Param"])
assert(
collateralFactor~=nilandtype(collateralFactor) =="number",
"Invalid collateral factor"
)
assert(
collateralFactor//1==collateralFactorandcollateralFactor>=0andcollateralFactor<=100,
"Collateral factor has to be a whole percentage between 0 and 100"
)
assert(
liquidationThreshold~=nilandtype(liquidationThreshold) =="number",
"Invalid liquidation threshold"
)
assert(
liquidationThreshold//1==liquidationThresholdandliquidationThreshold>=0andliquidationThreshold<=100,
"Liquidation threshold has to be a whole percentage between 0 and 100"
)
assert(
liquidationThreshold>collateralFactororliquidationThreshold==0andcollateralFactor==0,
"Liquidation threshold must be greater than the collateral factor"
)
assert(
reserveFactor~=nilandtype(reserveFactor) =="number",
"Invalid reserve factor"
)
assert(
reserveFactor//1==reserveFactorandreserveFactor>=0andreserveFactor<=100,
"Reserve factor has to be a whole percentage between 0 and 100"
)
assert(
baseRate~=nilandassertions.isValidNumber(baseRate),
"Invalid base rate"
)
assert(
initRate~=nilandassertions.isValidNumber(initRate),
"Invalid init rate"
)
assert(
jumpRate~=nilandassertions.isValidNumber(jumpRate),
"Invalid jump rate"
)
assert(
assertions.isTokenQuantity(msg.Tags["Value-Limit"]),
"Invalid value limit"
)
assert(
cooldownPeriod~=nilandassertions.isValidInteger(cooldownPeriod),
"Invalid cooldown period"
)
assert(
kinkParam~=nilandtype(kinkParam) =="number",
"Invalid kink parameter"
)
assert(
kinkParam//1==kinkParamandkinkParam>=0andkinkParam<=100,
"Kink parameter has to be a whole percentage between 0 and 100"
)
-- check if token is supported
localsupported, info=tokens.isSupported(token)
assert(supported, "Token not supported by the protocol")
-- spawn logo
locallogo=msg.Tags.Logoorinfo.Tags.Logo
-- the oToken configuration
localconfig= {
Name="LiquidOps " ..tostring(info.Tags.Nameorinfo.Tags.Tickeror""),
["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
localspawnResult=ao.spawn(Module, config).receive()
localspawnedID=spawnResult.Tags.Process
-- notify all other tokens
for_, tinipairs(Tokens) do
ift.oToken~=spawnedIDthen
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) or0
})
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
localtoken=msg.Tags.Token
assert(
assertions.isAddress(token),
"Invalid token address"
)
-- find token index
---@typeinteger|nil
localidx=utils.find(
function (t) returnt.id==tokenend,
Tokens
)
assert(type(idx) =="number", "Token is not listed")
-- id of the oToken for this token
localoToken=Tokens[idx].oToken
-- unlist
table.remove(Tokens, idx)
-- notify all other oTokens
for_, tinipairs(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(notUpdateInProgress, "An update is already in progress")
-- allow skipping oTokens
localskip=msg.Tags.Skipandjson.decode(msg.Tags.Skip)
-- generate update msgs
---@typeMessageParam[]
localupdateMsgs= {}
for_, tinipairs(Tokens) do
ifnotskiporutils.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
---@typeMessage[]
localupdates=scheduler.schedule(table.unpack(updateMsgs))
UpdateInProgress=false
-- filter failed updates
localfailed=utils.filter(
---@paramresMessage
function (res) returnres.Tags.Error~=nilorres.Tags.Updated~="true" end,
updates
)
-- reply with results
msg.reply({
Updated=tostring(#Tokens-#failed),
Failed=tostring(#failed),
Data=json.encode(utils.map(
---@paramresMessage
function (res) returnres.Fromend,
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)
returnmsg.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
localtarget=msg.Tags["X-Target"]
-- liquidator address
localliquidator=msg.Tags.Sender
-- token to be liquidated, currently lent to the target
-- (the token that is paying for the loan = transferred token)
localliquidatedToken=msg.From
-- the token that the liquidator will earn for
-- paying off the loan
-- the user has to have a position in this token
localrewardToken=msg.Tags["X-Reward-Token"]
-- prepare liquidation, check required environment
localsuccess, errorMsg, expectedRewardQty, oTokensParticipating, removeWhenDone=pcall(function ()
assert(
assertions.isAddress(target) andtarget~=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; }
localoTokensParticipating= {}
---@typeMessageParam[]
localpositionMsgs= {}
for_, tinipairs(Tokens) do
ift.id==liquidatedTokenthenoTokensParticipating.liquidated=t.oTokenend
ift.id==rewardTokenthenoTokensParticipating.reward=t.oTokenend
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
localprices=oracle.sync()
-- check user position
---@typeMessage[]
localpositions=scheduler.schedule(table.unpack(positionMsgs))
-- check queue
assert(
notqueue.isQueued(target),
"User is queued for an operation"
)
-- get tokens that need a price fetch
localzero=bint.zero()
---@typePriceParam[], PriceParam[]
localliquidationLimits, borrowBalances= {}, {}
-- symbols to sync
---@typestring[]
localsymbols= {}
-- incoming and outgoing token data
---@typeTokenData, TokenData
localinTokenData, outTokenData= {}, {}
-- the total collateral of the desired reward token
-- in the user's position for the reward token
localavailableRewardQty=zero
-- the total borrow of the liquidated token in the
-- user's position
localavailableLiquidateQty=zero
-- check if the user has any open positions (active loans)
localhasOpenPosition=false
-- populate capacities, symbols, incoming/outgoing token data and collateral qty
for_, posinipairs(positions) do
localsymbol=pos.Tags["Collateral-Ticker"]
localdenomination=tonumber(pos.Tags["Collateral-Denomination"]) or0
-- convert quantities
localliquidationLimit=bint(pos.Tags["Liquidation-Limit"] or0)
localborrowBalance=bint(pos.Tags["Borrow-Balance"] or0)
ifpos.From==oTokensParticipating.liquidatedthen
inTokenData= { ticker=symbol, denomination=denomination }
availableLiquidateQty=borrowBalance
end
ifpos.From==oTokensParticipating.rewardthen
outTokenData= { ticker=symbol, denomination=denomination }
availableRewardQty=bint(pos.Tags.Collateralizationor0)
end
-- only sync if there is a position
ifbint.ult(zero, borrowBalance) orbint.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
ifbint.ult(zero, borrowBalance) then
hasOpenPosition=true
end
end
assert(
inTokenData.ticker~=nilandinTokenData.denomination~=nil,
"Incoming token data not found"
)
assert(
outTokenData.ticker~=nilandoutTokenData.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
ifnothasOpenPositionthen
-- 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
localtotalLiquidationLimit=utils.reduce(
function (acc, curr) returnacc+curr.valueend,
zero,
oracle.getValues(prices, liquidationLimits)
)
localtotalBorrowBalance=utils.reduce(
function (acc, curr) returnacc+curr.valueend,
zero,
oracle.getValues(prices, borrowBalances)
)
assert(
bint.ult(totalLiquidationLimit, totalBorrowBalance),
"Target not eligible for liquidation"
)
-- get token quantities
localinQty=bint(msg.Tags.Quantity)
-- USD value of the liquidation
localusdValue=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) orbint.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
localmarketValueInQty=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
localdiscount=tokens.getDiscount(target)
-- update the expected reward quantity using the discount
localexpectedRewardQty=marketValueInQty
ifdiscount>0then
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
ifbint.ult(availableRewardQty, expectedRewardQty) then
expectedRewardQty=availableRewardQty
end
-- the minimum quantity expected by the user
localminExpectedRewardQty=bint(msg.Tags["X-Min-Expected-Quantity"] or0)
-- 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(
notqueue.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
localremoveWhenDone=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
ifnotsuccessthen
-- signal error
ao.send({
Target=liquidator,
Action="Liquidate-Error",
Error=string.gsub(errorMsg, "%[[%w_.\" ]*%]:%d*: ", "")
})
-- refund
returnao.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)
localliquidationReference=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
localloanLiquidationRes=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)
ifloanLiquidationRes.Tags.ErrororloanLiquidationRes.Tags.Action~="Liquidate-Borrow-Confirmation" then
returnao.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
ifremoveWhenDonethen
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)
ifmsg.Action~="Add-To-Queue" thenreturnfalseend
returnutils.find(
function (t) returnt.oToken==msg.Fromend,
Tokens
) ~=nil
end,
function (msg)
localuser=msg.Tags.User
-- validate address
ifnotassertions.isAddress(user) then
returnmsg.reply({ Error="Invalid user address" })
end
-- check if the user has already been added
ifqueue.isQueued(user) orUpdateInProgressthen
returnmsg.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)
ifmsg.Action~="Remove-From-Queue" thenreturnfalseend
returnutils.find(
function (t) returnt.oToken==msg.Fromend,
Tokens
) ~=nil
end,
function (msg)
localuser=msg.Tags.User
-- validate address
ifnotassertions.isAddress(user) then
returnmsg.reply({ Error="Invalid user address" })
end
-- try to remove the user from the queue
localres=queue.remove(user, msg.From)
ifres~="removed" then
returnmsg.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)
localuser=msg.Tags.User
-- validate address
ifnotassertions.isAddress(user) then
returnmsg.reply({ ["In-Queue"] ="false" })
end
-- the user is queued if they're either in the collateral
-- or the liquidation queues
returnmsg.reply({
["In-Queue"] =json.encode(queue.isQueued(user) orUpdateInProgress)
})
end
)
Handlers.add(
"get-auctions",
{ Action="Get-Auctions" },
function (msg)
msg.reply({
["Initial-Discount"] =tostring(MaxDiscount),