/
issuancedb.go
1219 lines (1030 loc) · 36.4 KB
/
issuancedb.go
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
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"math"
"github.com/33cn/chain33/account"
"github.com/33cn/chain33/common"
dbm "github.com/33cn/chain33/common/db"
"github.com/33cn/chain33/common/db/table"
"github.com/33cn/chain33/system/dapp"
"github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/issuance/types"
tokenE "github.com/33cn/plugin/plugin/dapp/token/executor"
"github.com/shopspring/decimal"
)
// List control
const (
ListDESC = int32(0) // list降序
ListASC = int32(1) // list升序
DefaultCount = int32(20) // 默认一次取多少条记录
MaxCount = int32(100) // 最多取100条
)
//setting
const (
DefaultDebtCeiling = 100000 // 默认借贷限额
DefaultLiquidationRatio = 0.25 * 1e4 // 默认质押比
DefaultPeriod = 3600 * 24 * 365 // 默认合约限期
PriceWarningRate = 1.3 * 1e4 // 价格提前预警率
ExpireWarningTime = 3600 * 24 * 10 // 提前10天超时预警
)
func getManageKey(key string, db dbm.KV) ([]byte, error) {
manageKey := types.ManageKey(key)
value, err := db.Get([]byte(manageKey))
if err != nil {
return nil, err
}
return value, nil
}
func getGuarantorAddr(db dbm.KV) (string, error) {
value, err := getManageKey(pty.GuarantorKey, db)
if err != nil {
clog.Error("IssuancePriceFeed", "getGuarantorAddr", err)
return "", err
}
if value == nil {
clog.Error("IssuancePriceFeed guarantorKey found nil value")
return "", err
}
var item types.ConfigItem
err = types.Decode(value, &item)
if err != nil {
clog.Error("IssuancePriceFeed", "getGuarantorAddr", err)
return "", err
}
return item.GetArr().Value[0], nil
}
func isRightAddr(key string, addr string, db dbm.KV) bool {
value, err := getManageKey(key, db)
if err != nil {
clog.Error("isRightAddr", "Key", key)
return false
}
if value == nil {
clog.Error("isRightAddr", "key", key, "error", "Found key nil value")
return false
}
var item types.ConfigItem
err = types.Decode(value, &item)
if err != nil {
clog.Error("isRightAddr", "Decode", value)
return false
}
for _, op := range item.GetArr().Value {
if op == addr {
return true
}
}
return false
}
func isSuperAddr(addr string, db dbm.KV) bool {
data, err := db.Get(AddrKey())
if err != nil {
clog.Error("getSuperAddr", "error", err)
return false
}
var item types.ConfigItem
err = types.Decode(data, &item)
if err != nil {
clog.Error("isSuperAddr", "Decode", data)
return false
}
for _, op := range item.GetArr().Value {
if op == addr {
return true
}
}
return false
}
// IssuanceDB def
type IssuanceDB struct {
pty.Issuance
}
// GetKVSet for IssuanceDB
func (issu *IssuanceDB) GetKVSet() (kvset []*types.KeyValue) {
value := types.Encode(&issu.Issuance)
kvset = append(kvset, &types.KeyValue{Key: Key(issu.IssuanceId), Value: value})
return kvset
}
// Save for IssuanceDB
func (issu *IssuanceDB) Save(db dbm.KV) {
set := issu.GetKVSet()
for i := 0; i < len(set); i++ {
db.Set(set[i].GetKey(), set[i].Value)
}
}
// Key for Issuance
func Key(id string) (key []byte) {
key = append(key, []byte("mavl-"+pty.IssuanceX+"-")...)
key = append(key, []byte(id)...)
return key
}
// AddrKey for IssuanceAddrConfig
func AddrKey() (key []byte) {
key = append(key, []byte("mavl-"+pty.IssuanceX+"-addr")...)
return key
}
// PriceKey for IssuancePriceFeed
func PriceKey() (key []byte) {
key = append(key, []byte("mavl-"+pty.IssuanceX+"-price")...)
return key
}
// Action struct
type Action struct {
coinsAccount *account.DB // bty账户
tokenAccount *account.DB // ccny账户
db dbm.KV
localDB dbm.KVDB
txhash []byte
fromaddr string
blocktime int64
height int64
execaddr string
difficulty uint64
index int
Issuance *Issuance
}
// NewIssuanceAction generate New Action
func NewIssuanceAction(c *Issuance, tx *types.Transaction, index int) *Action {
hash := tx.Hash()
fromaddr := tx.From()
cfg := c.GetAPI().GetConfig()
tokenDb, err := account.NewAccountDB(cfg, tokenE.GetName(), pty.CCNYTokenName, c.GetStateDB())
if err != nil {
clog.Error("NewIssuanceAction", "Get Account DB error", "error", err)
return nil
}
return &Action{
coinsAccount: c.GetCoinsAccount(), tokenAccount: tokenDb, db: c.GetStateDB(), localDB: c.GetLocalDB(),
txhash: hash, fromaddr: fromaddr, blocktime: c.GetBlockTime(), height: c.GetHeight(),
execaddr: dapp.ExecAddress(string(tx.Execer)), difficulty: c.GetDifficulty(), index: index, Issuance: c}
}
// GetCreateReceiptLog generate logs for Issuance create action
func (action *Action) GetCreateReceiptLog(issuance *pty.Issuance) *types.ReceiptLog {
log := &types.ReceiptLog{}
log.Ty = pty.TyLogIssuanceCreate
c := &pty.ReceiptIssuance{}
c.IssuanceId = issuance.IssuanceId
c.Status = issuance.Status
log.Log = types.Encode(c)
return log
}
// GetDebtReceiptLog generate logs for Issuance debt action
func (action *Action) GetDebtReceiptLog(issuance *pty.Issuance, debtRecord *pty.DebtRecord) *types.ReceiptLog {
log := &types.ReceiptLog{}
log.Ty = pty.TyLogIssuanceDebt
c := &pty.ReceiptIssuance{}
c.IssuanceId = issuance.IssuanceId
c.AccountAddr = action.fromaddr
c.DebtId = debtRecord.DebtId
c.Status = debtRecord.Status
log.Log = types.Encode(c)
return log
}
// GetRepayReceiptLog generate logs for Issuance Repay action
func (action *Action) GetRepayReceiptLog(issuance *pty.Issuance, debtRecord *pty.DebtRecord) *types.ReceiptLog {
log := &types.ReceiptLog{}
log.Ty = pty.TyLogIssuanceRepay
c := &pty.ReceiptIssuance{}
c.IssuanceId = issuance.IssuanceId
c.AccountAddr = action.fromaddr
c.DebtId = debtRecord.DebtId
c.Status = debtRecord.Status
log.Log = types.Encode(c)
return log
}
// GetFeedReceiptLog generate logs for Issuance price feed action
func (action *Action) GetFeedReceiptLog(issuance *pty.Issuance, debtRecord *pty.DebtRecord) *types.ReceiptLog {
log := &types.ReceiptLog{}
log.Ty = pty.TyLogIssuanceFeed
c := &pty.ReceiptIssuance{}
c.IssuanceId = issuance.IssuanceId
c.AccountAddr = debtRecord.AccountAddr
c.DebtId = debtRecord.DebtId
c.Status = debtRecord.Status
log.Log = types.Encode(c)
return log
}
// GetCloseReceiptLog generate logs for Issuance close action
func (action *Action) GetCloseReceiptLog(issuance *pty.Issuance) *types.ReceiptLog {
log := &types.ReceiptLog{}
log.Ty = pty.TyLogIssuanceClose
c := &pty.ReceiptIssuance{}
c.IssuanceId = issuance.IssuanceId
c.Status = issuance.Status
log.Log = types.Encode(c)
return log
}
// GetIndex returns index in block
func (action *Action) GetIndex() int64 {
return action.height*types.MaxTxsPerBlock + int64(action.index)
}
func getLatestLiquidationPrice(issu *pty.Issuance) int64 {
var latest int64
for _, collRecord := range issu.DebtRecords {
if collRecord.LiquidationPrice > latest {
latest = collRecord.LiquidationPrice
}
}
return latest
}
func getLatestExpireTime(issu *pty.Issuance) int64 {
var latest int64 = 0x7fffffffffffffff
for _, collRecord := range issu.DebtRecords {
if collRecord.ExpireTime < latest {
latest = collRecord.ExpireTime
}
}
return latest
}
// IssuanceManage 设置全局借贷参数(管理员权限)
func (action *Action) IssuanceManage(manage *pty.IssuanceManage) (*types.Receipt, error) {
var kv []*types.KeyValue
var receipt *types.Receipt
// 是否配置管理用户
if !isRightAddr(pty.ManageKey, action.fromaddr, action.db) {
clog.Error("IssuanceManage", "addr", action.fromaddr, "error", "Address has no permission to config")
return nil, pty.ErrPermissionDeny
}
// 添加大户地址
var item types.ConfigItem
data, err := action.db.Get(AddrKey())
if err != nil {
if err != types.ErrNotFound {
clog.Error("IssuanceManage", "error", err)
return nil, err
}
emptyValue := &types.ArrayConfig{Value: make([]string, 0)}
arr := types.ConfigItem_Arr{Arr: emptyValue}
item.Value = &arr
item.GetArr().Value = append(item.GetArr().Value, manage.SuperAddrs...)
value := types.Encode(&item)
action.db.Set(AddrKey(), value)
kv = append(kv, &types.KeyValue{Key: AddrKey(), Value: value})
} else {
err = types.Decode(data, &item)
if err != nil {
clog.Debug("IssuanceManage", "decode", err)
return nil, err
}
item.GetArr().Value = append(item.GetArr().Value, manage.SuperAddrs...)
value := types.Encode(&item)
action.db.Set(AddrKey(), value)
kv = append(kv, &types.KeyValue{Key: AddrKey(), Value: value})
}
receipt = &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: nil}
return receipt, nil
}
func (action *Action) getSuperAddr() []string {
data, err := action.db.Get(AddrKey())
if err != nil {
clog.Error("getSuperAddr", "error", err)
return nil
}
var addrStore pty.IssuanceManage
err = types.Decode(data, &addrStore)
if err != nil {
clog.Debug("getSuperAddr", "decode", err)
return nil
}
return addrStore.SuperAddrs
}
// IssuanceCreate 创建借贷,持有一定数量ccny的用户可创建借贷,提供给其他用户借贷
func (action *Action) IssuanceCreate(create *pty.IssuanceCreate) (*types.Receipt, error) {
var logs []*types.ReceiptLog
var kv []*types.KeyValue
var receipt *types.Receipt
cfg := action.Issuance.GetAPI().GetConfig()
// 是否配置管理用户
if !isRightAddr(pty.FundKey, action.fromaddr, action.db) {
clog.Error("IssuanceCreate", "addr", action.fromaddr, "error", "Address has no permission to create")
return nil, pty.ErrPermissionDeny
}
// 参数检查
if create.GetTotalBalance() <= 0 {
clog.Error("IssuanceCreate", "addr", action.fromaddr, "execaddr", action.execaddr, "total balance", create.GetTotalBalance(), "error", types.ErrAmount)
return nil, types.ErrAmount
}
if create.DebtCeiling < 0 || create.LiquidationRatio < 0 || create.Period < 0 {
clog.Error("IssuanceCreate", "addr", action.fromaddr, "execaddr", action.execaddr, "error", types.ErrInvalidParam)
return nil, types.ErrInvalidParam
}
// 检查ccny余额
if !action.CheckExecTokenAccount(action.fromaddr, create.TotalBalance, false) {
return nil, types.ErrInsufficientBalance
}
// 查找ID是否重复
issuanceID := common.ToHex(action.txhash)
_, err := queryIssuanceByID(action.db, issuanceID)
if err != types.ErrNotFound {
clog.Error("IssuanceCreate", "IssuanceCreate repeated", issuanceID)
return nil, pty.ErrIssuanceRepeatHash
}
// 冻结ccny
receipt, err = action.tokenAccount.ExecFrozen(action.fromaddr, action.execaddr, create.TotalBalance)
if err != nil {
clog.Error("IssuanceCreate.Frozen", "addr", action.fromaddr, "execaddr", action.execaddr, "amount", create.TotalBalance)
return nil, err
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
// 构造coll结构
issu := &IssuanceDB{}
issu.IssuanceId = issuanceID
issu.TotalBalance = create.TotalBalance
if create.LiquidationRatio != 0 {
issu.LiquidationRatio = create.LiquidationRatio
} else {
issu.LiquidationRatio = DefaultLiquidationRatio
}
if create.DebtCeiling != 0 {
issu.DebtCeiling = create.DebtCeiling
} else {
issu.DebtCeiling = DefaultDebtCeiling * cfg.GetCoinPrecision()
}
if create.Period != 0 {
issu.Period = create.Period
} else {
issu.Period = DefaultPeriod
}
issu.Balance = create.TotalBalance
issu.CreateTime = action.blocktime
issu.IssuerAddr = action.fromaddr
issu.Status = pty.IssuanceActionCreate
clog.Debug("IssuanceCreate created", "IssuanceID", issuanceID, "TotalBalance", issu.TotalBalance)
// 保存
issu.Save(action.db)
kv = append(kv, issu.GetKVSet()...)
receiptLog := action.GetCreateReceiptLog(&issu.Issuance)
logs = append(logs, receiptLog)
receipt = &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
// 根据最近抵押物价格计算需要冻结的BTY数量
func getBtyNumToFrozen(value int64, price int64, ratio int64) (int64, error) {
if price == 0 {
clog.Error("Bty price should greate to 0")
return 0, pty.ErrPriceInvalid
}
btyValue := (value * 1e4) / (price * ratio)
return btyValue * 1e4, nil
}
// 获取最近抵押物价格
func getLatestPrice(db dbm.KV) (int64, error) {
data, err := db.Get(PriceKey())
if err != nil {
clog.Error("getLatestPrice", "get", err)
return -1, err
}
var price pty.IssuanceAssetPriceRecord
//decode
err = types.Decode(data, &price)
if err != nil {
clog.Error("getLatestPrice", "decode", err)
return -1, err
}
return price.BtyPrice, nil
}
// CheckExecAccountBalance 检查账户抵押物余额
func (action *Action) CheckExecAccountBalance(fromAddr string, ToFrozen, ToActive int64) bool {
acc := action.coinsAccount.LoadExecAccount(fromAddr, action.execaddr)
if acc.GetBalance() >= ToFrozen && acc.GetFrozen() >= ToActive {
return true
}
return false
}
// CheckExecTokenAccount 检查账户token余额
func (action *Action) CheckExecTokenAccount(addr string, amount int64, isFrozen bool) bool {
acc := action.tokenAccount.LoadExecAccount(addr, action.execaddr)
if isFrozen {
if acc.GetFrozen() >= amount {
return true
}
} else {
if acc.GetBalance() >= amount {
return true
}
}
return false
}
// IssuanceDebt 大户质押bty借出ccny
func (action *Action) IssuanceDebt(debt *pty.IssuanceDebt) (*types.Receipt, error) {
var logs []*types.ReceiptLog
var kv []*types.KeyValue
if !isSuperAddr(action.fromaddr, action.db) {
clog.Error("IssuanceDebt", "error", "IssuanceDebt need super address")
return nil, pty.ErrPermissionDeny
}
// 查找对应的借贷ID
issuance, err := queryIssuanceByID(action.db, debt.IssuanceId)
if err != nil {
clog.Error("IssuanceDebt", "IssuanceId", debt.IssuanceId, "error", err)
return nil, err
}
// 状态检查
if issuance.Status == pty.IssuanceStatusClose {
clog.Error("IssuanceDebt", "CollID", issuance.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr, "status", issuance.Status, "error", pty.ErrIssuanceStatus)
return nil, pty.ErrIssuanceStatus
}
issu := &IssuanceDB{*issuance}
// 借贷金额检查
if debt.GetValue() <= 0 {
clog.Error("IssuanceDebt", "CollID", issu.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr, "debt value", debt.GetValue(), "error", types.ErrInvalidParam)
return nil, types.ErrInvalidParam
}
// 借贷金额不超过个人限额
userBalance, _ := queryIssuanceUserBalance(action.db, action.localDB, action.fromaddr)
if debt.GetValue()+userBalance > issu.DebtCeiling {
clog.Error("IssuanceDebt", "CollID", issu.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr,
"debt value", debt.GetValue(), "current balance", userBalance, "error", pty.ErrIssuanceExceedDebtCeiling)
return nil, pty.ErrIssuanceExceedDebtCeiling
}
// 借贷金额不超过当前可借贷金额
if debt.GetValue() > issu.Balance {
clog.Error("IssuanceDebt", "CollID", issu.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr, "debt value", debt.GetValue(), "error", pty.ErrIssuanceLowBalance)
return nil, pty.ErrIssuanceLowBalance
}
clog.Debug("IssuanceDebt", "value", debt.GetValue())
// 获取抵押物价格
lastPrice, err := getLatestPrice(action.db)
if err != nil {
clog.Error("IssuanceDebt.getLatestPrice", "CollID", issu.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr, "error", err)
return nil, err
}
// 精度转换 #1024
// 先将token由token精度转成精度8
valueReal := debt.GetValue()
cfg := action.Issuance.GetAPI().GetConfig()
if cfg.IsDappFork(action.Issuance.GetHeight(), pty.IssuanceX, pty.ForkIssuancePrecision) {
precisionNum := int(math.Log10(float64(cfg.GetTokenPrecision())))
valueReal = decimal.NewFromInt(valueReal).Shift(int32(-precisionNum)).Shift(8).IntPart()
}
// 根据价格和需要借贷的金额,计算需要质押的抵押物数量
btyFrozen, err := getBtyNumToFrozen(valueReal, lastPrice, issu.LiquidationRatio)
if err != nil {
clog.Error("IssuanceDebt.getBtyNumToFrozen", "CollID", issu.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr, "error", err)
return nil, err
}
// 再将bty由精度8转成coins精度
if cfg.IsDappFork(action.Issuance.GetHeight(), pty.IssuanceX, pty.ForkIssuancePrecision) {
precisionNum := int(math.Log10(float64(cfg.GetCoinPrecision())))
btyFrozen = decimal.NewFromInt(btyFrozen).Shift(-8).Shift(int32(precisionNum)).IntPart()
}
// 检查抵押物账户余额
if !action.CheckExecAccountBalance(action.fromaddr, btyFrozen, 0) {
clog.Error("IssuanceDebt.CheckExecAccountBalance", "CollID", issu.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr, "btyFrozen", btyFrozen, "error", types.ErrNoBalance)
return nil, types.ErrNoBalance
}
// 抵押物转账
receipt, err := action.coinsAccount.ExecTransfer(action.fromaddr, issu.IssuerAddr, action.execaddr, btyFrozen)
if err != nil {
clog.Error("IssuanceDebt.ExecTransfer", "addr", action.fromaddr, "execaddr", action.execaddr, "amount", btyFrozen)
return nil, err
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
// 抵押物冻结
receipt, err = action.coinsAccount.ExecFrozen(issu.IssuerAddr, action.execaddr, btyFrozen)
if err != nil {
clog.Error("IssuanceDebt.Frozen", "addr", issu.IssuerAddr, "execaddr", action.execaddr, "amount", btyFrozen)
return nil, err
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
// 借出ccny
receipt, err = action.tokenAccount.ExecTransferFrozen(issu.IssuerAddr, action.fromaddr, action.execaddr, debt.Value)
if err != nil {
clog.Error("IssuanceDebt.ExecTokenTransfer", "addr", action.fromaddr, "execaddr", action.execaddr, "amount", debt.Value)
return nil, err
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
// 构造借出记录
debtRecord := &pty.DebtRecord{}
debtRecord.AccountAddr = action.fromaddr
debtRecord.DebtId = common.ToHex(action.txhash)
debtRecord.IssuId = issu.IssuanceId
debtRecord.CollateralValue = btyFrozen
debtRecord.StartTime = action.blocktime
debtRecord.CollateralPrice = lastPrice
debtRecord.DebtValue = debt.Value
debtRecord.LiquidationPrice = (issu.LiquidationRatio * lastPrice * pty.IssuancePreLiquidationRatio) / 1e8
debtRecord.Status = pty.IssuanceUserStatusCreate
debtRecord.ExpireTime = action.blocktime + issu.Period
// 记录当前借贷的最高自动清算价格
if issu.LatestLiquidationPrice < debtRecord.LiquidationPrice {
issu.LatestLiquidationPrice = debtRecord.LiquidationPrice
}
// 保存
issu.DebtRecords = append(issu.DebtRecords, debtRecord)
issu.CollateralValue += btyFrozen
issu.DebtValue += debt.Value
issu.Balance -= debt.Value
issu.LatestExpireTime = getLatestExpireTime(&issu.Issuance)
issu.Save(action.db)
kv = append(kv, issu.GetKVSet()...)
receiptLog := action.GetDebtReceiptLog(&issu.Issuance, debtRecord)
logs = append(logs, receiptLog)
receipt = &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
// IssuanceRepay 用户主动清算
func (action *Action) IssuanceRepay(repay *pty.IssuanceRepay) (*types.Receipt, error) {
var logs []*types.ReceiptLog
var kv []*types.KeyValue
var receipt *types.Receipt
// 找到相应的借贷
issuance, err := queryIssuanceByID(action.db, repay.IssuanceId)
if err != nil {
clog.Error("IssuanceRepay", "CollID", repay.IssuanceId, "error", err)
return nil, err
}
issu := &IssuanceDB{*issuance}
// 状态检查
if issu.Status != pty.IssuanceStatusCreated {
clog.Error("IssuanceRepay", "CollID", repay.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr, "error", "status error", "Status", issu.Status)
return nil, pty.ErrIssuanceStatus
}
// 查找借出记录
var debtRecord *pty.DebtRecord
var index int
for i, record := range issu.DebtRecords {
if record.DebtId == repay.DebtId {
debtRecord = record
index = i
break
}
}
if debtRecord == nil {
clog.Error("IssuanceRepay", "CollID", repay.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr, "error", "Can not find debt record")
return nil, pty.ErrRecordNotExist
}
// 检查
if !action.CheckExecTokenAccount(action.fromaddr, debtRecord.DebtValue, false) {
clog.Error("IssuanceRepay", "CollID", issu.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr, "amount", debtRecord.DebtValue, "error", types.ErrInsufficientBalance)
return nil, types.ErrNoBalance
}
// ccny转移
receipt, err = action.tokenAccount.ExecTransfer(action.fromaddr, issu.IssuerAddr, action.execaddr, debtRecord.DebtValue)
if err != nil {
clog.Error("IssuanceRepay.ExecTokenTransfer", "addr", action.fromaddr, "execaddr", action.execaddr, "amount", debtRecord.DebtValue)
return nil, err
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
// 冻结ccny
receipt, err = action.tokenAccount.ExecFrozen(issu.IssuerAddr, action.execaddr, debtRecord.DebtValue)
if err != nil {
clog.Error("IssuanceCreate.Frozen", "addr", action.fromaddr, "execaddr", action.execaddr, "amount", debtRecord.DebtValue)
return nil, err
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
// 抵押物归还
receipt, err = action.coinsAccount.ExecTransferFrozen(issu.IssuerAddr, action.fromaddr, action.execaddr, debtRecord.CollateralValue)
if err != nil {
clog.Error("IssuanceRepay.ExecTransferFrozen", "addr", issu.IssuerAddr, "execaddr", action.execaddr, "amount", debtRecord.CollateralValue)
return nil, err
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
// 借贷记录关闭
debtRecord.PreStatus = debtRecord.Status
debtRecord.Status = pty.IssuanceUserStatusClose
// 保存
issu.Balance += debtRecord.DebtValue
issu.CollateralValue -= debtRecord.CollateralValue
issu.DebtValue -= debtRecord.DebtValue
issu.DebtRecords = append(issu.DebtRecords[:index], issu.DebtRecords[index+1:]...)
issu.InvalidRecords = append(issu.InvalidRecords, debtRecord)
issu.LatestLiquidationPrice = getLatestLiquidationPrice(&issu.Issuance)
issu.LatestExpireTime = getLatestExpireTime(&issu.Issuance)
issu.Save(action.db)
kv = append(kv, issu.GetKVSet()...)
receiptLog := action.GetRepayReceiptLog(&issu.Issuance, debtRecord)
logs = append(logs, receiptLog)
receipt = &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
func removeLiquidateRecord(debtRecords []*pty.DebtRecord, remove pty.DebtRecord) []*pty.DebtRecord {
for index, record := range debtRecords {
if record.DebtId == remove.DebtId {
debtRecords = append(debtRecords[:index], debtRecords[index+1:]...)
break
}
}
return debtRecords
}
// 系统清算
func (action *Action) systemLiquidation(issu *pty.Issuance, price int64) (*types.Receipt, error) {
var logs []*types.ReceiptLog
var kv []*types.KeyValue
var removeRecord []*pty.DebtRecord
for _, debtRecord := range issu.DebtRecords {
if (debtRecord.LiquidationPrice*PriceWarningRate)/1e4 < price {
// 价格恢复,告警记录恢复
if debtRecord.Status == pty.IssuanceUserStatusWarning {
debtRecord.PreStatus = debtRecord.Status
debtRecord.Status = pty.IssuanceUserStatusCreate
log := action.GetFeedReceiptLog(issu, debtRecord)
logs = append(logs, log)
}
continue
}
// 价格低于清算线,记录清算
if debtRecord.LiquidationPrice >= price {
// 价格低于清算线,记录清算
clog.Debug("systemLiquidation", "issuance id", debtRecord.IssuId, "record id", debtRecord.DebtId, "account", debtRecord.AccountAddr, "price", price)
getGuarantorAddr, err := getGuarantorAddr(action.db)
if err != nil {
if err != nil {
clog.Error("systemLiquidation", "getGuarantorAddr", err)
continue
}
}
// 抵押物转移
receipt, err := action.coinsAccount.ExecTransferFrozen(issu.IssuerAddr, getGuarantorAddr, action.execaddr, debtRecord.CollateralValue)
if err != nil {
clog.Error("systemLiquidation", "addr", action.fromaddr, "execaddr", action.execaddr, "amount", debtRecord.CollateralValue, "error", err)
continue
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
// 借贷记录清算
debtRecord.LiquidateTime = action.blocktime
debtRecord.PreStatus = debtRecord.Status
debtRecord.Status = pty.IssuanceUserStatusSystemLiquidate
issu.InvalidRecords = append(issu.InvalidRecords, debtRecord)
removeRecord = append(removeRecord, debtRecord)
log := action.GetFeedReceiptLog(issu, debtRecord)
logs = append(logs, log)
continue
}
// 价格高于清算线,且还不处于告警状态,记录告警
if debtRecord.Status != pty.IssuanceUserStatusWarning {
debtRecord.PreStatus = debtRecord.Status
debtRecord.Status = pty.IssuanceUserStatusWarning
log := action.GetFeedReceiptLog(issu, debtRecord)
logs = append(logs, log)
}
}
// 删除被清算的记录
for _, record := range removeRecord {
issu.DebtRecords = removeLiquidateRecord(issu.DebtRecords, *record)
}
// 保存
issu.LatestLiquidationPrice = getLatestLiquidationPrice(issu)
issu.LatestExpireTime = getLatestExpireTime(issu)
collDB := &IssuanceDB{*issu}
collDB.Save(action.db)
kv = append(kv, collDB.GetKVSet()...)
receipt := &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
// 超时清算
func (action *Action) expireLiquidation(issu *pty.Issuance) (*types.Receipt, error) {
var logs []*types.ReceiptLog
var kv []*types.KeyValue
var removeRecord []*pty.DebtRecord
for _, debtRecord := range issu.DebtRecords {
if debtRecord.ExpireTime-ExpireWarningTime > action.blocktime {
continue
}
// 超过超时时间,记录清算
if debtRecord.ExpireTime <= action.blocktime {
// 超过清算线,记录清算
clog.Debug("expireLiquidation", "issuance id", debtRecord.IssuId, "record id", debtRecord.DebtId, "account", debtRecord.AccountAddr, "time", action.blocktime)
getGuarantorAddr, err := getGuarantorAddr(action.db)
if err != nil {
if err != nil {
clog.Error("expireLiquidation", "getGuarantorAddr", err)
continue
}
}
// 抵押物转移
receipt, err := action.coinsAccount.ExecTransferFrozen(issu.IssuerAddr, getGuarantorAddr, action.execaddr, debtRecord.CollateralValue)
if err != nil {
clog.Error("expireLiquidation", "addr", action.fromaddr, "execaddr", action.execaddr, "amount", debtRecord.CollateralValue, "error", err)
continue
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
// 借贷记录清算
debtRecord.LiquidateTime = action.blocktime
debtRecord.PreStatus = debtRecord.Status
debtRecord.Status = pty.IssuanceUserStatusExpireLiquidate
issu.InvalidRecords = append(issu.InvalidRecords, debtRecord)
removeRecord = append(removeRecord, debtRecord)
log := action.GetFeedReceiptLog(issu, debtRecord)
logs = append(logs, log)
continue
}
// 还没记录超时告警,记录告警
if debtRecord.Status != pty.IssuanceUserStatusExpire {
debtRecord.PreStatus = debtRecord.Status
debtRecord.Status = pty.IssuanceUserStatusExpire
log := action.GetFeedReceiptLog(issu, debtRecord)
logs = append(logs, log)
}
}
// 删除被清算的记录
for _, record := range removeRecord {
issu.DebtRecords = removeLiquidateRecord(issu.DebtRecords, *record)
}
// 保存
issu.LatestLiquidationPrice = getLatestLiquidationPrice(issu)
issu.LatestExpireTime = getLatestExpireTime(issu)
collDB := &IssuanceDB{*issu}
collDB.Save(action.db)
kv = append(kv, collDB.GetKVSet()...)
receipt := &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
// 价格计算策略
func pricePolicy(feed *pty.IssuanceFeed) int64 {
var totalPrice int64
var totalVolume int64
for _, volume := range feed.Volume {
totalVolume += volume
}
if totalVolume == 0 {
clog.Error("issuance price feed volume empty")
return 0
}
for i, price := range feed.Price {
totalPrice += (price * feed.Volume[i]) / totalVolume
}
return totalPrice
}
// IssuanceFeed 喂价
func (action *Action) IssuanceFeed(feed *pty.IssuanceFeed) (*types.Receipt, error) {
var logs []*types.ReceiptLog
var kv []*types.KeyValue
if feed == nil || len(feed.Price) == 0 || len(feed.Price) != len(feed.Volume) {
clog.Error("IssuancePriceFeed", types.ErrInvalidParam)
return nil, types.ErrInvalidParam
}
// 是否后台管理用户
if !isRightAddr(pty.PriceFeedKey, action.fromaddr, action.db) {
clog.Error("IssuancePriceFeed", "addr", action.fromaddr, "error", "Address has no permission to feed price")
return nil, pty.ErrPermissionDeny
}
price := pricePolicy(feed)
if price <= 0 {
clog.Error("IssuancePriceFeed", "price", price, "error", pty.ErrPriceInvalid)
return nil, pty.ErrPriceInvalid
}
ids, err := queryIssuanceByStatus(action.localDB, pty.IssuanceStatusCreated, "")
if err != nil {
clog.Debug("IssuancePriceFeed", "get issuance record error", err)
}
for _, collID := range ids {
issu, err := queryIssuanceByID(action.db, collID)
if err != nil {
clog.Error("IssuancePriceFeed", "Issuance ID", issu.IssuanceId, "get issuance record by id error", err)
continue
}
// 超时清算判断
if issu.LatestExpireTime-ExpireWarningTime <= action.blocktime {
receipt, err := action.expireLiquidation(issu)
if err != nil {
clog.Error("IssuancePriceFeed", "Issuance ID", issu.IssuanceId, "expire liquidation error", err)
continue
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
}
// 系统清算判断
receipt, err := action.systemLiquidation(issu, price)
if err != nil {
clog.Error("IssuancePriceFeed", "Issuance ID", issu.IssuanceId, "system liquidation error", err)
continue
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
}
var priceRecord pty.IssuanceAssetPriceRecord
priceRecord.BtyPrice = price
priceRecord.RecordTime = action.blocktime
// 最近喂价记录
pricekv := &types.KeyValue{Key: PriceKey(), Value: types.Encode(&priceRecord)}
action.db.Set(pricekv.Key, pricekv.Value)
kv = append(kv, pricekv)
receipt := &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
// IssuanceClose 终止借贷
func (action *Action) IssuanceClose(close *pty.IssuanceClose) (*types.Receipt, error) {
var logs []*types.ReceiptLog
var kv []*types.KeyValue
var receipt *types.Receipt
issuance, err := queryIssuanceByID(action.db, close.IssuanceId)
if err != nil {
clog.Error("IssuanceClose", "IssuanceId", close.IssuanceId, "error", err)
return nil, err
}
if action.fromaddr != issuance.IssuerAddr {
clog.Error("IssuanceClose", "IssuanceId", issuance.IssuanceId, "error", "account error", "create", issuance.IssuerAddr, "from", action.fromaddr)
return nil, pty.ErrPermissionDeny
}
for _, debtRecord := range issuance.DebtRecords {
if debtRecord.Status != pty.IssuanceUserStatusClose {
clog.Error("IssuanceClose", "IssuanceId", close.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr, "error", pty.ErrIssuanceRecordNotEmpty)
return nil, pty.ErrIssuanceRecordNotEmpty
}
}
// 解冻ccny
if issuance.Balance > 0 {
receipt, err = action.tokenAccount.ExecActive(action.fromaddr, action.execaddr, issuance.Balance)
if err != nil {
clog.Error("IssuanceClose.ExecActive", "addr", action.fromaddr, "execaddr", action.execaddr, "amount", issuance.Balance, "error", err)
return nil, err
}
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)