-
Notifications
You must be signed in to change notification settings - Fork 7
/
lambo.ride
718 lines (620 loc) · 33.8 KB
/
lambo.ride
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
{-# STDLIB_VERSION 4 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}
let SEP = "__"
func getStringOrFail(key: String) = {this.getString(key).valueOrErrorMessage("No data for this.key=" + key)}
func getBooleanOrFail(key: String) = {this.getBoolean(key).valueOrErrorMessage("No data for this.key=" + key)}
func getIntOrFail(key: String) = {this.getInteger(key).valueOrErrorMessage("No data for this.key=" + key)}
func IntE(key: String, val: Int) = {IntegerEntry(key, val)}
func StrE(key: String, val: String) = {StringEntry(key, val)}
func failExecuteGet(msg: String, baseAssetStr: String, userAddressStr: String, submitTxIdStr: String, operationType: String) = {
throw(msg + ": baseAsset=" + baseAssetStr
+ " userAddress=" + userAddressStr
+ " submitTxId=" + submitTxIdStr
+ " operation=" + operationType)
}
func failSubmitLimitsExceeds(remainingBase:Int, remainingShare:Int, newRemainingBase:Int, newRemainingShare:Int) = {
throw("submit operation limits have been reached: "
+ " remainingBaseVal=" + remainingBase.toString()
+ " remainingShareVal=" + remainingShare.toString()
+ " newRemainingBaseVal=" + newRemainingBase.toString()
+ " newRemainingShareVal=" + newRemainingShare.toString())
}
func failTopupManagerOnly(topupManagerAddress: String) = {
throw("opertion denied: only topUpManager=" + topupManagerAddress + " can send such transactions")
}
func failTopupMaxPriceDeviation(price: Int, minAllowedPrice: Int) = {
throw("topup is not allowed - max deviation from ATH price exceeds: newPrice=" + price.toString() + " minAllowedPrice=" + minAllowedPrice.toString())
}
func convertShare2Base(shareAmount: Int, price: Int, priceMult: Int) = {fraction(shareAmount, price, priceMult)}
func convertBase2Share(baseAmount: Int, price: Int, priceMult: Int) = {fraction(baseAmount, priceMult, price)}
# single key which is based on REAL base asset id
func keyAssetCfg(baseAssetStr: String) = {"%s%s%s__config__asset__" + baseAssetStr}
func keyNextInternalAssetId()
= {"%s__nextInternalAssetId"}
func keyPriceLast(innerBaseStr: String)
= {"%s%s%d__price__last__" + innerBaseStr}
func keyPriceATH(innerBaseStr: String)
= {"%s%s%d__price__ath__" + innerBaseStr}
func keyPriceByTopUpIdx(innerBaseStr: String, topUpIdx: Int)
= {makeString(["%s%s%d%d__price__byTopUpIdx", innerBaseStr, topUpIdx.toString()], SEP)}
func keyPriceHistory(innerBaseStr: String, h: Int, timestamp: Int)
= {makeString(["%s%s%d%d%d__price__history", innerBaseStr, h.toString(), timestamp.toString()], SEP)}
func keyTotalLocked(innerBaseStr: String)
= {"%s%s%d__total__locked__" + innerBaseStr}
func keyTotalLockedByUser(innerBaseStr: String, userAddressStr: String)
= {makeString(["%s%s%d%s__total__locked", innerBaseStr, userAddressStr], SEP)}
func keyMappingsInternal2baseAssetId(internalBaseAsset: Int)
= {"%s%s%d__mappings__internal2baseAssetId__" + internalBaseAsset.toString()}
func keyMappingsBaseAsset2internalId(baseAssetStr: String)
= {"%s%s%s__mappings__baseAsset2internalId__" + baseAssetStr}
func keyMappingsShare2baseAssetId(shareAssetStr: String)
= {"%s%s%s__mappings__share2baseAssetId__" + shareAssetStr}
func keyMappingsBaseAsset2shareId(baseAssetStr: String)
= {"%s%s%s__mappings__baseAsset2shareId__" + baseAssetStr}
func keyShutdownSubmitOperation(innerBaseStr: String)
= {"%s%s%d__shutdown__submit__" + innerBaseStr}
func keyShutdownManager(innerBaseStr: String)
= {"%s%s%d__shutdown__manager__" + innerBaseStr}
func keyTopUpCurrentIdx(innerBaseStr: String)
= {"%s%s%d__topup__currentIdx__" + innerBaseStr}
func keyTopUpLastHeight(innerBaseStr: String, sender: String)
= {makeString(["%s%s%s%d%s__topup__last__height", innerBaseStr, sender], SEP)}
func keyTopupMutext(innerBaseStr: String)
= {"%s%s%d__topup__mutex__" + innerBaseStr}
func keyTopupLastTimestamp(innerBaseStr: String)
= {"%s%s%s%d__topup__last__timestamp__" + innerBaseStr}
func keyTopupHistory(innerBaseStr: String, topupIdx: Int)
= {makeString(["%s%s%d%d__topup__history", innerBaseStr, topupIdx.toString()], SEP)}
func keyLimitsRemaining(innerBaseStr: String)
= {"%s%s%d__limits__remaining__" + innerBaseStr}
let IdxCfgShareAssetId = 1
let IdxCfgInternalBaseAsset = 2
let IdxCfgDecimalsMultBothAssets = 3
let IdxCfgDecimalsMultPrice = 4
let IdxCfgGetDelayBlocks = 5
let IdxCfgTopupIntervalInBlocks = 6
let IdxCfgTopupMaxNegativePart = 7
let IdxCfgTopupManagerAddress = 8
let IdxCfgSubmitLimitsBaseMax = 9
let IdxCfgSubmitLimitsBaseReset = 10
let IdxCfgSubmitLimitsShareMax = 11
let IdxCfgSubmitLimitsShareReset = 12
let IdxCfgAdminAddress = 13
#func dataAssetCfgAllStrings(
# shareAssetStr: String, innerBaseStr: String, decimalsMultBothAssets: String,
# decimalsMultPrice: String, getDelayInBlocks: String,
# topupIntervalInBlocks: String, topupMaxNegativePart: String, topupManagerAddress: String,
# submitLimitsBaseMax: String, submitLimitsBaseReset: String,
# submitLimitsShareMax: String, submitLimitsShareReset: String, adminAddress: String) = {
# makeString(["%s%d%d%d%d%d%d%s%d%d%d%d",
# shareAssetStr, # 1
# innerBaseStr, # 2
# decimalsMultBothAssets, # 3
# decimalsMultPrice, # 4
# getDelayInBlocks, # 5
# topupIntervalInBlocks, # 6
# topupMaxNegativePart, # 7
# topupManagerAddress, # 8
# submitLimitsBaseMax, # 9
# submitLimitsBaseReset, # 10
# submitLimitsShareMax, # 11
# submitLimitsShareReset, # 12
# adminAddress # 13
# ],
# SEP)
#}
func dataAssetCfg(shareAssetStr: String, innerBaseStr: String, decimalsMultBothAssets: Int,
decimalsMultPrice: Int, getDelayInBlocks: Int,
topupIntervalInBlocks: Int, topupMaxNegativePart: Int, topupManagerAddress: String,
submitLimitsBaseMax: Int, submitLimitsBaseReset: Int,
submitLimitsShareMax: Int, submitLimitsShareReset: Int, adminAddress: String) = {
makeString(["%s%d%d%d%d%d%d%s%d%d%d%d",
shareAssetStr, # 1
innerBaseStr, # 2
decimalsMultBothAssets.toString(), # 3
decimalsMultPrice.toString(), # 4
getDelayInBlocks.toString(), # 5
topupIntervalInBlocks.toString(), # 6
topupMaxNegativePart.toString(), # 7
topupManagerAddress, # 8
submitLimitsBaseMax.toString(), # 9
submitLimitsBaseReset.toString(), # 10
submitLimitsShareMax.toString(), # 11
submitLimitsShareReset.toString(), # 12
adminAddress # 13
],
SEP)
}
let IdxTotalLockedInShare = 1
let IdxTotalLockedOutBase = 2
let IdxTotalLockedInBase = 3
let IdxTotalLockedOutShare = 4
func dataTotalLocked(inShareAmount: Int, outBaseAmount: Int, inBaseAmount: Int, outShareAmount: Int) = {
makeString(["%d%d%d%d", # 0
inShareAmount.toString(), # 1
outBaseAmount.toString(), # 2
inBaseAmount.toString(), # 3
outShareAmount.toString() # 4
], SEP)
}
func dataTotalLockedInt(inShareAmount: Int, outBaseAmount: Int, inBaseAmount: Int, outShareAmount: Int) = {
[ -1, # 0
inShareAmount, # 1
outBaseAmount, # 2
inBaseAmount, # 3
outShareAmount # 4
]
}
func readTotalLocked(key: String) = {
let totalLockedArray = this.getString(key).valueOrElse(dataTotalLocked(0, 0, 0, 0))
.split(SEP)
dataTotalLockedInt(
totalLockedArray[IdxTotalLockedInShare].parseIntValue(),
totalLockedArray[IdxTotalLockedOutBase].parseIntValue(),
totalLockedArray[IdxTotalLockedInBase].parseIntValue(),
totalLockedArray[IdxTotalLockedOutShare].parseIntValue()
)
}
# @returns {$totalDiff, $userDiff, $outAmount, $outAssetId, $isLockedByHeight}
func calcTotalLockedDiff(direction: String, operationType: String, innerBaseStr: String, price: Int, priceMult: Int, inAmount: Int, baseAssetId: ByteVector, shareAssetId: ByteVector) = {
let t = direction + operationType
let emptyVect = "".fromBase58String()
if (t == "submitP") then {
let totalDiff = dataTotalLockedInt(0, 0, inAmount, 0)
let userDiff = totalDiff
(totalDiff, userDiff, 0, emptyVect, false)
}
else if (t == "submitG") then {
let totalDiff = dataTotalLockedInt(inAmount, 0, 0, 0)
let userDiff = totalDiff
(totalDiff, userDiff, 0, emptyVect, true)
}
else if (t == "executeP") then {
let outAmount = convertBase2Share(inAmount, price, priceMult)
let totalDiff = dataTotalLockedInt(0, 0, 0, outAmount)
let userDiff = dataTotalLockedInt(0, 0, inAmount, 0)
(totalDiff, userDiff, outAmount, shareAssetId, false)
}
else if (t == "executeG") then {
let outAmount = convertShare2Base(inAmount, price, priceMult)
let totalDiff = dataTotalLockedInt(0, outAmount, 0, 0)
let userDiff = dataTotalLockedInt(inAmount, 0, 0, 0)
(totalDiff, userDiff, outAmount, baseAssetId, false)
}
else if (t == "topup") then {
let totalLockedArray = readTotalLocked(keyTotalLocked(innerBaseStr))
let totalLockedInBaseAmount = totalLockedArray[IdxTotalLockedInBase]
let totalLockedInShareAmount = totalLockedArray[IdxTotalLockedInShare]
let totalDiff = dataTotalLockedInt(
totalLockedInShareAmount,
-1*convertShare2Base(totalLockedInShareAmount, price, priceMult),
totalLockedInBaseAmount,
-1*convertBase2Share(totalLockedInBaseAmount, price, priceMult))
(totalDiff, [], 0, emptyVect, false)
}
else throw("Unsupported Type " + t)
}
func TotalLockedStringEntry(action: String, key: String, diff: List[Int]) = {
func UPDATE(a: Int, b: Int) = {
if (action == "INCREMENT") then a + b else
if (action == "DECREMENT") then a - b else
throw("Unsupported action " + action)
}
let dataArray = readTotalLocked(key)
StrE(key,
dataTotalLocked(
UPDATE(dataArray[IdxTotalLockedInShare], diff[IdxTotalLockedInShare]),
UPDATE(dataArray[IdxTotalLockedOutBase], diff[IdxTotalLockedOutBase]),
UPDATE(dataArray[IdxTotalLockedInBase], diff[IdxTotalLockedInBase]),
UPDATE(dataArray[IdxTotalLockedOutShare], diff[IdxTotalLockedOutShare])
)
)
}
func keyOperation(operationType: String, innerBaseStr: String, userAddress: String, txId: String) = {
makeString(["%s%d%s%s", operationType, innerBaseStr, userAddress, txId], SEP)
}
let IdxOperStatus = 1
let IdxOperInAmount = 2
let IdxOperPrice = 3
let IdxOperOutAmount = 4
let IdxOperStartHeight = 5
let IdxOperStartTimestamp = 6
let IdxOperEndHeight = 7
let IdxOperEndTimestamp = 8
let IdxOperTopupUnlockIdx = 9
func privateDataOperationAllStrings(status: String, inAssetAmount: String, price: String, outAssetAmount: String,
startHeight: String, startTimestamp: String, endHeight: String, endTimestamp: String, lock: String) = {
makeString(["%s%d%d%d%d%d%d%d%d",
status, # 1
inAssetAmount, # 2
price, # 3
outAssetAmount, # 4
startHeight, # 5
startTimestamp, # 6
endHeight, # 7
endTimestamp, # 8
lock # 9
],
SEP)
}
func dataOperation(status: String, inAssetAmount: Int, price: Int, outAssetAmount: Int,
startHeight: Int, startTimestamp: Int, endHeight: Int, endTimestamp: Int, topupUnlockIdx: Int) = {
privateDataOperationAllStrings(
status, # 1
inAssetAmount.toString(), # 2
price.toString(), # 3
outAssetAmount.toString(), # 4
startHeight.toString(), # 5
startTimestamp.toString(), # 6
endHeight.toString(), # 7
endTimestamp.toString(), # 8
topupUnlockIdx.toString() # 9
)
}
func dataOperationExecutionUpdate(currOperArray: List[String], newStatus: String, newPrice: Int, newOutAmount: Int) = {
privateDataOperationAllStrings(
newStatus,
currOperArray[IdxOperInAmount],
newPrice.toString(),
newOutAmount.toString(),
currOperArray[IdxOperStartHeight],
currOperArray[IdxOperStartTimestamp],
height.toString(),
lastBlock.timestamp.toString(),
currOperArray[IdxOperTopupUnlockIdx]
)
}
func readAssetCfgOrFail(baseAssetStr: String) = {
let key = keyAssetCfg(baseAssetStr)
getStringOrFail(key)
.split(SEP)
}
let IdxLimitsRemainingBase = 1
let IdxLimitsRemainingShare = 2
func RemainingLimitsStringEntry(key:String, baseRemainingLimit:Int, shareRemainingLimit:Int) = {
StrE(key,
makeString(["%d%d", baseRemainingLimit.toString(), shareRemainingLimit.toString()], SEP)
)
}
func TopupMutexIntEntry(innerBaseStr:String, acquiredHeight:Int) = {
IntE(keyTopupMutext(innerBaseStr), acquiredHeight)
}
func genericCalcPrice(innerBaseStr: String, baseAssetId: ByteVector, topUpBaseAmount: Int, shareAssetId: ByteVector, decimalsMultPrice: Int) = {
let totalLockedArray = readTotalLocked(keyTotalLocked(innerBaseStr))
let totalLockedOutBaseAmount = totalLockedArray[IdxTotalLockedOutBase]
let currIterTotalInBaseAmount = totalLockedArray[IdxTotalLockedInBase]
let baseAssetBalance = this.assetBalance(baseAssetId)
# base Asset Balance Without Completed Operations
let baseAssetBalanceWCO = baseAssetBalance + topUpBaseAmount - currIterTotalInBaseAmount - totalLockedOutBaseAmount
let totalLockedOutShareAmount = totalLockedArray[IdxTotalLockedOutShare]
let currIterTotalInShareAmount = totalLockedArray[IdxTotalLockedInShare]
let shareEmission = assetInfo(shareAssetId).value().quantity
if (baseAssetBalanceWCO < 0) then throw("baseAssetBalanceWco < 0: baseAssettBalance=" + baseAssetBalance.toString() + " baseAssetBalanceWco=" + baseAssetBalanceWCO.toString()) else
# TODO consider to ROUNDUP
let lastPrice = getIntOrFail(keyPriceLast(innerBaseStr))
let price = if (shareEmission == 0) then lastPrice else fraction(baseAssetBalanceWCO, decimalsMultPrice, shareEmission)
# TODO modify returned result
(price, baseAssetBalance, -1, baseAssetBalanceWCO, shareEmission, currIterTotalInBaseAmount, currIterTotalInShareAmount, totalLockedOutBaseAmount, totalLockedOutShareAmount)
}
func calcPrice(innerBaseStr: String, baseAssetId: ByteVector, shareAssetId: ByteVector, decimalsMultPrice: Int) = {
genericCalcPrice(innerBaseStr, baseAssetId, 0, shareAssetId, decimalsMultPrice)
}
func commonSubmit(operationType: String, i: Invocation, inAmount: Int, inAssetId: ByteVector, baseAssetStr: String) = {
let inAssetStr = inAssetId.toBase58String()
let userAddressStr = i.caller.toString()
let baseAssetId = baseAssetStr.fromBase58String()
let cfgArray = readAssetCfgOrFail(baseAssetStr)
let shareAssetStr = cfgArray[IdxCfgShareAssetId]
let shareAssetId = shareAssetStr.fromBase58String()
let decimalsMultBothAssets = cfgArray[IdxCfgDecimalsMultBothAssets].parseIntValue()
let innerBaseStr = cfgArray[IdxCfgInternalBaseAsset]
let getDelayBlocks = cfgArray[IdxCfgGetDelayBlocks].parseIntValue()
let limitsKEY = keyLimitsRemaining(innerBaseStr)
let limitsCfgArray = getStringOrFail(limitsKEY).split(SEP)
let limitsRemainingBase = limitsCfgArray[IdxLimitsRemainingBase].parseIntValue()
let limitsRemainingShare = limitsCfgArray[IdxLimitsRemainingShare].parseIntValue()
let isSubmitBlocked = this.getBoolean(keyShutdownSubmitOperation(innerBaseStr)).valueOrElse(false)
if (isSubmitBlocked) then throw("submit operation is blocked") else
let operationsMutex = this.getInteger(keyTopupMutext(innerBaseStr)).valueOrElse(0)
if (operationsMutex + 60 > height) then throw("submit operations are blocked by topup manager") else
let diffTuple = calcTotalLockedDiff("submit", operationType, innerBaseStr, 0, 0, inAmount, baseAssetId, shareAssetId)
let limitsRemainingBaseNew = limitsRemainingBase - diffTuple._2[IdxTotalLockedInBase]
let limitsRemainingShareNew = limitsRemainingShare - diffTuple._2[IdxTotalLockedInShare]
if (limitsRemainingBaseNew < 0 || limitsRemainingShareNew < 0) then failSubmitLimitsExceeds(limitsRemainingBase, limitsRemainingShare, limitsRemainingBaseNew, limitsRemainingShareNew) else
let topUpCurrentIdx = getIntOrFail(keyTopUpCurrentIdx(innerBaseStr))
let endHeight = if (diffTuple._5) then height + getDelayBlocks else height
[StrE(
keyOperation(operationType, innerBaseStr, userAddressStr, i.transactionId.toBase58String()),
dataOperation("PENDING", inAmount, 0, 0, height, lastBlock.timestamp, endHeight, 0, topUpCurrentIdx + 1))
]
:+ TotalLockedStringEntry("INCREMENT", keyTotalLocked(innerBaseStr), diffTuple._1)
:+ TotalLockedStringEntry("INCREMENT", keyTotalLockedByUser(innerBaseStr, userAddressStr), diffTuple._2)
:+ RemainingLimitsStringEntry(limitsKEY, limitsRemainingBaseNew, limitsRemainingShareNew)
}
func commonExecute(operationType: String, baseAssetStr: String, userAddressStr: String, submitTxIdStr: String) = {
let userAddress = addressFromStringValue(userAddressStr)
let assetCfgArray = readAssetCfgOrFail(baseAssetStr)
let shareAssetId = assetCfgArray[IdxCfgShareAssetId].fromBase58String()
let innerBaseStr = assetCfgArray[IdxCfgInternalBaseAsset]
let decimalsMultPrice = assetCfgArray[IdxCfgDecimalsMultPrice].parseIntValue()
let baseAssetId = baseAssetStr.fromBase58String()
let opKey = keyOperation(operationType, innerBaseStr, userAddressStr, submitTxIdStr)
let opArray = getStringOrFail(opKey)
.split(SEP)
let status = opArray[IdxOperStatus]
let inAmount = opArray[IdxOperInAmount].parseIntValue()
let topupUnlockIdx = opArray[IdxOperTopupUnlockIdx].parseIntValue()
let unlockHeight = opArray[IdxOperEndHeight].parseIntValue()
let currTopUpIdx = getIntOrFail(keyTopUpCurrentIdx(innerBaseStr))
let priceByTopUpId = getIntOrFail(keyPriceByTopUpIdx(innerBaseStr, topupUnlockIdx))
if (status != "PENDING") then failExecuteGet("Status is not PENDING", baseAssetStr, userAddressStr, submitTxIdStr, operationType) else
if (currTopUpIdx < topupUnlockIdx) then failExecuteGet("OperLock[" + topupUnlockIdx.toString() + "] > " + currTopUpIdx.toString(), baseAssetStr, userAddressStr, submitTxIdStr, operationType) else
if (height < unlockHeight) then failExecuteGet("OperHeightLock[" + unlockHeight.toString() + "] > " + height.toString(), baseAssetStr, userAddressStr, submitTxIdStr, operationType) else
let diffTuple = calcTotalLockedDiff("execute", operationType, innerBaseStr, priceByTopUpId, decimalsMultPrice, inAmount, baseAssetId, shareAssetId)
let outAmount = diffTuple._3
let outTransferData =
if (diffTuple._4 == baseAssetId)
then [ScriptTransfer(userAddress, outAmount, baseAssetId)]
else [ScriptTransfer(userAddress, outAmount, shareAssetId)]
outTransferData
:+ StrE(opKey,
dataOperationExecutionUpdate(opArray, "FINISHED", priceByTopUpId, outAmount))
:+ TotalLockedStringEntry("DECREMENT", keyTotalLocked(innerBaseStr), diffTuple._1)
:+ TotalLockedStringEntry("DECREMENT", keyTotalLockedByUser(innerBaseStr, userAddressStr), diffTuple._2)
}
# read only to provide data
#@Callable - workaround to disable minification
func privateCurrentSysParamsREST(baseAssetStr: String) = {
let baseAssetId = baseAssetStr.fromBase58String()
let cfgArray = readAssetCfgOrFail(baseAssetStr)
let shareAssetStr = cfgArray[IdxCfgShareAssetId]
let shareAssetId = shareAssetStr.fromBase58String()
let decimalsMultBothAssetsVal = cfgArray[IdxCfgDecimalsMultBothAssets].parseIntValue()
let decimalsMultPriceVal = cfgArray[IdxCfgDecimalsMultPrice].parseIntValue()
let innerBaseStr = cfgArray[IdxCfgInternalBaseAsset]
let priceAthKEY = keyPriceATH(innerBaseStr)
let priceAthVal = this.getInteger(priceAthKEY).valueOrElse(0)
let priceLastKEY = keyPriceLast(innerBaseStr)
let priceLastVal = this.getInteger(priceLastKEY).valueOrElse(0)
let topupLastTimeKEY = keyTopupLastTimestamp(innerBaseStr)
let topupLastTimeVal = this.getInteger(topupLastTimeKEY).valueOrElse(0)
# (price, decimalsMultPrice, baseAssetBalance, -1, baseAssetBalanceWCO, shareEmission, currIterTotalInBaseAmount, currIterTotalInShareAmount, totalLockedOutBaseAmount, totalLockedOutShareAmount, decimalsMultBothAssets, priceATH)
let sysState = calcPrice(innerBaseStr, baseAssetId, shareAssetId, decimalsMultPriceVal)
(
IntE("price", priceLastVal),
IntE("decimalsMultPrice", decimalsMultPriceVal),
IntE("baseAssetBalance", sysState._2),
IntE("-1", sysState._3),
IntE("baseAssetBalanceWCO", sysState._4),
IntE("shareEmission", sysState._5),
IntE("currIterTotalInBaseAmount", sysState._6),
IntE("currIterTotalInShareAmount", sysState._7),
IntE("totalLockedOutBaseAmount", sysState._8),
IntE("totalLockedOutShareAmount", sysState._9),
IntE("decimalsMultBothAssets", decimalsMultBothAssetsVal),
IntE("priceATH", priceAthVal),
IntE("priceRecalculated", sysState._1),
IntE("topupLastTimestamp", topupLastTimeVal)
)
}
@Callable(i)
func adminRegisterAsset(baseAssetStr: String, shareAssetName: String, shareAssetDescr: String,
getDelayinBlocks: Int, shutdownManagerAddress: String, startPrice: Int,
topupIntervalInBlocks: Int, topupMaxNegativePart: Int, topupManagerAddress: String,
submitLimitsBaseMax: Int, submitLimitsBaseReset: Int,
submitLimitsShareMax: Int, submitLimitsShareReset: Int, adminAddress: String) = {
# TODO submitLimitsBaseMax and submitLimitsShareMax can be < 0
let baseAssetId = baseAssetStr.fromBase58String()
let bothAssetsDecimals = assetInfo(baseAssetId).value().decimals
let decimalsMultBothAssets = pow(10, 0, bothAssetsDecimals, 0, 0, DOWN)
let decimalsMultPrice = 100 * 1000 * 1000 # 10^8
let topupMaxNegativePercents = fraction(topupMaxNegativePart, 100, decimalsMultBothAssets)
let baseAssetBalance = this.assetBalance(baseAssetId)
# validate admin public key - in our case contract PK
if (i.caller != this) then throw("permissions denied") else
if (baseAssetBalance == 0) then throw(this.toString() + " must have any initial balance of " + baseAssetStr) else
if (this.getString(keyAssetCfg(baseAssetStr)).isDefined()) then throw(baseAssetStr + " has been already registered") else
if (addressFromStringValue(shutdownManagerAddress).toString() != shutdownManagerAddress) then throw("invalid shutdownManagerAddress") else
if (addressFromStringValue(topupManagerAddress).toString() != topupManagerAddress) then throw("invalid topupManagerAddress") else
if (getDelayinBlocks < 0) then throw("invalid getDelayinBlocks=" + getDelayinBlocks.toString()) else
if (topupMaxNegativePercents <= 0 || topupMaxNegativePercents >= 99) then throw("invalid topupMaxNegativePart parameter") else
let shareInitAmount = convertBase2Share(baseAssetBalance, startPrice, decimalsMultPrice)
let shareAssetIssueAction = Issue(shareAssetName, shareAssetDescr, shareInitAmount, bothAssetsDecimals, true)
let shareAssetId = shareAssetIssueAction.calculateAssetId()
let shareAssetStr = shareAssetId.toBase58String()
let internalBaseAssetId = this.getInteger(keyNextInternalAssetId()).valueOrElse(0)
let innerBaseStr = internalBaseAssetId.toString()
[
StrE(keyAssetCfg(baseAssetStr),
dataAssetCfg(shareAssetStr,
innerBaseStr,
decimalsMultBothAssets,
decimalsMultPrice,
getDelayinBlocks,
topupIntervalInBlocks,
topupMaxNegativePart,
topupManagerAddress,
submitLimitsBaseMax,
submitLimitsBaseReset,
submitLimitsShareMax,
submitLimitsShareReset,
adminAddress)),
StrE(keyMappingsInternal2baseAssetId(internalBaseAssetId), baseAssetStr),
StrE(keyMappingsBaseAsset2internalId(baseAssetStr), innerBaseStr),
StrE(keyMappingsShare2baseAssetId(shareAssetStr), baseAssetStr),
StrE(keyMappingsBaseAsset2shareId(baseAssetStr), shareAssetStr),
BooleanEntry(keyShutdownSubmitOperation(innerBaseStr), false),
StrE(keyShutdownManager(innerBaseStr), shutdownManagerAddress),
IntE(keyNextInternalAssetId(), internalBaseAssetId + 1),
IntE(keyPriceLast(innerBaseStr), startPrice),
IntE(keyPriceATH(innerBaseStr), startPrice),
IntE(keyPriceHistory(innerBaseStr, height, lastBlock.timestamp), startPrice),
IntE(keyTopUpCurrentIdx(innerBaseStr), 0),
RemainingLimitsStringEntry(keyLimitsRemaining(innerBaseStr), submitLimitsBaseMax, submitLimitsShareMax),
shareAssetIssueAction,
ScriptTransfer(topupManagerAddress.addressFromStringValue(), shareInitAmount, shareAssetId)
]
}
#@Callable(i)
#func adminUpdateCfg(baseAssetStr: String, updateCfgParamIdx: Int, newCfgParamVal: String) = {
# let cfgArray = readAssetCfgOrFail(baseAssetStr)
# let adminAddress = cfgArray[IdxCfgAdminAddress]
# if (i.caller.toString() != adminAddress) then throw("permissioned denied") else
# func UpdateOrKeep(idx: Int) = {if (idx == updateCfgParamIdx) then newCfgParamVal else cfgArray[idx]}
# let newCfg = dataAssetCfgAllStrings(
# UpdateOrKeep(IdxCfgShareAssetId), # 1
# UpdateOrKeep(IdxCfgInternalBaseAsset), # 2
# UpdateOrKeep(IdxCfgDecimalsMultBothAssets), # 3
# UpdateOrKeep(IdxCfgDecimalsMultPrice), # 4
# UpdateOrKeep(IdxCfgGetDelayBlocks), # 5
# UpdateOrKeep(IdxCfgTopupIntervalInBlocks), # 6
# UpdateOrKeep(IdxCfgTopupMaxNegativePart), # 7
# UpdateOrKeep(IdxCfgTopupManagerAddress), # 8
# UpdateOrKeep(IdxCfgSubmitLimitsBaseMax), # 9
# UpdateOrKeep(IdxCfgSubmitLimitsBaseReset), # 10
# UpdateOrKeep(IdxCfgSubmitLimitsShareMax), # 11
# UpdateOrKeep(IdxCfgSubmitLimitsShareReset), # 12
# UpdateOrKeep(IdxCfgAdminAddress) # 13
# )
# [StringEntry(keyAssetCfg(baseAssetStr), newCfg)]
#}
@Callable(i)
func shutdownSubmits(internalBaseAssetId: Int) = {
let internalBaseAssetIdStr = internalBaseAssetId.toString()
let baseAssetIdStr = getStringOrFail(keyMappingsInternal2baseAssetId(internalBaseAssetId))
let shutdownManagerAddress = getStringOrFail(keyShutdownManager(internalBaseAssetIdStr))
if (baseAssetIdStr.size() < 1) then throw("invalid internalBaseAssetId") else
if (i.caller.toString() != shutdownManagerAddress) then throw("access denied") else
[BooleanEntry(keyShutdownSubmitOperation(internalBaseAssetId.toString()), true)]
}
@Callable(i)
func submitPut() = {
let pmt = i.payments[0].value()
let inAmount = pmt.amount
let inAssetId = pmt.assetId.value()
let baseAssetStr = inAssetId.toBase58String()
commonSubmit("P", i, inAmount, inAssetId, baseAssetStr)
}
@Callable(i)
func submitGet() = {
let pmt = i.payments[0].value()
let inAmount = pmt.amount
let inAssetId = pmt.assetId.value()
let shareAssetStr = inAssetId.toBase58String()
let baseAssetStr = getStringOrFail(keyMappingsShare2baseAssetId(shareAssetStr))
commonSubmit("G", i, inAmount, inAssetId, baseAssetStr)
}
@Callable(i)
func executePut(baseAssetStr: String, userAddressStr: String, submitTxIdStr: String) = {
commonExecute("P", baseAssetStr, userAddressStr, submitTxIdStr)
}
@Callable(i)
func executeGet(baseAssetStr: String, userAddressStr: String, submitTxIdStr: String) = {
commonExecute("G", baseAssetStr, userAddressStr, submitTxIdStr)
}
@Callable(i)
func operationsMutex(baseAssetStr: String) = {
let assetCfgArray = readAssetCfgOrFail(baseAssetStr)
let topUpManagerAddressStr = assetCfgArray[IdxCfgTopupManagerAddress]
let innerBaseStr = assetCfgArray[IdxCfgInternalBaseAsset]
if (i.caller.toString() != topUpManagerAddressStr) then failTopupManagerOnly(topUpManagerAddressStr) else
[TopupMutexIntEntry(innerBaseStr, height)] # acquiredHeight
}
@Callable(i)
func topUpBalance(baseAssetStr: String, income: Int) = {
let baseAssetId = baseAssetStr.fromBase58String()
let cfg = readAssetCfgOrFail(baseAssetStr)
let shareAssetId = cfg[IdxCfgShareAssetId].fromBase58String()
let priceMult = cfg[IdxCfgDecimalsMultPrice].parseIntValue()
let bothAssetMult = cfg[IdxCfgDecimalsMultBothAssets].parseIntValue()
let topupIntervalInBlocks = cfg[IdxCfgTopupIntervalInBlocks].parseIntValue()
let topupMaxNegativePart = cfg[IdxCfgTopupMaxNegativePart].parseIntValue()
let innerBaseStr = cfg[IdxCfgInternalBaseAsset]
let topUpManagerAddressStr = cfg[IdxCfgTopupManagerAddress]
let submitLimitsBaseMax = cfg[IdxCfgSubmitLimitsBaseMax].parseIntValue()
let submitLimitsShareMax = cfg[IdxCfgSubmitLimitsShareMax].parseIntValue()
let topUpCurrentIdxKEY = keyTopUpCurrentIdx(innerBaseStr)
let prevTopUpIdx = getIntOrFail(topUpCurrentIdxKEY)
let currentTopUpIdx = prevTopUpIdx + 1
let topUpLastHeightKEY = keyTopUpLastHeight(innerBaseStr, i.caller.toString())
let topUpLastHeight = this.getInteger(topUpLastHeightKEY).valueOrElse(0)
let priceAthKEY = keyPriceATH(innerBaseStr)
let prevPriceATH = this.getInteger(priceAthKEY).valueOrElse(0)
if (i.caller.toString() != topUpManagerAddressStr) then failTopupManagerOnly(topUpManagerAddressStr) else
if (height - topUpLastHeight < topupIntervalInBlocks) then throw("1 topup per " + topupIntervalInBlocks.toString() + " blocks from the same address is allowed") else
let price = genericCalcPrice(innerBaseStr, baseAssetId, income, shareAssetId, priceMult)._1
let valid =
if (income > 0) then {
let pmt = i.payments[0].value()
let pmtAssetId = pmt.assetId.value()
if (baseAssetId != pmtAssetId) then throw("attached payment's asset id is NOT matched passed baseAssetStr") else
if (i.payments.size() > 1) then throw("only one payment can be attached") else
if (pmt.amount != income) then throw("attached payment.amount is NOT matched passed income argument") else
true
} else if (income < 0) then {
let minAllowedPrice = fraction(prevPriceATH, 1*bothAssetMult - topupMaxNegativePart, bothAssetMult)
if (price < minAllowedPrice) then failTopupMaxPriceDeviation(price, minAllowedPrice) else
true
} else throw("zero income is not allowed")
if (!valid) then throw("validation failed") else
let diffTuple = calcTotalLockedDiff("topup", "", innerBaseStr, price, priceMult, 0, baseAssetId, shareAssetId)
let topupTotalDiff = diffTuple._1
[IntE(keyPriceLast(innerBaseStr), price),
IntE(keyPriceHistory(innerBaseStr, height, lastBlock.timestamp), price),
IntE(keyPriceByTopUpIdx(innerBaseStr, currentTopUpIdx), price),
IntE(topUpCurrentIdxKEY, currentTopUpIdx),
IntE(priceAthKEY, if (price > prevPriceATH) then price else prevPriceATH),
IntE(topUpLastHeightKEY, height)
]
:+ TotalLockedStringEntry("DECREMENT", keyTotalLocked(innerBaseStr), topupTotalDiff)
# release mutex
:+ TopupMutexIntEntry(innerBaseStr, 0)
:+ IntE(keyTopupLastTimestamp(innerBaseStr), lastBlock.timestamp)
# reset limits
:+ RemainingLimitsStringEntry(keyLimitsRemaining(innerBaseStr), submitLimitsBaseMax, submitLimitsShareMax)
:+ Burn(shareAssetId, topupTotalDiff[IdxTotalLockedInShare])
:+ Reissue(shareAssetId, -topupTotalDiff[IdxTotalLockedOutShare], true)
++ if (income < 0) then [ScriptTransfer(i.caller, -income, baseAssetId)] else []
}
@Callable(i)
func currentSysParamsREST(baseAssetStr: String)= {
let sysStateTuple = privateCurrentSysParamsREST(baseAssetStr)
# (price, decimalsMultPrice, baseAssetBalance, -1, baseAssetBalanceWCO, shareEmission, currIterTotalInBaseAmount, currIterTotalInShareAmount, totalLockedOutBaseAmount, totalLockedOutShareAmount, decimalsMultBothAssets, priceATH)
let price = sysStateTuple._1.value
let decimalsMultPrice = sysStateTuple._2.value
let baseAssetBalance = sysStateTuple._3.value
let totalLockedBaseAmount = sysStateTuple._4.value
let baseAssetBalanceWCO = sysStateTuple._5.value
let shareEmission = sysStateTuple._6.value
let currIterTotalInBaseAmount = sysStateTuple._7.value
let currIterTotalInShareAmount = sysStateTuple._8.value
let totalLockedOutBaseAmount = sysStateTuple._9.value
let totalLockedOutShareAmount = sysStateTuple._10.value
let decimalsMultBothAssets = sysStateTuple._11.value
let priceATH = sysStateTuple._12.value
let priceRecalculated = sysStateTuple._13.value
let topupLastTime = sysStateTuple._14.value
let restData = makeString(["startCurrentSysParamsREST",
price.toString(),
decimalsMultPrice.toString(),
baseAssetBalance.toString(),
totalLockedBaseAmount.toString(),
baseAssetBalanceWCO.toString(),
shareEmission.toString(),
currIterTotalInBaseAmount.toString(),
currIterTotalInShareAmount.toString(),
totalLockedOutBaseAmount.toString(),
totalLockedOutShareAmount.toString(),
decimalsMultBothAssets.toString(),
priceATH.toString(),
priceRecalculated.toString(),
topupLastTime.toString(),
"endCurrentSysParamsREST"],
SEP)
throw(restData)
}
@Verifier(tx)
func verify () = {
sigVerify(tx.bodyBytes, tx.proofs[0], fromBase58String("2Cbd8ozG7A1RyRNC3nNnZgHu7Ru4K3JCfpyPkhqr9zxq"))
}