-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPartialOrder.hs
1221 lines (1120 loc) · 49.2 KB
/
PartialOrder.hs
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
{-# LANGUAGE LambdaCase #-}
{- |
Module : GeniusYield.Api.Dex.PartialOrder
Copyright : (c) 2023 GYELD GMBH
License : Apache 2.0
Maintainer : support@geniusyield.co
Stability : develop
-}
module GeniusYield.Api.Dex.PartialOrder (
PORefs (..),
PORef (..),
-- * PartialOrderInfo
PartialOrderInfo (..),
POIContainedFee (..),
partialOrderInfoToIn,
partialOrderInfoToPayment,
partialOrderInfoToPartialOrderDatum,
poiGetContainedFeeValue,
expectedPaymentWithDeposit,
-- * Redeemer & Datum
PartialOrderAction (..),
PartialOrderDatum (..),
-- * Partial order NFT policy
partialOrderNftPolicy,
partialOrderNftPolicyId,
-- * Queries
partialOrders,
partialOrdersHavingAsset,
partialOrdersWithTransformerPredicate,
orderByNft,
getPartialOrderInfo,
getPartialOrdersInfos,
getPartialOrdersInfos',
-- * Tx constructors
placePartialOrder,
placePartialOrder',
placePartialOrder'',
placePartialOrderWithVersion,
placePartialOrderWithVersion',
placePartialOrderWithVersion'',
completelyFillPartialOrder,
partiallyFillPartialOrder,
fillPartialOrder,
fillPartialOrder',
fillMultiplePartialOrders,
completelyFillMultiplePartialOrders,
fillMultiplePartialOrders',
cancelPartialOrder,
cancelMultiplePartialOrders,
cancelMultiplePartialOrders',
-- * Utilities
partialOrderAddr,
partialOrderPrice,
partialOrderPrice',
roundFunctionForPOCVersion,
getVersionsInOrders,
preferentiallySelectLatestVersion,
preferentiallySelectLatestPocd,
) where
import Control.Monad.Reader (ask)
import Data.Bifunctor (Bifunctor)
import Data.Foldable (foldlM)
import Data.Map.Merge.Strict qualified as Map
import Data.Map.Strict qualified as Map
import Data.Maybe (fromJust)
import Data.Ratio ((%))
import Data.Set qualified as Set
import Data.Strict.Tuple (Pair (..), (:!:))
import Data.Swagger qualified as Swagger
import Data.Text qualified as Text
import GeniusYield.Api.Dex.PartialOrderConfig (
PORef (..),
PORefs (..),
RefPocd (..),
RefPocds,
SomePORef (..),
SomeRefPocd (..),
fetchPartialOrderConfig,
fetchPartialOrderConfigs,
selectPor,
selectRefPocd,
selectV1RefPocd,
selectV1_1RefPocd,
withSomePORef,
)
import GeniusYield.Api.Dex.Types (
GYDexApiMonad,
GYDexApiQueryMonad,
HasDexScripts,
)
import GeniusYield.HTTP.Errors
import GeniusYield.Imports
import GeniusYield.Scripts.Dex.Nft (
gyExpectedTokenName,
mkNftRedeemer,
)
import GeniusYield.Scripts.Dex.PartialOrder (
PartialOrderAction (..),
PartialOrderContainedFee (..),
PartialOrderDatum (..),
PartialOrderFeeOutput (..),
partialOrderValidator,
)
import GeniusYield.Scripts.Dex.PartialOrderConfig (
PartialOrderConfigInfo,
PartialOrderConfigInfoF (..),
)
import GeniusYield.Scripts.Dex.PartialOrderNft (partialOrderNftMintingPolicy)
import GeniusYield.Scripts.Dex.Version
import GeniusYield.TxBuilder
import GeniusYield.Types
import Network.HTTP.Types.Status
import PlutusTx.AssocMap qualified as PlutusTx
import PlutusTx.Ratio qualified as PlutusTx
data PodException
= PodNftNotAvailable
| PodNonPositiveAmount !Integer
| PodNonPositivePrice !GYRational
| PodRequestedAmountGreaterOrEqualToOfferedAmount {podReqAmt ∷ !Natural, podOfferedAmount ∷ !Natural}
| PodRequestedAmountGreaterThanOfferedAmount {podReqAmt ∷ !Natural, podOfferedAmount ∷ !Natural}
| -- | Offered asset is same as asked asset.
PodNonDifferentAssets !GYAssetClass
| PodEndEarlierThanStart
!GYTime
-- ^ Start time.
!GYTime
-- ^ End time.
| PodNegativeFrontendFee !GYValue
| -- | We couldn't fetch information for some of the given `GYTxOutRef`s. Note that this does not relate to UTxO being spent as depending upon provider, we would fetch information for even those `GYTxOutRef` which have been spent.
PodNotAllOrderRefsPresent
!(Set.Set GYTxOutRef)
-- ^ Missing output refs.
| -- | Such an order does not belong to supported swap script credentials.
PodOrderDoesntBelongToScript !GYTxOutRef
deriving stock (Show)
deriving anyclass (Exception)
instance IsGYApiError PodException where
toApiError PodNftNotAvailable =
GYApiError
{ gaeErrorCode = "NFT_NOT_AVAILABLE",
gaeHttpStatus = status400,
gaeMsg = Text.pack "Nft Not Available"
}
toApiError (PodNonPositiveAmount amt) =
GYApiError
{ gaeErrorCode = "NON_POSITIVE_AMOUNT",
gaeHttpStatus = status400,
gaeMsg = Text.pack $ "Amount was : " ++ show amt
}
toApiError (PodNonPositivePrice price) =
GYApiError
{ gaeErrorCode = "NON_POSITIVE_PRICE",
gaeHttpStatus = status400,
gaeMsg = Text.pack $ "Price was: " ++ show price
}
toApiError (PodRequestedAmountGreaterOrEqualToOfferedAmount reqAmt offeredAmt) =
GYApiError
{ gaeErrorCode = "REQUESTED_AMOUNT_GREATER_OR_EQUAL_TO_OFFERED_AMOUNT",
gaeHttpStatus = status400,
gaeMsg = Text.pack $ printf "Requested Amount was: %s but offered amount is %s" (show reqAmt) (show offeredAmt)
}
toApiError (PodRequestedAmountGreaterThanOfferedAmount reqAmt offeredAmt) =
GYApiError
{ gaeErrorCode = "REQUESTED_AMOUNT_GREATER_THAN_OFFERED_AMOUNT",
gaeHttpStatus = status400,
gaeMsg = Text.pack $ printf "Requested Amount was: %s but offered amount is %s" (show reqAmt) (show offeredAmt)
}
toApiError (PodNonDifferentAssets offeredAsset) =
GYApiError
{ gaeErrorCode = "NOT_DIFFERENT_OFFERED_ASKED_ASSET",
gaeHttpStatus = status400,
gaeMsg = Text.pack $ "Offered asset is same as asked asset, which is: " ++ show offeredAsset
}
toApiError (PodEndEarlierThanStart startTime endTime) =
GYApiError
{ gaeErrorCode = "END_EARLIER_THAN_START",
gaeHttpStatus = status400,
gaeMsg = Text.pack $ "End time is earlier than start. Start time: " ++ show startTime ++ ", end time: " ++ show endTime
}
toApiError (PodNegativeFrontendFee fee) =
GYApiError
{ gaeErrorCode = "NEGATIVE_FRONTEND_FEE",
gaeHttpStatus = status400,
gaeMsg = Text.pack $ "Negative frontend fee: " ++ show fee
}
toApiError (PodNotAllOrderRefsPresent missingRefs) =
GYApiError
{ gaeErrorCode = "MISSING_REFS",
gaeHttpStatus = status400,
gaeMsg = Text.pack $ "Not all of given references are present, missing ones: " ++ show missingRefs
}
toApiError (PodOrderDoesntBelongToScript ref) =
GYApiError
{ gaeErrorCode = "ORDER_DOESNT_BELONG_TO_SCRIPT",
gaeHttpStatus = status400,
gaeMsg = Text.pack $ "Order doesn't belong to supported swap script credentials: " ++ show ref
}
-------------------------------------------------------------------------------
-- Order info
-------------------------------------------------------------------------------
data POIContainedFee = POIContainedFee
{ poifLovelaces ∷ !Natural,
poifOfferedTokens ∷ !Natural,
poifAskedTokens ∷ !Natural
}
deriving stock (Show, Generic, Eq)
deriving anyclass (Swagger.ToSchema)
instance Semigroup POIContainedFee where
(<>) a b =
POIContainedFee
{ poifLovelaces = poifLovelaces a + poifLovelaces b,
poifOfferedTokens = poifOfferedTokens a + poifOfferedTokens b,
poifAskedTokens = poifAskedTokens a + poifAskedTokens b
}
instance Monoid POIContainedFee where mempty = POIContainedFee 0 0 0
data PartialOrderInfo = PartialOrderInfo
{ -- | Reference to the partial order.
poiRef ∷ !GYTxOutRef,
-- | Public key hash of the owner.
poiOwnerKey ∷ !GYPubKeyHash,
-- | Address of the owner.
poiOwnerAddr ∷ !GYAddress,
-- | The asset being offered.
poiOfferedAsset ∷ !GYAssetClass,
-- | The number of units originally offered.
poiOfferedOriginalAmount ∷ !Natural,
-- | The number of units being offered.
poiOfferedAmount ∷ !Natural,
-- | The asset being asked for as payment.
poiAskedAsset ∷ !GYAssetClass,
-- | The price for one unit of the offered asset.
poiPrice ∷ !GYRational,
-- | Token name of the NFT identifying this partial order.
poiNFT ∷ !GYTokenName,
-- | The time when the order can earliest be filled (optional).
poiStart ∷ !(Maybe GYTime),
-- | The time when the order can latest be filled (optional).
poiEnd ∷ !(Maybe GYTime),
-- | The number of past partial fills.
poiPartialFills ∷ !Natural,
-- | Flat fee (in lovelace) paid by the taker.
poiMakerLovelaceFlatFee ∷ !Natural,
-- | Flat fee (in lovelace) paid by the taker.
poiTakerLovelaceFlatFee ∷ !Natural,
-- | Fee contained in the order.
poiContainedFee ∷ !POIContainedFee,
-- | Payment (in asked asset) contained in the order.
poiContainedPayment ∷ !Natural,
-- | Total value in the UTxO.
poiUTxOValue ∷ !GYValue,
-- | Address of the order UTxO.
poiUTxOAddr ∷ !GYAddress,
-- | Caching the CS to avoid recalculating for it.
poiNFTCS ∷ !GYMintingPolicyId,
-- | Version of the partial order.
poiVersion ∷ !POCVersion,
-- | Raw datum.
poiRawDatum ∷ !GYDatum
}
deriving stock (Show, Eq, Generic)
poiContainedFeeToPlutus ∷ POIContainedFee → PartialOrderContainedFee
poiContainedFeeToPlutus POIContainedFee {..} =
PartialOrderContainedFee
{ pocfLovelaces = fromIntegral poifLovelaces,
pocfOfferedTokens = fromIntegral poifOfferedTokens,
pocfAskedTokens = fromIntegral poifAskedTokens
}
poiContainedFeeFromPlutus ∷ PartialOrderContainedFee → POIContainedFee
poiContainedFeeFromPlutus PartialOrderContainedFee {..} =
POIContainedFee
{ poifLovelaces = fromIntegral pocfLovelaces,
poifOfferedTokens = fromIntegral pocfOfferedTokens,
poifAskedTokens = fromIntegral pocfAskedTokens
}
partialOrderInfoToPartialOrderDatum ∷ PartialOrderInfo → PartialOrderDatum
partialOrderInfoToPartialOrderDatum PartialOrderInfo {..} =
PartialOrderDatum
{ podOwnerKey = pubKeyHashToPlutus poiOwnerKey,
podOwnerAddr = addressToPlutus poiOwnerAddr,
podOfferedAsset = assetClassToPlutus poiOfferedAsset,
podOfferedOriginalAmount = fromIntegral poiOfferedOriginalAmount,
podOfferedAmount = fromIntegral poiOfferedAmount,
podAskedAsset = assetClassToPlutus poiAskedAsset,
podPrice = PlutusTx.fromGHC $ toRational poiPrice,
podNFT = tokenNameToPlutus poiNFT,
podStart = timeToPlutus <$> poiStart,
podEnd = timeToPlutus <$> poiEnd,
podPartialFills = fromIntegral poiPartialFills,
podMakerLovelaceFlatFee = fromIntegral poiMakerLovelaceFlatFee,
podTakerLovelaceFlatFee = toInteger poiTakerLovelaceFlatFee,
podContainedFee = poiContainedFeeToPlutus poiContainedFee,
podContainedPayment = toInteger poiContainedPayment
}
poiGetContainedFeeValue ∷ PartialOrderInfo → GYValue
poiGetContainedFeeValue PartialOrderInfo {..} = poiContainedFeeToValue poiContainedFee poiOfferedAsset poiAskedAsset
poiContainedFeeToValue ∷ POIContainedFee → GYAssetClass → GYAssetClass → GYValue
poiContainedFeeToValue POIContainedFee {..} offAC askAC = valueSingleton GYLovelace (fromIntegral poifLovelaces) <> valueSingleton offAC (fromIntegral poifOfferedTokens) <> valueSingleton askAC (fromIntegral poifAskedTokens)
partialOrderInfoToIn
∷ HasDexScripts a
⇒ a
→ POCVersion
→ PORefs
→ PartialOrderInfo
→ PartialOrderAction
→ GYTxIn 'PlutusV2
partialOrderInfoToIn a pocVersion pors PartialOrderInfo {..} oa =
let SomePORef PORef {..} = selectPor pors pocVersion
in GYTxIn
{ gyTxInTxOutRef = poiRef,
gyTxInWitness =
GYTxInWitnessScript
(GYInReference porValRef $ validatorToScript $ partialOrderValidator a pocVersion porRefNft)
(Just poiRawDatum)
$ redeemerFromPlutusData oa
}
partialOrderInfoToPayment ∷ PartialOrderInfo → GYValue → GYTxOut 'PlutusV2
partialOrderInfoToPayment oi v = mkGYTxOut (poiOwnerAddr oi) v (datumFromPlutusData $ txOutRefToPlutus $ poiRef oi)
partialOrderPrice ∷ PartialOrderInfo → Natural → GYValue
partialOrderPrice oi@PartialOrderInfo {poiAskedAsset} amt = valueSingleton poiAskedAsset $ fromIntegral $ partialOrderPrice' oi amt
roundFunctionForPOCVersion1_1 ∷ Integral a ⇒ Rational → a
roundFunctionForPOCVersion1_1 = floor
roundFunctionForPOCVersion ∷ Integral a ⇒ POCVersion → Rational → a
roundFunctionForPOCVersion = \case
POCVersion1 → ceiling
POCVersion1_1 → roundFunctionForPOCVersion1_1
partialOrderPrice' ∷ PartialOrderInfo → Natural → Natural
partialOrderPrice' PartialOrderInfo {poiPrice} amt = ceiling $ rationalToGHC poiPrice * toRational amt
{- | Note that at any moment, an order UTxO contains:-
* An NFT.
* Remaining offered tokens.
* Payment for tokens consumed.
* Initial deposit.
* Collected fees.
-}
expectedPaymentWithDeposit ∷ PartialOrderInfo → Bool → GYValue
expectedPaymentWithDeposit poi@PartialOrderInfo {..} isCompleteFill =
let toSubtract = valueSingleton (GYToken poiNFTCS poiNFT) 1 <> valueSingleton poiOfferedAsset (toInteger poiOfferedAmount) <> poiGetContainedFeeValue poi
toAdd = if isCompleteFill then partialOrderPrice poi poiOfferedAmount else mempty
in poiUTxOValue <> toAdd `valueMinus` toSubtract
-------------------------------------------------------------------------------
-- script address
-------------------------------------------------------------------------------
partialOrderAddr ∷ ∀ v m a. (GYDexApiQueryMonad m a, SingPOCVersionI v) ⇒ PORef v → m GYAddress
partialOrderAddr PORef {..} = do
a ← ask
scriptAddress $ partialOrderValidator a (fromSingPOCVersion $ singPOCVersion @v) porRefNft
partialOrderAddrTuple ∷ GYDexApiQueryMonad m a ⇒ PORefs → m (GYAddress :!: GYAddress)
partialOrderAddrTuple PORefs {..} = do
addrV1 ← partialOrderAddr porV1
addrV1_1 ← partialOrderAddr porV1_1
pure $ addrV1 :!: addrV1_1
-------------------------------------------------------------------------------
-- partial order NFT policy
-------------------------------------------------------------------------------
partialOrderNftPolicy
∷ ∀ v m a
. (GYDexApiQueryMonad m a, SingPOCVersionI v)
⇒ PORef v
→ m (GYMintingPolicy 'PlutusV2)
-- ^ The minting policy of the partial order NFT.
partialOrderNftPolicy por = do
a ← ask
pure $ partialOrderNftPolicy' a por
partialOrderNftPolicy'
∷ ∀ v a
. (SingPOCVersionI v, HasDexScripts a)
⇒ a
→ PORef v
→ GYMintingPolicy 'PlutusV2
-- ^ The minting policy of the partial order NFT.
partialOrderNftPolicy' a PORef {..} = partialOrderNftMintingPolicy a (fromSingPOCVersion $ singPOCVersion @v) porRefNft
partialOrderNftPolicyId
∷ ∀ v m a
. (GYDexApiQueryMonad m a, SingPOCVersionI v)
⇒ PORef v
→ m GYMintingPolicyId
-- ^ The minting policy id of the partial order NFT.
partialOrderNftPolicyId por =
mintingPolicyId <$> partialOrderNftPolicy por
-------------------------------------------------------------------------------
-- Queries
-------------------------------------------------------------------------------
partialOrders
∷ GYDexApiQueryMonad m a
⇒ PORefs
→ m (Map.Map GYTxOutRef PartialOrderInfo)
partialOrders = flip partialOrdersHavingAsset Nothing
partialOrdersHavingAsset
∷ GYDexApiQueryMonad m a
⇒ PORefs
→ Maybe GYAssetClass
→ m (Map.Map GYTxOutRef PartialOrderInfo)
partialOrdersHavingAsset pors hasAsset = do
addrTuple ← partialOrderAddrTuple pors
let pV1 :!: pV1_1 = applyToBoth (fromJust . addressToPaymentCredential) addrTuple
utxosWithDatumsV1 ← utxosAtPaymentCredentialWithDatums pV1 hasAsset
-- TODO: Add support in Atlas to query multiple payment credentials in one go.
utxosWithDatumsV1_1 ← utxosAtPaymentCredentialWithDatums pV1_1 hasAsset
policyIdV1 ← partialOrderNftPolicyId (porV1 pors)
policyIdV1_1 ← partialOrderNftPolicyId (porV1_1 pors)
let datumsV1 = utxosDatumsPureWithOriginalDatum utxosWithDatumsV1
datumsV1_1 = utxosDatumsPureWithOriginalDatum utxosWithDatumsV1_1
m1 ←
iwither
(\oref vod → makePartialOrderInfo' policyIdV1 oref vod POCVersion1)
datumsV1
m1_1 ←
iwither
(\oref vod → makePartialOrderInfo' policyIdV1_1 oref vod POCVersion1_1)
datumsV1_1
pure $! m1 <> m1_1
partialOrdersWithTransformerPredicate
∷ GYDexApiQueryMonad m a
⇒ PORefs
→ (PartialOrderInfo → Maybe b)
→ m [b]
partialOrdersWithTransformerPredicate pors transformerPredicate = do
ois ← Map.elems <$> partialOrders pors
pure $ mapMaybe transformerPredicate ois
orderByNft
∷ GYDexApiQueryMonad m a
⇒ PORefs
→ GYAssetClass
→ m (Maybe PartialOrderInfo)
orderByNft por orderNft = do
ois ← partialOrdersHavingAsset por (Just orderNft)
case Map.elems ois of
[oi] → pure $ Just oi
_ → pure Nothing
getPartialOrderVersion ∷ GYDexApiQueryMonad m a ⇒ PORefs → (GYAddress :!: GYTxOutRef) → m POCVersion
getPartialOrderVersion pors outxo = do
ps ← applyToBoth addressToPaymentCredential <$> partialOrderAddrTuple pors
getPartialOrderVersion' ps outxo
getPartialOrderVersion' ∷ GYDexApiQueryMonad m a ⇒ (Maybe GYPaymentCredential :!: Maybe GYPaymentCredential) → (GYAddress :!: GYTxOutRef) → m POCVersion
getPartialOrderVersion' (p1 :!: p1_1) (addr :!: oref) = do
let pc = addressToPaymentCredential addr
if
| p1 == pc → pure POCVersion1
| p1_1 == pc → pure POCVersion1_1
| otherwise → throwAppError $ PodOrderDoesntBelongToScript oref
getPartialOrderInfo
∷ GYDexApiQueryMonad m a
⇒ PORefs
→ GYTxOutRef
→ m PartialOrderInfo
getPartialOrderInfo pors orderRef = do
utxoWithDatum ← utxoAtTxOutRefWithDatum' orderRef
let utxo = fst utxoWithDatum
pocVersion ← getPartialOrderVersion pors (utxoAddress utxo :!: utxoRef utxo)
vod ← utxoDatumPureWithOriginalDatum' utxoWithDatum
policyId ← withSomePORef (selectPor pors pocVersion) partialOrderNftPolicyId
makePartialOrderInfo policyId orderRef vod pocVersion
getPartialOrdersInfos
∷ GYDexApiQueryMonad m a
⇒ PORefs
→ [GYTxOutRef]
→ m (Map.Map GYTxOutRef PartialOrderInfo)
getPartialOrdersInfos pors orderRefs = do
utxosWithDatums ← utxosAtTxOutRefsWithDatums orderRefs
ps ← applyToBoth addressToPaymentCredential <$> partialOrderAddrTuple pors
let vod = utxosDatumsPureWithOriginalDatum utxosWithDatums
when (Map.size vod /= length orderRefs) $ throwAppError $ PodNotAllOrderRefsPresent $ Set.fromList orderRefs `Set.difference` Map.keysSet vod
let makePartialOrderInfo'' oref v@(addr, _, _, _) = do
pocVersion ← getPartialOrderVersion' ps (addr :!: oref)
policyId ← withSomePORef (selectPor pors pocVersion) partialOrderNftPolicyId
makePartialOrderInfo policyId oref v pocVersion
Map.traverseWithKey makePartialOrderInfo'' vod
getPartialOrdersInfos' ∷ GYDexApiQueryMonad m a ⇒ PORefs → [(GYTxOutRef, Natural)] → m [(PartialOrderInfo, Natural)]
getPartialOrdersInfos' por ordersWithTokenBuyAmount = do
let ordersWithTokenBuyAmount' = Map.fromList ordersWithTokenBuyAmount
orders ← getPartialOrdersInfos por $ Map.keys ordersWithTokenBuyAmount' -- @Map.keys@ instead of @fst <$> ordersWithTokenBuyAmount@ just to make sure we don't give in duplicates, though not strictly necessary.
-- Even though we use `dropMissing`, `getPartialOrdersInfos` verify that all entries are present.
pure $ Map.elems $ Map.merge Map.dropMissing Map.dropMissing (Map.zipWithMatched (\_ poi amt → (poi, amt))) orders ordersWithTokenBuyAmount'
makePartialOrderInfo'
∷ GYDexApiQueryMonad m a
⇒ GYMintingPolicyId
→ GYTxOutRef
→ (GYAddress, GYValue, PartialOrderDatum, GYDatum)
→ POCVersion
→ m (Maybe PartialOrderInfo)
makePartialOrderInfo' policyId orderRef tuple pocVersion = catchError (Just <$> makePartialOrderInfo policyId orderRef tuple pocVersion) $ \(_ ∷ GYTxMonadException) → pure Nothing
makePartialOrderInfo
∷ GYDexApiQueryMonad m a
⇒ GYMintingPolicyId
→ GYTxOutRef
→ (GYAddress, GYValue, PartialOrderDatum, GYDatum)
→ POCVersion
→ m PartialOrderInfo
makePartialOrderInfo policyId orderRef (utxoAddr, v, PartialOrderDatum {..}, origDatum) pocVersion = do
addr ← addressFromPlutus' podOwnerAddr
key ← pubKeyHashFromPlutus' podOwnerKey
offeredAsset ← assetClassFromPlutus' podOfferedAsset
nft ← tokenNameFromPlutus' podNFT
askedAsset ← assetClassFromPlutus' podAskedAsset
when (valueAssetClass v (GYToken policyId nft) /= 1) $
throwAppError PodNftNotAvailable
return
PartialOrderInfo
{ poiRef = orderRef,
poiOwnerKey = key,
poiOwnerAddr = addr,
poiOfferedAsset = offeredAsset,
poiOfferedOriginalAmount = fromInteger podOfferedOriginalAmount,
poiOfferedAmount = fromInteger podOfferedAmount,
poiAskedAsset = askedAsset,
poiPrice = rationalFromPlutus podPrice,
poiNFT = nft,
poiStart = timeFromPlutus <$> podStart,
poiEnd = timeFromPlutus <$> podEnd,
poiPartialFills = fromInteger podPartialFills,
poiMakerLovelaceFlatFee = fromIntegral podMakerLovelaceFlatFee,
poiTakerLovelaceFlatFee = fromInteger podTakerLovelaceFlatFee,
poiContainedFee = poiContainedFeeFromPlutus podContainedFee,
poiContainedPayment = fromInteger podContainedPayment,
poiUTxOValue = v,
poiUTxOAddr = utxoAddr,
poiNFTCS = policyId,
poiVersion = pocVersion,
poiRawDatum = origDatum
}
-------------------------------------------------------------------------------
-- Tx constructors
-------------------------------------------------------------------------------
placePartialOrder
∷ GYDexApiMonad m a
⇒ PORefs
→ GYAddress
-- ^ Order owner
→ (Natural, GYAssetClass)
-- ^ Amount and asset to offer.
→ GYAssetClass
-- ^ The asset being asked for as payment.
→ GYRational
-- ^ The price for one unit of the offered asset.
→ Maybe GYTime
-- ^ The earliest time when the order can be filled (optional).
→ Maybe GYTime
-- ^ The latest time when the order can be filled (optional).
→ Maybe GYStakeCredential
-- ^ Stake credential of user. We do not support pointer reference.
→ m (GYTxSkeleton 'PlutusV2)
placePartialOrder pors = placePartialOrderWithVersion pors defaultPOCVersion
placePartialOrderWithVersion
∷ GYDexApiMonad m a
⇒ PORefs
→ POCVersion
→ GYAddress
-- ^ Order owner
→ (Natural, GYAssetClass)
-- ^ Amount and asset to offer.
→ GYAssetClass
-- ^ The asset being asked for as payment.
→ GYRational
-- ^ The price for one unit of the offered asset.
→ Maybe GYTime
-- ^ The earliest time when the order can be filled (optional).
→ Maybe GYTime
-- ^ The latest time when the order can be filled (optional).
→ Maybe GYStakeCredential
-- ^ Stake credential of user. We do not support pointer reference.
→ m (GYTxSkeleton 'PlutusV2)
placePartialOrderWithVersion pors pocVersion addr (offerAmt, offerAC) priceAC price start end stakeCred = do
SomeRefPocd (RefPocd (cfgRef :!: pocd)) ← fetchPartialOrderConfig pocVersion pors
placePartialOrderWithVersion' pors pocVersion addr (offerAmt, offerAC) priceAC price start end 0 0 stakeCred cfgRef pocd
placePartialOrder'
∷ (GYDexApiMonad m a, HasCallStack)
⇒ PORefs
→ GYAddress
-- ^ Order owner
→ (Natural, GYAssetClass)
-- ^ Amount and asset to offer.
→ GYAssetClass
-- ^ The asset being asked for as payment.
→ GYRational
-- ^ The price for one unit of the offered asset.
→ Maybe GYTime
-- ^ The earliest time when the order can be filled (optional).
→ Maybe GYTime
-- ^ The latest time when the order can be filled (optional).
→ Natural
-- ^ Additional lovelace fee.
→ Natural
-- ^ Additional fee in offered tokens.
→ Maybe GYStakeCredential
-- ^ Stake credential of user. We do not support pointer reference.
→ GYTxOutRef
→ PartialOrderConfigInfoF GYAddress
→ m (GYTxSkeleton 'PlutusV2)
placePartialOrder' pors addr (offerAmt, offerAC) priceAC price start end addLov addOff stakeCred cfgRef pocd = snd <$> placePartialOrder'' pors addr (offerAmt, offerAC) priceAC price start end addLov addOff stakeCred cfgRef pocd
placePartialOrder''
∷ (GYDexApiMonad m a, HasCallStack)
⇒ PORefs
→ GYAddress
-- ^ Order owner
→ (Natural, GYAssetClass)
-- ^ Amount and asset to offer.
→ GYAssetClass
-- ^ The asset being asked for as payment.
→ GYRational
-- ^ The price for one unit of the offered asset.
→ Maybe GYTime
-- ^ The earliest time when the order can be filled (optional).
→ Maybe GYTime
-- ^ The latest time when the order can be filled (optional).
→ Natural
-- ^ Additional lovelace fee.
→ Natural
-- ^ Additional fee in offered tokens.
→ Maybe GYStakeCredential
-- ^ Stake credential of user. We do not support pointer reference.
→ GYTxOutRef
→ PartialOrderConfigInfoF GYAddress
→ m (GYAssetClass, GYTxSkeleton 'PlutusV2)
placePartialOrder'' pors = placePartialOrderWithVersion'' pors defaultPOCVersion
placePartialOrderWithVersion'
∷ (GYDexApiMonad m a, HasCallStack)
⇒ PORefs
→ POCVersion
→ GYAddress
-- ^ Order owner
→ (Natural, GYAssetClass)
-- ^ Amount and asset to offer.
→ GYAssetClass
-- ^ The asset being asked for as payment.
→ GYRational
-- ^ The price for one unit of the offered asset.
→ Maybe GYTime
-- ^ The earliest time when the order can be filled (optional).
→ Maybe GYTime
-- ^ The latest time when the order can be filled (optional).
→ Natural
-- ^ Additional lovelace fee.
→ Natural
-- ^ Additional fee in offered tokens.
→ Maybe GYStakeCredential
-- ^ Stake credential of user. We do not support pointer reference.
→ GYTxOutRef
→ PartialOrderConfigInfoF GYAddress
→ m (GYTxSkeleton 'PlutusV2)
placePartialOrderWithVersion' pors pocVersion addr (offerAmt, offerAC) priceAC price start end addLov addOff stakeCred cfgRef pocd = snd <$> placePartialOrderWithVersion'' pors pocVersion addr (offerAmt, offerAC) priceAC price start end addLov addOff stakeCred cfgRef pocd
placePartialOrderWithVersion''
∷ (GYDexApiMonad m a, HasCallStack)
⇒ PORefs
→ POCVersion
→ GYAddress
-- ^ Order owner
→ (Natural, GYAssetClass)
-- ^ Amount and asset to offer.
→ GYAssetClass
-- ^ The asset being asked for as payment.
→ GYRational
-- ^ The price for one unit of the offered asset.
→ Maybe GYTime
-- ^ The earliest time when the order can be filled (optional).
→ Maybe GYTime
-- ^ The latest time when the order can be filled (optional).
→ Natural
-- ^ Additional lovelace fee.
→ Natural
-- ^ Additional fee in offered tokens.
→ Maybe GYStakeCredential
-- ^ Stake credential of user. We do not support pointer reference.
→ GYTxOutRef
→ PartialOrderConfigInfoF GYAddress
→ m (GYAssetClass, GYTxSkeleton 'PlutusV2)
placePartialOrderWithVersion'' pors pocVersion addr (offerAmt, offerAC) priceAC price start end addLov addOff stakeCred cfgRef pocd = do
when (offerAmt == 0) $ throwAppError $ PodNonPositiveAmount $ toInteger offerAmt
when (price <= 0) $ throwAppError $ PodNonPositivePrice price
when (offerAC == priceAC) $ throwAppError $ PodNonDifferentAssets offerAC
case (start, end) of
(Just start', Just end') → when (end' < start') $ throwAppError $ PodEndEarlierThanStart start' end'
_ → pure ()
let por@(SomePORef PORef {..}) = selectPor pors pocVersion
pkh ← addressToPubKeyHash' addr
outAddr ← withSomePORef por partialOrderAddr
nid ← networkId
let outAddr' = addressFromCredential nid (addressToPaymentCredential outAddr & fromJust) stakeCred
policy ← withSomePORef por partialOrderNftPolicy
nftRef ← someUTxOWithoutRefScript
let nftName = gyExpectedTokenName nftRef
nftRedeemer = mkNftRedeemer $ Just nftRef
nft = GYToken (mintingPolicyId policy) nftName
nftInput =
GYTxIn
{ gyTxInTxOutRef = nftRef,
gyTxInWitness = GYTxInWitnessKey
}
nftV = valueSingleton nft 1
offerAmt' = toInteger offerAmt
makerFeeFlat = fromIntegral addLov + pociMakerFeeFlat pocd
makerFeeOff = (+) (fromIntegral addOff) $ roundFunctionForPOCVersion pocVersion $ toRational offerAmt * rationalToGHC (pociMakerFeeRatio pocd)
makerFee =
valueFromLovelace makerFeeFlat
<> valueSingleton offerAC makerFeeOff
offerV =
valueSingleton offerAC offerAmt'
<> nftV
<> valueFromLovelace (toInteger $ pociMinDeposit pocd)
<> makerFee
containedFee =
PartialOrderContainedFee
{ pocfLovelaces = makerFeeFlat,
pocfOfferedTokens = makerFeeOff,
pocfAskedTokens = 0
}
od =
PartialOrderDatum
{ podOwnerKey = pubKeyHashToPlutus pkh,
podOwnerAddr = addressToPlutus addr,
podOfferedAsset = assetClassToPlutus offerAC,
podOfferedOriginalAmount = offerAmt',
podOfferedAmount = offerAmt',
podAskedAsset = assetClassToPlutus priceAC,
podPrice = rationalToPlutus price,
podNFT = tokenNameToPlutus nftName,
podStart = timeToPlutus <$> start,
podEnd = timeToPlutus <$> end,
podPartialFills = 0,
podMakerLovelaceFlatFee = makerFeeFlat,
podTakerLovelaceFlatFee = pociTakerFee pocd,
podContainedFee = containedFee,
podContainedPayment = 0
}
o = mkGYTxOut outAddr' offerV (datumFromPlutusData od)
return $
(nft,) $
mustHaveInput nftInput
<> mustHaveOutput o
<> mustMint (GYMintReference porMintRef $ mintingPolicyToScript policy) nftRedeemer nftName 1
<> mustHaveRefInput cfgRef
<> mustHaveTxMetadata stampPlaced
-- | Fills an order. If the provided amount of offered tokens to buy is equal to the offered amount, then we completely fill the order. Otherwise, it gets partially filled.
fillPartialOrder
∷ (HasCallStack, GYDexApiMonad m a)
⇒ PORefs
→ GYTxOutRef
-- ^ The order reference.
→ Natural
-- ^ The amount of offered tokens to buy.
→ Maybe SomeRefPocd
→ Natural
-- ^ Additional taker fee in payment tokens.
→ m (GYTxSkeleton 'PlutusV2)
fillPartialOrder por orderRef amt mRefPocd addTakerFee = do
oi ← getPartialOrderInfo por orderRef
fillPartialOrder' por oi amt mRefPocd addTakerFee
{- | Fills an order. If the provided amount of offered tokens to buy is equal to the offered amount, then we completely fill the order. Otherwise, it gets partially filled.
This differs from `fillPartialOrder` in that it takes fetched order information instead of it's reference.
-}
fillPartialOrder'
∷ (HasCallStack, GYDexApiMonad m a)
⇒ PORefs
→ PartialOrderInfo
-- ^ The order information.
→ Natural
-- ^ The amount of offered tokens to buy.
→ Maybe SomeRefPocd
→ Natural
-- ^ Additional taker fee in payment tokens.
→ m (GYTxSkeleton 'PlutusV2)
fillPartialOrder' por oi@PartialOrderInfo {poiOfferedAmount} amt mRefPocd addTakerFee = do
if amt == poiOfferedAmount
then mkSkeletonCompletelyFillPartialOrder por oi mRefPocd addTakerFee
else mkSkeletonPartiallyFillPartialOrder por oi amt mRefPocd addTakerFee
-- | Completely fill a partially-fillable order.
completelyFillPartialOrder
∷ (HasCallStack, GYDexApiMonad m a)
⇒ PORefs
→ GYTxOutRef
-- ^ The order reference.
→ Maybe SomeRefPocd
→ Natural
-- ^ Additional taker fee in payment tokens.
→ m (GYTxSkeleton 'PlutusV2)
completelyFillPartialOrder por orderRef mRefPocd addTakerFee = do
oi ← getPartialOrderInfo por orderRef
mkSkeletonCompletelyFillPartialOrder por oi mRefPocd addTakerFee
-- | Partially fill a partially-fillable order.
partiallyFillPartialOrder
∷ (HasCallStack, GYDexApiMonad m a)
⇒ PORefs
→ GYTxOutRef
-- ^ The order reference.
→ Natural
-- ^ The amount of offered tokens to buy.
→ Maybe SomeRefPocd
→ Natural
-- ^ Additional taker fee in payment tokens.
→ m (GYTxSkeleton 'PlutusV2)
partiallyFillPartialOrder pors orderRef amt mRefPocd addTakerFee = do
oi ← getPartialOrderInfo pors orderRef
mkSkeletonPartiallyFillPartialOrder pors oi amt mRefPocd addTakerFee
-- | Creates the complete fill skeleton of a partial order.
mkSkeletonCompletelyFillPartialOrder
∷ (HasCallStack, GYDexApiQueryMonad m a)
⇒ PORefs
→ PartialOrderInfo
→ Maybe SomeRefPocd
→ Natural
→ m (GYTxSkeleton 'PlutusV2)
mkSkeletonCompletelyFillPartialOrder pors oi@PartialOrderInfo {..} mRefPocd addTakerFee = do
pocVersion ← getPartialOrderVersion pors (poiUTxOAddr :!: poiRef)
let por@(SomePORef PORef {..}) = selectPor pors pocVersion
cs ← validFillRangeConstraints poiStart poiEnd
gycs ← ask
script ← mintingPolicyToScript <$> withSomePORef por partialOrderNftPolicy
SomeRefPocd (RefPocd (cfgRef :!: pocd)) ←
case mRefPocd of
Just refPocd → pure refPocd
Nothing → fetchPartialOrderConfig pocVersion pors
let containedFee = poiGetContainedFeeValue oi
fee = containedFee <> valueFromLovelace (fromIntegral poiTakerLovelaceFlatFee) <> valueSingleton poiAskedAsset (fromIntegral addTakerFee) -- Note that SC is fine if @addTakerFee@ is not included.
feeOutput
| fee == mempty = mempty -- We do not require a fee output.
| otherwise =
mustHaveOutput $
mkGYTxOut
(pociFeeAddr pocd)
fee
( datumFromPlutusData $
PartialOrderFeeOutput
{ pofdMentionedFees = PlutusTx.singleton (txOutRefToPlutus poiRef) (valueToPlutus containedFee),
pofdReservedValue = mempty,
pofdSpentUTxORef = Nothing
}
)
expectedValueOut = expectedPaymentWithDeposit oi True
return $
mustHaveInput (partialOrderInfoToIn gycs pocVersion pors oi CompleteFill)
<> mustHaveRefInput cfgRef
<> mustHaveOutput (partialOrderInfoToPayment oi expectedValueOut)
<> feeOutput
<> mustMint (GYMintReference porMintRef script) nothingRedeemer poiNFT (-1)
<> cs
<> mustHaveTxMetadata stampFilled
-- | Creates the partial fill skeleton of a partial order.
mkSkeletonPartiallyFillPartialOrder
∷ (HasCallStack, GYDexApiQueryMonad m a)
⇒ PORefs
→ PartialOrderInfo
→ Natural
-- ^ The amount of offered tokens to buy.
→ Maybe SomeRefPocd
→ Natural
→ m (GYTxSkeleton 'PlutusV2)
mkSkeletonPartiallyFillPartialOrder pors oi@PartialOrderInfo {..} amt mRefPocd addTakerFee = do
pocVersion ← getPartialOrderVersion pors (poiUTxOAddr :!: poiRef)
when (amt == 0) . throwAppError $ PodNonPositiveAmount $ toInteger amt
when (amt >= poiOfferedAmount) . throwAppError $ PodRequestedAmountGreaterOrEqualToOfferedAmount amt poiOfferedAmount
SomeRefPocd (RefPocd (cfgRef :!: _pocd)) ←
case mRefPocd of
Just refPocd → pure refPocd
Nothing → fetchPartialOrderConfig pocVersion pors
let price' = partialOrderPrice oi amt
od =
partialOrderInfoToPartialOrderDatum
oi
{ poiOfferedAmount = poiOfferedAmount - amt,
poiPartialFills = poiPartialFills + 1,
poiContainedFee = poiContainedFee <> mempty {poifLovelaces = fromIntegral poiTakerLovelaceFlatFee, poifAskedTokens = addTakerFee},
poiContainedPayment = poiContainedPayment + fromIntegral (valueAssetClass price' poiAskedAsset)
}
expectedValueOut = poiUTxOValue <> price' <> valueFromLovelace (fromIntegral poiTakerLovelaceFlatFee) <> valueSingleton poiAskedAsset (fromIntegral addTakerFee) `valueMinus` valueSingleton poiOfferedAsset (toInteger amt)
o = mkGYTxOut poiUTxOAddr expectedValueOut (datumFromPlutusData od)
cs ← validFillRangeConstraints poiStart poiEnd
gycs ← ask
return $
mustHaveInput (partialOrderInfoToIn gycs pocVersion pors oi $ PartialFill $ toInteger amt)
<> mustHaveOutput o
<> cs
<> mustHaveRefInput cfgRef
<> mustHaveTxMetadata stampFilled
cancelPartialOrder
∷ (HasCallStack, GYDexApiMonad m a)
⇒ PORefs
→ GYTxOutRef
→ m (GYTxSkeleton 'PlutusV2)
cancelPartialOrder por orderRef = cancelMultiplePartialOrders por (pure orderRef)
-- | Cancel multiple partial orders.
cancelMultiplePartialOrders
∷ (HasCallStack, GYDexApiMonad m a)
⇒ PORefs
→ [GYTxOutRef]
→ m (GYTxSkeleton 'PlutusV2)
cancelMultiplePartialOrders pors orderRefs = do
ois ← Map.elems <$> getPartialOrdersInfos pors orderRefs
cancelMultiplePartialOrders' pors ois
getVersionsInOrders ∷ [PartialOrderInfo] → Set POCVersion
getVersionsInOrders = foldl' (\acc PartialOrderInfo {..} → Set.insert poiVersion acc) Set.empty
addCfgRefInputs ∷ Set POCVersion → RefPocds → GYTxSkeleton 'PlutusV2
addCfgRefInputs versionsSet cfgRefs =
let RefPocd (cfgRefV1 :!: _) = selectV1RefPocd cfgRefs
RefPocd (cfgRefV1_1 :!: _) = selectV1_1RefPocd cfgRefs
in ( if Set.member POCVersion1 versionsSet
then mustHaveRefInput cfgRefV1
else mempty
)
<> ( if Set.member POCVersion1_1 versionsSet
then mustHaveRefInput cfgRefV1_1
else mempty
)
preferentiallySelectLatestVersion ∷ Set POCVersion → POCVersion
preferentiallySelectLatestVersion versionsSet = fromMaybe maxBound (Set.lookupMax versionsSet)
-- | If there is a version 1.1 order in the set, then preferentially select it's config reference datum. Idea behind this is that when orders we are interacting with are all of same version, then we select that version's config reference datum but if it's a mixed bag, we select for the latest version.
preferentiallySelectLatestPocd ∷ Set POCVersion → RefPocds → PartialOrderConfigInfo
preferentiallySelectLatestPocd versionsSet cfgRefs =
let overallVersion = preferentiallySelectLatestVersion versionsSet
SomeRefPocd (RefPocd (_ :!: pocd)) = selectRefPocd cfgRefs overallVersion
in pocd
-- | Cancel multiple partial orders.
cancelMultiplePartialOrders'
∷ (HasCallStack, GYDexApiMonad m a)
⇒ PORefs
→ [PartialOrderInfo]
→ m (GYTxSkeleton 'PlutusV2)