-
Notifications
You must be signed in to change notification settings - Fork 0
/
asset.ride
457 lines (379 loc) · 23.6 KB
/
asset.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
{-# STDLIB_VERSION 4 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}
###
func keyAccumulatedFee() = {"%s__accumulatedFee"}
func keyAccumulatedProtocolFee() = {"%s__accumulatedProtocolFee"}
func keyUcollateral() = {"%s__ucollateral"}
func keyTotalLendedAtOtherAccs() = {"%s__totalLendedAtOtherAccs"}
func keyAssetLockedTotal(assetId: String) = {"%s%s__assetLockedTotal__" + assetId}
func keyAccountOperation(unlockHeight: Int, address: String, status: String) = {"%s%s%d%s__defoAssetOperation__" + address + "__" + unlockHeight.toString() + "__" + status}
func keyFactory() = {"%s__factory"}
func keyLendedAmountByAssetCode(assetCode: String) = {"%s%s__lendedBaseAssetAmount__" + assetCode}
func keyPrice(assetCode: String) = {"%s%s__price__" + assetCode}
func keyControlLastHeight(assetCode: String) = {"%s%s__lastHeight__" + assetCode}
#func keyDefoAddressByAssetId(assetId: String) = {"%s%s%s__defoAssetId__" + assetId + "__addressByAssetId"}
let IdxOperationAmountIn = 1
let IdxOperationAssetIn = 2
let IdxOperationPrice = 3
let IdxOperationAmountOut = 4
let IdxOperationAssetOut = 5
func assetDataSwapOperation(amountIn: Int, assetIn: String, price: Int, amountOut: Int, assetOut: String,
bruttoAmount: Int, feeAmount: Int, protocolFeeAmount: Int) = {
makeString([
"%d%s%d%s%d%d%d%d",
amountIn.toString(),
assetIn,
amountOut.toString(),
assetOut,
price.toString(),
bruttoAmount.toString(),
feeAmount.toString(),
protocolFeeAmount.toString()
], "__")
}
func assetDataRebalanceTrace(debtorAssetCode: String, debtPmt: AttachedPayment, basePmt: AttachedPayment,
lendedAmtBefore: Int, lendedAmtAfter: Int) = {
makeString([
"%s%s%d%s%d%d%d",
debtorAssetCode,
debtPmt.assetId.value().toBase58String(),
debtPmt.amount.toString(),
basePmt.assetId.value().toBase58String(),
basePmt.amount.toString(),
lendedAmtBefore.toString(),
lendedAmtAfter.toString()
], "__")
}
func assetReadSwapDataArrayOrFail(accOperationKey: String) = {
let accOperationDataStr = getString(this, accOperationKey)
.valueOrErrorMessage("There is no request for passed arguments: " + accOperationKey)
accOperationDataStr.split("__")
# (accOperationDataArray[0].parseIntValue(), # amountIn
# accOperationDataArray[1], # assetIn
# accOperationDataArray[2].parseIntValue(), # price
# accOperationDataArray[3].parseIntValue(), # amountOut
# accOperationDataArray[4]) # assetOut
}
###
let nullInt = -1
let nullStr = "NULL"
### Factory API
let factoryAcc = this.getString(keyFactory()).valueOrErrorMessage("No config at this=" + this.toString() + " for key=" + keyFactory())
.addressFromStringValue()
func keyFactoryNeutrinoContractAddressKey() = {"%s%s__commonConfig__neutrinoContractAddress"}
func keyFactoryDebtAssetId() = {"%s%s__commonConfig__debtAssetId"}
func keyFactoryDebtAssetEtalonBalance() = {"%s%s__commonConfig__debtAssetEtalonBalance"}
func keyFactoryAssetCfg(assetAddressStr: String) = {"%s%s%s__defoAsset__" + assetAddressStr + "__config"}
func keyFactoryAssetCurrentPool(assetAccAddress: Address) = {"%s%s%s__defoAsset__" + assetAccAddress.toString() + "__currentPool"}
func keyFactoryDefoAddressByAssetCode(assetCode: String) = {"%s%s%s__defoAsset__" + assetCode + "__addressByAssetCode"}
func keyFactoryAssetPoolMakers(assetAddress: String) = {"%s%s%s__defoAsset__" + assetAddress + "__poolMakers"}
func keyFactoryDefoStakingPacemakerPub() = {"%s%s__commonConfig__defoStakingPacemakerPub"}
func keyFactoryPoolMakerLiquidityRequest(assetAddress: String, poolMakerAddress: String, h: Int) = makeString(["%s%s%s%d%s__pool", assetAddress, poolMakerAddress, h.toString(), "liquidityRequest"], "__")
func keyFactoryPoolMakerUnlockHeight(assetAddress: String, poolMakerAddress: String) = makeString(["%s%s%s%s__pool", assetAddress, poolMakerAddress, "unlockHeight"], "__")
func factoryReadDebtAssetId() = {
factoryAcc.getString(keyFactoryDebtAssetId())
.valueOrErrorMessage("No config at factory=" + factoryAcc.toString() + " for key=" + keyFactoryDebtAssetId())
}
func factoryReadAssetCfgByAddress(assetAddressStr: String) = {
factoryAcc.getString(keyFactoryAssetCfg(assetAddressStr))
.valueOrErrorMessage("No config at factory=" + factoryAcc.toString() + " for key=" + keyFactoryAssetCfg(assetAddressStr))
.split("__")
}
func factoryReadAssetCfgByCode(assetCode: String) = {
let assetAddressStr = factoryAcc.getString(keyFactoryDefoAddressByAssetCode(assetCode))
.valueOrErrorMessage("No config at factory=" + factoryAcc.toString() + " for key=" + keyFactoryDefoAddressByAssetCode(assetCode))
(assetAddressStr, factoryReadAssetCfgByAddress(assetAddressStr))
}
func factoryReadNextPoolMakerToDistributeFee(assetAddressStr: String) = {
# TODO - move into config
"3PEs19bv4qT4Gz5idjcWynkQyrH9psGipmw".addressFromStringValue()
}
func factoryReadDefoStakingPacemakerPub() = {
factoryAcc.getString(keyFactoryDefoStakingPacemakerPub())
.valueOrErrorMessage("No config at factory=" + factoryAcc.toString() + " for key=" + keyFactoryDefoStakingPacemakerPub())
.fromBase58String()
}
let IdxDefoAssetCode = 1
let IdxDefoAssetId = 2
let IdxDefoAssetStatus = 3
let IdxPriceDecimals = 4
let IdxBaseAssetId = 5
let IdxOverCollateralPercent = 6
let IdxMinInitPool = 7
let IdxPriceOracleAddress = 8
let IdxMinBuyPayment = 9
let IdxMinSellPayment = 10
let IdxBuyLockInterval = 11
let IdxSellLockInterval = 12
let IdxBuyFeePercent = 13
let IdxSellFeePercent = 14
let IdxPoolRedemptionTimeout = 15
let IdxWeekendsPriceChangeCoefficient = 16
let IdxAssetAccountPublicStr = 17
let IdxAssetStakingReferralPublicStr = 18
let IdxCrossExchangeCoefficient = 19
let IdxStakingMinAmtFromSellCoefficient = 20
let IdxPoolStabilityFeePart = 21
let IdxProtocolFeePercent = 22
let thisCfgArray = factoryReadAssetCfgByAddress(this.toString())
let defoAssetCode = thisCfgArray[IdxDefoAssetCode]
let defoAssetIdStr = thisCfgArray[IdxDefoAssetId]
let defoAssetId = defoAssetIdStr.fromBase58String()
let priceOracleAcc = thisCfgArray[IdxPriceOracleAddress].addressFromStringValue()
let overCollateralPercent = thisCfgArray[IdxOverCollateralPercent].parseIntValue()
let baseAssetIdStr = thisCfgArray[IdxBaseAssetId]
let baseAssetId = baseAssetIdStr.fromBase58String()
let priceDecimals = thisCfgArray[IdxPriceDecimals].parseIntValue()
let minBasicBuyAmount = thisCfgArray[IdxMinBuyPayment].parseIntValue()
let minSynthSellAmount = thisCfgArray[IdxMinSellPayment].parseIntValue()
let buyLockInterval = thisCfgArray[IdxBuyLockInterval].parseIntValue()
let sellLockInterval = thisCfgArray[IdxSellLockInterval].parseIntValue()
let buyFeePercent = thisCfgArray[IdxBuyFeePercent].parseIntValue()
let sellFeePercent = thisCfgArray[IdxSellFeePercent].parseIntValue()
let weekendsPriceChangeCoefficient = thisCfgArray[IdxWeekendsPriceChangeCoefficient].parseIntValue()
let assetAccountPublicStr = thisCfgArray[IdxAssetAccountPublicStr]
let assetStakingReferralPublicStr = thisCfgArray[IdxAssetStakingReferralPublicStr]
let crossExchangeCoefficient = thisCfgArray[IdxCrossExchangeCoefficient].parseIntValue()
let stakingMinAmtFromSellCoefficient = thisCfgArray[IdxStakingMinAmtFromSellCoefficient].parseIntValue()
let poolStabilityFeePart = thisCfgArray[IdxPoolStabilityFeePart].parseIntValue()
let protocolFeePercent = thisCfgArray[IdxProtocolFeePercent].parseIntValue()
## Control API
func keyIsBlocked() = "%s__isBlocked"
func keyIsMarketOpened(assetCode: String) = "%s%s__isMarketOpened__" + assetCode
let isBlocked = priceOracleAcc.getBoolean(keyIsBlocked()).valueOrElse(false)
let isMarketOpened = priceOracleAcc.getBoolean(keyIsMarketOpened(defoAssetCode))
.valueOrElse(false)
#.valueOrErrorMessage("Empty mandatory key at priceOracle=" + priceOracleAcc.toString() + " for key=" + keyIsMarketOpened(defoAssetCode))
func controlAccReadPrice(assetCode: String) = {
priceOracleAcc.getInteger(keyPrice(assetCode))
.valueOrErrorMessage("No price at priceOracle=" + priceOracleAcc.toString() + " for key=" + keyPrice(assetCode))
}
func controlAccReadLastHeight(assetCode: String) = {
priceOracleAcc.getInteger(keyControlLastHeight(assetCode))
.valueOrErrorMessage("No lastHeight at priceOracle=" + priceOracleAcc.toString() + " for key=" + keyControlLastHeight(assetCode))
}
func controlAccReadCurrIdxOrFail() = {
getInteger(priceOracleAcc, "currIdx")
.valueOrErrorMessage("No currIdx at controlAcc=" + priceOracleAcc.toString())
}
func controlAccReadIdxHeight(idx: Int) = {
let idxHeightKey = "idxHeight_" + idx.toString()
getInteger(priceOracleAcc, idxHeightKey).valueOrElse(0)
}
func controlAccReadPriceByHeight(priceHeight: Int) = {
let priceByHeightKey = "price_" + priceHeight.toString()
priceOracleAcc.getInteger(priceByHeightKey)
.valueOrErrorMessage("No " + priceByHeightKey + " at controlAcc=" + priceOracleAcc.toString())
}
let priceLastHeight = controlAccReadLastHeight(defoAssetCode)
let isBlockedByLastHeight = (height - priceLastHeight) > 5
###
### Neutrino API
# key name from neutrino state
func keyFeesManagerAddressKey() = {"fees_manager_address"}
let neutrinoMainAcc = factoryAcc.getString(keyFactoryNeutrinoContractAddressKey())
.valueOrErrorMessage("No config at factory=" + factoryAcc.toString() + " for key=" + keyFactoryNeutrinoContractAddressKey())
.addressFromStringValue()
let feeManagerAddress = neutrinoMainAcc.getString(keyFeesManagerAddressKey())
.valueOrErrorMessage(keyFeesManagerAddressKey() + " is not specified")
.addressFromString().valueOrErrorMessage(keyFeesManagerAddressKey() + " invalid address format")
###
### Staking API
let keyDefoStakingAddress = "%s%s__commonConfig__defoStakingAddress"
let keyNeutrinoStakingAddress = "%s%s__commonConfig__neutrinoStakingAddress"
func keyDefoStakingAssetBalance(assetId: String) = "%s%s__stakingBalance__" + assetId
func keyNeutrinoStakingBalance() = "rpd_balance_" + baseAssetIdStr + "_" + this.toString()
let defoStakingAcc = factoryAcc.getString(keyDefoStakingAddress)
.valueOrErrorMessage("No config at factoryAcc" + factoryAcc.toString() + " for key=" + keyDefoStakingAddress)
.addressFromString().valueOrErrorMessage("address extraction error for key=" + keyDefoStakingAddress)
let neutrinoStakingAcc = factoryAcc.getString(keyNeutrinoStakingAddress)
.valueOrErrorMessage("No config at factoryAcc" + factoryAcc.toString() + " for key=" + keyNeutrinoStakingAddress)
.addressFromString().valueOrErrorMessage("address extraction error for key=" + keyNeutrinoStakingAddress)
func getThisDefoStakingBalance() = {
defoStakingAcc.getInteger(keyDefoStakingAssetBalance(defoAssetIdStr)).valueOrElse(0)
}
func getThisNeutrinoStakingBalance() = {
neutrinoStakingAcc.getInteger(keyNeutrinoStakingBalance()).valueOrElse(0)
}
###
# TODO: ucollateral can be < 0
let ucollateral = this.getInteger(keyUcollateral()).valueOrElse(0)
let accumulatedFee = this.getInteger(keyAccumulatedFee()).valueOrElse(0)
let accumulatedProtocolFee = this.getInteger(keyAccumulatedProtocolFee()).valueOrElse(0)
let currPoolAmount = factoryAcc.getIntegerValue(keyFactoryAssetCurrentPool(this))
let debtAssetId = factoryReadDebtAssetId().fromBase58String()
let debtAssetEtalonBalance = factoryAcc.getIntegerValue(keyFactoryDebtAssetEtalonBalance())
# if positive then this acc is creditor
# if negative then this acc is debtor
let lendedOrDebtAmount = debtAssetEtalonBalance - this.assetBalance(debtAssetId)
let currentBaseAssetBalance = this.assetBalance(baseAssetId) + getThisNeutrinoStakingBalance() + lendedOrDebtAmount
let controlPrice = controlAccReadPrice(thisCfgArray[IdxDefoAssetCode])
let emission = assetInfo(defoAssetId).value().quantity - this.assetBalance(defoAssetId) # TODO add fee or transfer fee to another acc
func getBuyPrice(changeCoeff: Int) = {
if (isMarketOpened) then controlPrice else fraction(priceDecimals - changeCoeff, controlPrice, priceDecimals)
}
# used only in buy operation to avoid conversion spends for staking payouts
func getBuyFeeConsideringStakingReferral(callerPub58Str: String) = {
if (assetStakingReferralPublicStr == callerPub58Str) then 0 else buyFeePercent
}
# used only in buy operation to avoid conversion spends for staking payouts
func getProtocolFeeConsideringStakingReferral(callerPub58Str: String) = {
if (assetStakingReferralPublicStr == callerPub58Str) then 0 else protocolFeePercent
}
# used only in buy operation to avoid conversion spends for staking payouts
func getBuyPriceConsideringStakingReferral(changeCoeff: Int, callerPub58Str: String) = {
if (assetStakingReferralPublicStr == callerPub58Str)
then controlPrice
else getBuyPrice(changeCoeff)
}
func getSellPrice(changeCoeff: Int) = {
if (isMarketOpened) then controlPrice else fraction(priceDecimals + changeCoeff, controlPrice, priceDecimals)
}
func getSellPriceFrom(fromPrice: Int, changeCoeff: Int) = {
if (isMarketOpened) then fromPrice else fraction(priceDecimals + changeCoeff, fromPrice, priceDecimals)
}
func internalBuyAsset(sellerAddr: Address, sellAmt: Int, sellAssetId: ByteVector, minSellAmt: Int, buy2sellPrice: Int, poolMakersFeePart: Int, protocolFeePart: Int) = {
let defoAssetAmountGross = fraction(sellAmt, buy2sellPrice, priceDecimals)
# stabilityFeeAmount is excluded from defo asset emission
let stabilityFeeDefoAmount = fraction(poolStabilityFeePart, defoAssetAmountGross, priceDecimals)
let poolMakersFeeDefoAmount = fraction(poolMakersFeePart, defoAssetAmountGross, priceDecimals)
let protocolFeeDefoAmount = fraction(protocolFeePart, defoAssetAmountGross, priceDecimals)
let defoAssetAmount = defoAssetAmountGross - stabilityFeeDefoAmount - poolMakersFeeDefoAmount - protocolFeeDefoAmount
let requiredBasicAssetAmount = fraction(defoAssetAmountGross, priceDecimals, buy2sellPrice)
let change = sellAmt - requiredBasicAssetAmount
# allow to swap less than minSellAmt for staking acc
if (sellAmt < minSellAmt && sellerAddr.toString() != defoStakingAcc.toString()) then throw("impossible to issue new " + defoAssetCode + ": payment=" + sellAmt.toString() + "is less then min amount=" + minSellAmt.toString()) else
([IntegerEntry(keyUcollateral(), ucollateral + requiredBasicAssetAmount),
StringEntry(keyAccountOperation(height, sellerAddr.toString(), "FINISHED"),
assetDataSwapOperation(sellAmt, sellAssetId.toBase58String(), controlPrice, defoAssetAmount, defoAssetId.toBase58String(), defoAssetAmountGross, poolMakersFeeDefoAmount, protocolFeeDefoAmount)),
Reissue(defoAssetId, defoAssetAmount + poolMakersFeeDefoAmount + protocolFeeDefoAmount, true),
ScriptTransfer(sellerAddr, defoAssetAmount, defoAssetId),
ScriptTransfer(sellerAddr, change, sellAssetId),
ScriptTransfer(factoryReadNextPoolMakerToDistributeFee(this.toString()), poolMakersFeeDefoAmount, defoAssetId),
ScriptTransfer(feeManagerAddress, protocolFeeDefoAmount, defoAssetId),
IntegerEntry(keyAccumulatedFee(), accumulatedFee + poolMakersFeeDefoAmount),
IntegerEntry(keyAccumulatedProtocolFee(), accumulatedProtocolFee + protocolFeeDefoAmount)
], change)
}
@Callable(i)
func buyAsset() = {
let pmt = i.payments[0].value()
let pmtAssetId = pmt.assetId.value()
let callerPub58Str = i.callerPublicKey.toBase58String()
if (isBlocked) then throw("contract is blocked by EMERGENCY SHUTDOWN actions untill reactivation by emergency oracles") else
if (pmtAssetId != baseAssetId) then throw("Payment asset id doesn't match basic asset: expected=" + baseAssetId.toBase58String() + " actual=" + pmtAssetId.toBase58String()) else
internalBuyAsset(
i.caller,
pmt.amount,
pmtAssetId,
minBasicBuyAmount,
getBuyPriceConsideringStakingReferral(weekendsPriceChangeCoefficient, callerPub58Str),
getBuyFeeConsideringStakingReferral(callerPub58Str),
getProtocolFeeConsideringStakingReferral(callerPub58Str))
._1
}
# user sends synthAsset to exchange on basic asset. We don't know exchange rate (price) which will be used to change synthAsset.
# As a result we don't know Basic asset amount and we need:
# - to consider locked synthAsset as current emission
# - to sync delay intervals between withdrawFromPool and sellAsset
@Callable(i)
func sellAsset() = {
let pmt = i.payments[0].value()
let pmtAsset = pmt.assetId.value()
let callerAddress = i.caller.toString()
let sellPrice = getSellPrice(weekendsPriceChangeCoefficient)
if (isBlocked) then throw("contract is blocked by EMERGENCY SHUTDOWN actions untill reactivation by emergency oracles") else
if (pmtAsset != defoAssetId) then throw("Invalid payment asset id: expected=" + defoAssetId.toBase58String() + " actual=" + pmtAsset.toBase58String()) else
if (pmt.amount < minSynthSellAmount) then throw("Payment amount less then mininimal allowed: paymentAmount=" + pmt.amount.toString() + " minAmount=" + minSynthSellAmount.toString()) else
let baseAssetAmountNoBalanceLimit = fraction(pmt.amount, priceDecimals, sellPrice)
let baseAssetAmountAvailable = if (baseAssetAmountNoBalanceLimit > currentBaseAssetBalance) then currentBaseAssetBalance else baseAssetAmountNoBalanceLimit
let soldDefoAssetAmountGross = fraction(baseAssetAmountAvailable, sellPrice, priceDecimals)
let change = pmt.amount - soldDefoAssetAmountGross
# stabilityFeeAmount is excluded from defo asset emission
let stabilityFeeDefoAmount = fraction(0, soldDefoAssetAmountGross, priceDecimals)
let poolMakersFeeDefoAmount = fraction(0, soldDefoAssetAmountGross, priceDecimals)
let protocolFeeDefoAmount = fraction(0, soldDefoAssetAmountGross, priceDecimals)
let soldDefoAssetAmount = soldDefoAssetAmountGross - stabilityFeeDefoAmount - poolMakersFeeDefoAmount - protocolFeeDefoAmount
let baseAssetAmountToSend = fraction(soldDefoAssetAmount, priceDecimals, sellPrice)
[IntegerEntry(keyUcollateral(), ucollateral - baseAssetAmountToSend),
StringEntry(
keyAccountOperation(height, callerAddress, "FINISHED"),
assetDataSwapOperation(pmt.amount, pmtAsset.toBase58String(), sellPrice, baseAssetAmountToSend, baseAssetIdStr, soldDefoAssetAmountGross, poolMakersFeeDefoAmount, protocolFeeDefoAmount)),
Burn(defoAssetId, soldDefoAssetAmount + stabilityFeeDefoAmount),
ScriptTransfer(i.caller, baseAssetAmountToSend, baseAssetId),
ScriptTransfer(i.caller, change, defoAssetId),
ScriptTransfer(feeManagerAddress, protocolFeeDefoAmount, defoAssetId),
ScriptTransfer(factoryReadNextPoolMakerToDistributeFee(this.toString()), poolMakersFeeDefoAmount, defoAssetId),
IntegerEntry(keyAccumulatedFee(), accumulatedFee + poolMakersFeeDefoAmount),
IntegerEntry(keyAccumulatedProtocolFee(), accumulatedProtocolFee + protocolFeeDefoAmount)
]
}
@Callable(i)
func crossExchange(buyAssetCodeConfirm: String, sellAssetCodeConfirm: String) = {
throw("DeFo buy and crossExchange operations are stopped due to fundamental changes in the Neutrino protocol. "
+ "Sell and redeemFromPool operations will remain available all the time, "
+ "so that everyone can swap DeFo tokens to the base underlying token.")
}
@Callable(i)
func rebalanceDebts() = {
let debtPmt0 = i.payments[0].value()
let debtPmtAsset0 = debtPmt0.assetId.value()
let basePmt1 = i.payments[1].value()
let basePmtAsset1 = basePmt1.assetId.value()
let debtorAddress = i.caller.toString()
let debtorAssetCfg = factoryReadAssetCfgByAddress(debtorAddress)
let debtorAssetCode = debtorAssetCfg[IdxDefoAssetCode]
let lendedAmountByAssetCodeKey = keyLendedAmountByAssetCode(debtorAssetCode)
let lendedAmt = this.getInteger(lendedAmountByAssetCodeKey).valueOrErrorMessage("No debts for " + debtorAssetCode);
if (i.payments.size() != 2) then throw("exact 2 payments must be attached") else
if (isBlocked) then throw("contract is blocked by EMERGENCY SHUTDOWN actions untill reactivation by emergency oracles") else
if (debtAssetId != debtPmtAsset0) then throw("invalid debt asset id in the first paymet: expected=" + debtAssetId.toBase58String() + " actual=" + debtPmtAsset0.toBase58String()) else
if (baseAssetId != basePmtAsset1) then throw("invalid base asset id in the second payment: expected=" + baseAssetId.toBase58String() + " actual=" + basePmtAsset1.toBase58String()) else
if (debtPmt0.amount != basePmt1.amount) then throw("first payment amount doesn't match to the second payment amount") else
if (lendedAmt <= 0) then throw("lendedAmt is less then zero: lendedAmt=" + lendedAmt.toString()) else
if (debtPmt0.amount <= 100*priceDecimals) then throw("attached payment must be greater then 100: pmt0.amount=" + debtPmt0.amount.toString()) else
if (debtPmt0.amount > lendedAmt) then throw("attached payment is grater than required: pmtAmount=" + debtPmt0.amount.toString() + " lendedAmt=" + lendedAmt.toString()) else
let totalLendedAtOtherAccs = this.getInteger(keyTotalLendedAtOtherAccs()).valueOrElse(0)
let lendedAmtAfter = lendedAmt - debtPmt0.amount
[IntegerEntry(lendedAmountByAssetCodeKey, lendedAmtAfter),
IntegerEntry(keyTotalLendedAtOtherAccs(), totalLendedAtOtherAccs - debtPmt0.amount),
StringEntry("%s%s__rebalanceTrace__" + i.transactionId.toBase58String(),
assetDataRebalanceTrace(debtorAssetCode, debtPmt0, basePmt1, lendedAmt, lendedAmtAfter))
]
}
@Callable(i)
func fulfillRedeemRequest(poolMakerAddress: String) = {
let thisAddressStr = this.toString()
let poolMakerUnlockHeightKey = keyFactoryPoolMakerUnlockHeight(thisAddressStr, poolMakerAddress)
let poolMakerUnlockHeight = factoryAcc.getInteger(poolMakerUnlockHeightKey).valueOrElse(0)
if (poolMakerUnlockHeight <= 0) then throw("All liquidity request fulfilled") else
let poolMakerLiquidityRequestKey = keyFactoryPoolMakerLiquidityRequest(thisAddressStr, poolMakerAddress, poolMakerUnlockHeight)
let poolMakerLiquidityRequestAmount = factoryAcc.getInteger(poolMakerLiquidityRequestKey).valueOrErrorMessage("Empty poolMakerLiquidityRequestKey at factory acc")
if (this.getInteger(poolMakerLiquidityRequestKey).isDefined()) then throw("Liquidity request has been already fulfilled") else
[
IntegerEntry(poolMakerLiquidityRequestKey, poolMakerLiquidityRequestAmount),
ScriptTransfer(factoryAcc, poolMakerLiquidityRequestAmount, baseAssetId)
]
}
@Verifier(tx)
func verify() = {
match (tx) {
case inv:InvokeScriptTransaction => {
if (inv.fee > 900*1000) then throw("fee amount is greater than max allowed: " + inv.fee.toString()) else
if (isDefined(inv.feeAssetId)) then throw("only Waves is allowed as feeAssetId") else
if (inv.function == "rebalanceDebts") then {
let invDappAddress = inv.dApp.addressFromRecipient().toString()
if (factoryReadAssetCfgByAddress(invDappAddress)[IdxDefoAssetStatus] != "ISSUED") then throw("only defo dapp is allowed") else
if (invDappAddress == this.toString()) then throw("impossible to call self rebealnceDebt") else
true
} else if (inv.function == "lockNeutrino"
|| inv.function == "lockNeutrinoSP"
|| inv.function == "unlockNeutrino") then {
if (neutrinoStakingAcc.toString() != inv.dApp.addressFromRecipient().toString()) then throw("invalid neutrino staking dapp address") else
sigVerify(tx.bodyBytes, tx.proofs[0], factoryReadDefoStakingPacemakerPub())
} else throw("Not allowed invocation method calls")
}
case _ => sigVerify_128Kb(tx.bodyBytes, tx.proofs[0], fromBase58String("Ce5zjCMEm3ZxvKznGGm8BhwaDiRNd8kADwMNgriVg4tD"))
}
}