-
Notifications
You must be signed in to change notification settings - Fork 50
/
Ogmios.purs
1327 lines (1144 loc) · 43.8 KB
/
Ogmios.purs
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
-- | Provides types and instances to create Ogmios requests and decode
-- | its responses.
module Ctl.Internal.QueryM.Ogmios
( ChainOrigin(ChainOrigin)
, ChainPoint
, ChainTipQR(CtChainOrigin, CtChainPoint)
, CurrentEpoch(CurrentEpoch)
, DelegationsAndRewardsR(DelegationsAndRewardsR)
, ExecutionUnits
, MempoolSizeAndCapacity(MempoolSizeAndCapacity)
, MempoolSnapshotAcquired
, MempoolTransaction(MempoolTransaction)
, OgmiosAddress
, OgmiosBlockHeaderHash(OgmiosBlockHeaderHash)
, OgmiosTxOut
, OgmiosTxOutRef
, PParamRational(PParamRational)
, PoolParameters
, PoolParametersR(PoolParametersR)
, OgmiosProtocolParameters(OgmiosProtocolParameters)
, RedeemerPointer
, ScriptFailure
( ExtraRedeemers
, MissingRequiredDatums
, MissingRequiredScripts
, ValidatorFailed
, UnknownInputReferencedByRedeemer
, NonScriptInputReferencedByRedeemer
, IllFormedExecutionBudget
, NoCostModelForLanguage
)
, AdditionalUtxoSet(AdditionalUtxoSet)
, OgmiosUtxoMap
, OgmiosDatum
, OgmiosEraSummaries(OgmiosEraSummaries)
, OgmiosScript
, OgmiosSystemStart(OgmiosSystemStart)
, OgmiosTxIn
, OgmiosTxId
, SubmitTxR(SubmitTxSuccess, SubmitFail)
, TxEvaluationFailure(UnparsedError, ScriptFailures)
, TxEvaluationResult(TxEvaluationResult)
, TxEvaluationR(TxEvaluationR)
, PoolIdsR
, TxHash
, UtxoQR(UtxoQR)
, UtxoQueryResult
, acquireMempoolSnapshotCall
, aesonArray
, aesonObject
, evaluateTxCall
, queryStakePoolsCall
, mempoolSnapshotHasTxCall
, mempoolSnapshotNextTxCall
, mempoolSnpashotSizeAndCapacityCall
, mkOgmiosCallType
, mkOgmiosCallTypeNoArgs
, queryChainTipCall
, queryCurrentEpochCall
, queryEraSummariesCall
, queryProtocolParametersCall
, querySystemStartCall
, queryPoolParameters
, queryDelegationsAndRewards
, releaseMempoolCall
, submitTxCall
, slotLengthFactor
, parseIpv6String
, rationalToSubcoin
) where
import Prelude
import Aeson
( class DecodeAeson
, class EncodeAeson
, Aeson
, JsonDecodeError(TypeMismatch, MissingValue, AtKey)
, caseAesonArray
, caseAesonObject
, caseAesonString
, decodeAeson
, encodeAeson
, fromArray
, getField
, getFieldOptional
, getFieldOptional'
, isNull
, isString
, stringifyAeson
, toString
, (.:)
, (.:?)
)
import Control.Alt ((<|>))
import Control.Alternative (guard)
import Control.Monad.Reader.Trans (ReaderT(ReaderT), runReaderT)
import Ctl.Internal.Cardano.Types.NativeScript
( NativeScript
( ScriptPubkey
, ScriptAll
, ScriptAny
, ScriptNOfK
, TimelockStart
, TimelockExpiry
)
)
import Ctl.Internal.Cardano.Types.ScriptRef
( ScriptRef(NativeScriptRef, PlutusScriptRef)
)
import Ctl.Internal.Cardano.Types.Transaction
( CostModel(CostModel)
, Costmdls(Costmdls)
, ExUnitPrices
, ExUnits
, Ipv4(Ipv4)
, Ipv6(Ipv6)
, PoolMetadata(PoolMetadata)
, PoolMetadataHash(PoolMetadataHash)
, PoolPubKeyHash
, Relay(MultiHostName, SingleHostAddr, SingleHostName)
, SubCoin
, URL(URL)
, UnitInterval
)
import Ctl.Internal.Cardano.Types.Value
( Coin(Coin)
, CurrencySymbol
, NonAdaAsset
, Value
, flattenNonAdaValue
, getCurrencySymbol
, getLovelace
, getNonAdaAsset
, mkCurrencySymbol
, mkNonAdaAsset
, mkValue
, valueToCoin
)
import Ctl.Internal.Deserialization.FromBytes (fromBytes)
import Ctl.Internal.Helpers (encodeMap, showWithParens)
import Ctl.Internal.QueryM.JsonRpc2 (JsonRpc2Call, JsonRpc2Request, mkCallType)
import Ctl.Internal.Serialization.Address (Slot(Slot))
import Ctl.Internal.Serialization.Hash (Ed25519KeyHash, ed25519KeyHashFromBytes)
import Ctl.Internal.Types.BigNum (BigNum)
import Ctl.Internal.Types.BigNum (fromBigInt, fromString) as BigNum
import Ctl.Internal.Types.ByteArray
( ByteArray
, byteArrayFromIntArray
, byteArrayToHex
, hexToByteArray
)
import Ctl.Internal.Types.CborBytes (CborBytes, cborBytesToHex)
import Ctl.Internal.Types.Epoch (Epoch(Epoch))
import Ctl.Internal.Types.EraSummaries
( EraSummaries(EraSummaries)
, EraSummary(EraSummary)
, EraSummaryParameters(EraSummaryParameters)
)
import Ctl.Internal.Types.Int as Csl
import Ctl.Internal.Types.Natural (Natural)
import Ctl.Internal.Types.Natural (fromString) as Natural
import Ctl.Internal.Types.ProtocolParameters
( CoinsPerUtxoUnit(CoinsPerUtxoWord, CoinsPerUtxoByte)
, CostModelV1
, CostModelV2
, ProtocolParameters(ProtocolParameters)
, convertPlutusV1CostModel
, convertPlutusV2CostModel
)
import Ctl.Internal.Types.Rational (Rational, (%))
import Ctl.Internal.Types.Rational as Rational
import Ctl.Internal.Types.RedeemerTag (RedeemerTag)
import Ctl.Internal.Types.RedeemerTag (fromString) as RedeemerTag
import Ctl.Internal.Types.RewardAddress (RewardAddress)
import Ctl.Internal.Types.Scripts
( Language(PlutusV1, PlutusV2)
, PlutusScript(PlutusScript)
)
import Ctl.Internal.Types.SystemStart
( SystemStart
, sysStartFromOgmiosTimestamp
, sysStartToOgmiosTimestamp
)
import Ctl.Internal.Types.TokenName (TokenName, getTokenName, mkTokenName)
import Ctl.Internal.Types.VRFKeyHash (VRFKeyHash(VRFKeyHash))
import Data.Array (catMaybes, index)
import Data.Array (head, length, replicate) as Array
import Data.Bifunctor (lmap)
import Data.BigInt (BigInt)
import Data.BigInt as BigInt
import Data.Either (Either(Left, Right), either, note)
import Data.Foldable (fold, foldl)
import Data.Generic.Rep (class Generic)
import Data.Int (fromString) as Int
import Data.Map (Map)
import Data.Map as Map
import Data.Maybe (Maybe(Just, Nothing), fromJust, fromMaybe, maybe)
import Data.Newtype (class Newtype, unwrap, wrap)
import Data.Show.Generic (genericShow)
import Data.String
( Pattern(Pattern)
, Replacement(Replacement)
, indexOf
, split
, splitAt
, uncons
)
import Data.String (replaceAll) as String
import Data.String.Common (split) as String
import Data.String.Utils as StringUtils
import Data.Traversable (for, sequence, traverse)
import Data.Tuple (Tuple(Tuple), snd, uncurry)
import Data.Tuple.Nested (type (/\), (/\))
import Data.UInt (UInt)
import Data.UInt as UInt
import Foreign.Object (Object)
import Foreign.Object (singleton, toUnfoldable) as ForeignObject
import Foreign.Object as Object
import Partial.Unsafe (unsafePartial)
import Untagged.TypeCheck (class HasRuntimeType)
import Untagged.Union (type (|+|), toEither1)
--------------------------------------------------------------------------------
-- Local State Query Protocol
-- https://ogmios.dev/mini-protocols/local-state-query/
--------------------------------------------------------------------------------
-- | Queries Ogmios for the system start Datetime
querySystemStartCall :: JsonRpc2Call Unit OgmiosSystemStart
querySystemStartCall = mkOgmiosCallTypeNoArgs "queryNetwork/startTime"
-- | Queries Ogmios for the current epoch
queryCurrentEpochCall :: JsonRpc2Call Unit CurrentEpoch
queryCurrentEpochCall = mkOgmiosCallTypeNoArgs "queryLedgerState/epoch"
-- | Queries Ogmios for an array of era summaries, used for Slot arithmetic.
queryEraSummariesCall :: JsonRpc2Call Unit OgmiosEraSummaries
queryEraSummariesCall = mkOgmiosCallTypeNoArgs "queryLedgerState/eraSummaries"
-- | Queries Ogmios for the current protocol parameters
queryProtocolParametersCall :: JsonRpc2Call Unit OgmiosProtocolParameters
queryProtocolParametersCall = mkOgmiosCallTypeNoArgs
"queryLedgerState/protocolParameters"
-- | Queries Ogmios for the chain’s current tip.
queryChainTipCall :: JsonRpc2Call Unit ChainTipQR
queryChainTipCall = mkOgmiosCallTypeNoArgs "queryNetwork/tip"
queryStakePoolsCall :: JsonRpc2Call Unit PoolIdsR
queryStakePoolsCall = mkOgmiosCallTypeNoArgs "queryLedgerState/stakePools"
queryPoolParameters :: JsonRpc2Call (Array PoolPubKeyHash) PoolParametersR
queryPoolParameters = mkOgmiosCallType
{ method: "Query"
, params: \params -> { query: { poolParameters: params } }
}
queryDelegationsAndRewards :: JsonRpc2Call (Array String) DelegationsAndRewardsR
queryDelegationsAndRewards = mkOgmiosCallType
{ method: "rewardAccountSummaries"
, params: \skhs ->
{ query:
{ delegationsAndRewards: skhs
}
}
}
type OgmiosAddress = String
--------------------------------------------------------------------------------
-- Local Tx Submission Protocol
-- https://ogmios.dev/mini-protocols/local-tx-submission/
--------------------------------------------------------------------------------
-- | Sends a serialized signed transaction with its full witness through the
-- | Cardano network via Ogmios.
submitTxCall :: JsonRpc2Call (TxHash /\ CborBytes) SubmitTxR
submitTxCall = mkOgmiosCallType
{ method: "submitTransaction"
, params: \(_ /\ cbor) ->
{ transaction: { cbor: cborBytesToHex cbor }
}
}
-- | Evaluates the execution units of scripts present in a given transaction,
-- | without actually submitting the transaction.
evaluateTxCall :: JsonRpc2Call (CborBytes /\ AdditionalUtxoSet) TxEvaluationR
evaluateTxCall = mkOgmiosCallType
{ method: "evaluateTransaction"
, params: \(cbor /\ utxoqr) ->
{ transaction: { cbor: cborBytesToHex cbor }
, additionalUtxo: utxoqr
}
}
--------------------------------------------------------------------------------
-- Local Tx Monitor Protocol
-- https://ogmios.dev/mini-protocols/local-tx-monitor/
--------------------------------------------------------------------------------
acquireMempoolSnapshotCall :: JsonRpc2Call Unit MempoolSnapshotAcquired
acquireMempoolSnapshotCall =
mkOgmiosCallTypeNoArgs "acquireMempool"
mempoolSnapshotHasTxCall
:: MempoolSnapshotAcquired -> JsonRpc2Call TxHash Boolean
mempoolSnapshotHasTxCall _ = mkOgmiosCallType
{ method: "hasTransacation"
, params: { id: _ }
}
mempoolSnapshotNextTxCall
:: MempoolSnapshotAcquired -> JsonRpc2Call Unit (Maybe MempoolTransaction)
mempoolSnapshotNextTxCall _ = mkOgmiosCallType
{ method: "nextTransaction"
, params: const { fields: "all" }
}
mempoolSnpashotSizeAndCapacityCall
:: MempoolSnapshotAcquired -> JsonRpc2Call Unit MempoolSizeAndCapacity
mempoolSnpashotSizeAndCapacityCall _ =
mkOgmiosCallTypeNoArgs "sizeOfMempool"
releaseMempoolCall
:: MempoolSnapshotAcquired -> JsonRpc2Call Unit String
releaseMempoolCall _ =
mkOgmiosCallTypeNoArgs "releaseMempool"
--------------------------------------------------------------------------------
-- Local Tx Monitor Query Response & Parsing
--------------------------------------------------------------------------------
newtype MempoolSnapshotAcquired = AwaitAcquired Slot
instance Show MempoolSnapshotAcquired where
show (AwaitAcquired slot) = "(AwaitAcquired " <> show slot <> ")"
instance DecodeAeson MempoolSnapshotAcquired where
decodeAeson =
map AwaitAcquired <<< aesonObject
(flip getField "AwaitAcquired" >=> flip getField "slot")
-- | The acquired snapshot’s size (in bytes), number of transactions, and capacity
-- | (in bytes).
newtype MempoolSizeAndCapacity = MempoolSizeAndCapacity
{ capacity :: Int
, currentSize :: Int
, numberOfTxs :: Int
}
derive instance Generic MempoolSizeAndCapacity _
derive instance Newtype MempoolSizeAndCapacity _
instance Show MempoolSizeAndCapacity where
show = genericShow
instance DecodeAeson MempoolSizeAndCapacity where
decodeAeson = aesonObject \o -> do
capacity <- getField o "capacity"
currentSize <- getField o "currentSize"
numberOfTxs <- getField o "numberOfTxs"
pure $ wrap { capacity, currentSize, numberOfTxs }
newtype MempoolTransaction = MempoolTransaction
{ id :: OgmiosTxId
, raw :: String
}
derive instance Generic MempoolTransaction _
derive instance Newtype MempoolTransaction _
instance Show MempoolTransaction where
show = genericShow
instance DecodeAeson MempoolTransaction where
decodeAeson = aesonObject \o -> do
id <- o .: "id"
raw <- o .: "raw"
pure $ MempoolTransaction { id, raw }
--------------------------------------------------------------------------------
-- Helpers
--------------------------------------------------------------------------------
mkOgmiosCallTypeNoArgs
:: forall (o :: Type). String -> JsonRpc2Call Unit o
mkOgmiosCallTypeNoArgs method =
mkOgmiosCallType { method, params: const {} }
mkOgmiosCallType
:: forall (a :: Type) (i :: Type) (o :: Type)
. EncodeAeson (JsonRpc2Request a)
=> { method :: String, params :: i -> a }
-> JsonRpc2Call i o
mkOgmiosCallType =
mkCallType { jsonrpc: "2.0" }
---------------- TX SUBMISSION QUERY RESPONSE & PARSING
data SubmitTxR
= SubmitTxSuccess TxHash
| SubmitFail (Array Aeson)
derive instance Generic SubmitTxR _
instance Show SubmitTxR where
show = genericShow
type TxHash = ByteArray
instance DecodeAeson SubmitTxR where
decodeAeson = aesonObject $
\o ->
( getField o "transaction" >>= flip getField "id" >>= hexToByteArray
>>> maybe (Left (TypeMismatch "Expected hexstring"))
(pure <<< SubmitTxSuccess)
) <|> (SubmitFail <$> getField o "SubmitFail")
---------------- SYSTEM START QUERY RESPONSE & PARSING
newtype OgmiosSystemStart = OgmiosSystemStart SystemStart
derive instance Generic OgmiosSystemStart _
derive instance Newtype OgmiosSystemStart _
derive newtype instance Eq OgmiosSystemStart
instance Show OgmiosSystemStart where
show = genericShow
instance DecodeAeson OgmiosSystemStart where
decodeAeson =
caseAesonString (Left (TypeMismatch "Timestamp string"))
(map wrap <<< lmap TypeMismatch <<< sysStartFromOgmiosTimestamp)
instance EncodeAeson OgmiosSystemStart where
encodeAeson = encodeAeson <<< sysStartToOgmiosTimestamp <<< unwrap
---------------- CURRENT EPOCH QUERY RESPONSE & PARSING
newtype CurrentEpoch = CurrentEpoch BigInt
derive instance Generic CurrentEpoch _
derive instance Newtype CurrentEpoch _
derive newtype instance DecodeAeson CurrentEpoch
derive newtype instance EncodeAeson CurrentEpoch
derive newtype instance Eq CurrentEpoch
derive newtype instance Ord CurrentEpoch
instance Show CurrentEpoch where
show (CurrentEpoch ce) = showWithParens "CurrentEpoch" ce
---------------- ERA SUMMARY QUERY RESPONSE & PARSING
newtype OgmiosEraSummaries = OgmiosEraSummaries EraSummaries
derive instance Generic OgmiosEraSummaries _
derive instance Newtype OgmiosEraSummaries _
derive newtype instance Eq OgmiosEraSummaries
instance Show OgmiosEraSummaries where
show = genericShow
instance DecodeAeson OgmiosEraSummaries where
decodeAeson = aesonArray (map (wrap <<< wrap) <<< traverse decodeEraSummary)
where
decodeEraSummary :: Aeson -> Either JsonDecodeError EraSummary
decodeEraSummary = aesonObject \o -> do
start <- getField o "start"
-- The field "end" is required by Ogmios API, but it can optionally return
-- Null, so we want to fail if the field is absent but make Null value
-- acceptable in presence of the field (hence why "end" is wrapped in
-- `Maybe`).
end' <- getField o "end"
end <- if isNull end' then pure Nothing else Just <$> decodeAeson end'
parameters <- decodeEraSummaryParameters =<< getField o "parameters"
pure $ wrap { start, end, parameters }
decodeEraSummaryParameters
:: Object Aeson -> Either JsonDecodeError EraSummaryParameters
decodeEraSummaryParameters o = do
epochLength <- getField o "epochLength"
slotLength <- wrap <$> ((*) slotLengthFactor <$>
(flip getField "seconds" =<< getField o "slotLength"))
safeZone <- fromMaybe zero <$> getField o "safeZone"
pure $ wrap { epochLength, slotLength, safeZone }
instance EncodeAeson OgmiosEraSummaries where
encodeAeson (OgmiosEraSummaries (EraSummaries eraSummaries)) =
fromArray $ map encodeEraSummary eraSummaries
where
encodeEraSummary :: EraSummary -> Aeson
encodeEraSummary (EraSummary { start, end, parameters }) =
encodeAeson
{ "start": start
, "end": end
, "parameters": encodeEraSummaryParameters parameters
}
encodeEraSummaryParameters :: EraSummaryParameters -> Aeson
encodeEraSummaryParameters (EraSummaryParameters params) =
encodeAeson
{ "epochLength": params.epochLength
, "slotLength": params.slotLength
, "safeZone": params.safeZone
}
-- Ogmios returns `slotLength` in seconds, and we use milliseconds,
-- so we need to convert between them.
slotLengthFactor :: Number
slotLengthFactor = 1000.0
---------------- DELEGATIONS & REWARDS QUERY RESPONSE & PARSING
newtype DelegationsAndRewardsR = DelegationsAndRewardsR
( Map String
{ rewards :: Maybe Coin
, delegate :: Maybe PoolPubKeyHash
}
)
derive instance Generic DelegationsAndRewardsR _
derive instance Newtype DelegationsAndRewardsR _
instance DecodeAeson DelegationsAndRewardsR where
decodeAeson aeson = do
obj :: Object (Object Aeson) <- decodeAeson aeson
kvs <- for (Object.toUnfoldable obj :: Array _) \(Tuple k objParams) -> do
rewards <- map Coin <$> objParams .:? "rewards"
delegate <- objParams .:? "delegate"
pure $ k /\ { rewards, delegate }
pure $ DelegationsAndRewardsR $ Map.fromFoldable kvs
---------------- POOL PARAMETERS QUERY RESPONSE & PARSING
type PoolParameters =
{ vrfKeyhash :: VRFKeyHash
-- needed to prove that the pool won the lottery
, pledge :: BigNum
, cost :: BigNum -- >= pparams.minPoolCost
, margin :: UnitInterval -- proportion that goes to the reward account
, rewardAccount :: RewardAddress
, poolOwners :: Array Ed25519KeyHash
-- payment key hashes that contribute to pledge amount
, relays :: Array Relay
, poolMetadata :: Maybe PoolMetadata
}
newtype PoolParametersR = PoolParametersR (Map String PoolParameters)
derive instance Newtype PoolParametersR _
derive instance Generic PoolParametersR _
instance Show PoolParametersR where
show = genericShow
instance DecodeAeson PoolParametersR where
decodeAeson aeson = do
obj :: Object (Object Aeson) <- decodeAeson aeson
kvs <- for (Object.toUnfoldable obj :: Array _) \(Tuple k objParams) -> do
poolParams <- decodePoolParameters objParams
pure $ k /\ poolParams
pure $ PoolParametersR $ Map.fromFoldable kvs
decodePoolParameters :: Object Aeson -> Either JsonDecodeError PoolParameters
decodePoolParameters objParams = do
vrfKeyhash <- decodeVRFKeyHash =<< objParams .: "vrf"
pledge <- objParams .: "pledge"
cost <- objParams .: "cost"
margin <- decodeUnitInterval =<< objParams .: "margin"
rewardAccount <- objParams .: "rewardAccount"
poolOwners <- objParams .: "owners"
relayArr <- objParams .: "relays"
relays <- for relayArr decodeRelay
poolMetadata <- objParams .:? "metadata" >>= traverse decodePoolMetadata
pure
{ vrfKeyhash
, pledge
, cost
, margin
, rewardAccount
, poolOwners
, relays
, poolMetadata
}
decodeVRFKeyHash :: Aeson -> Either JsonDecodeError VRFKeyHash
decodeVRFKeyHash = aesonString $ \vrfKeyhashHex -> do
vrfKeyhashBytes <- note (TypeMismatch "VRFKeyHash") $ hexToByteArray
vrfKeyhashHex
note (TypeMismatch "VRFKeyHash") $ VRFKeyHash <$> fromBytes
(wrap vrfKeyhashBytes)
decodeUnitInterval :: Aeson -> Either JsonDecodeError UnitInterval
decodeUnitInterval aeson = do
str <- decodeAeson aeson
case String.split (Pattern "/") str of
[ num, den ] -> do
numerator <- note (TypeMismatch "BigNum") $ BigNum.fromString num
denominator <- note (TypeMismatch "BigNum") $ BigNum.fromString den
pure
{ numerator
, denominator
}
_ -> Left $ TypeMismatch "UnitInterval"
decodeIpv4 :: Aeson -> Either JsonDecodeError Ipv4
decodeIpv4 aeson = do
str <- decodeAeson aeson
case String.split (Pattern ".") str of
bs@[ _, _, _, _ ] -> do
ints <- for bs $
note (TypeMismatch "Ipv4") <<< Int.fromString
Ipv4 <$> note (TypeMismatch "Ipv4") (byteArrayFromIntArray ints)
_ -> Left $ TypeMismatch "Ipv4"
decodeIpv6 :: Aeson -> Either JsonDecodeError Ipv6
decodeIpv6 aeson = do
decodeAeson aeson >>= parseIpv6String >>> note (TypeMismatch "Ipv6")
parseIpv6String :: String -> Maybe Ipv6
parseIpv6String str = do
let
parts = String.split (Pattern ":") str
partsFixed =
if Array.length parts < 8 then
-- Normalize double colon
-- see https://ipcisco.com/lesson/ipv6-address/
do
part <- parts
if part == "" then
Array.replicate (8 - Array.length parts + 1) ""
else
pure part
else
parts
guard (Array.length partsFixed == 8)
let
padded = String.replaceAll (Pattern " ") (Replacement "0") $ fold $
partsFixed
<#> StringUtils.padStart 4
Ipv6 <$> hexToByteArray padded
decodeRelay :: Aeson -> Either JsonDecodeError Relay
decodeRelay aeson = do
obj <- decodeAeson aeson
let
decodeSingleHostAddr = do
port <- obj .:? "port"
ipv4 <- obj .:? "ipv4" >>= traverse decodeIpv4
ipv6 <- obj .:? "ipv6" >>= traverse decodeIpv6
pure $ SingleHostAddr { port, ipv4, ipv6 }
decodeSingleHostName = do
port <- obj .: "port"
dnsName <- obj .: "hostname"
pure $ SingleHostName { port, dnsName }
decodeMultiHostName = do
dnsName <- obj .: "hostname"
pure $ MultiHostName { dnsName }
decodeSingleHostName <|> decodeSingleHostAddr <|> decodeMultiHostName
decodePoolMetadata :: Aeson -> Either JsonDecodeError PoolMetadata
decodePoolMetadata aeson = do
obj <- decodeAeson aeson
hash <- obj .: "hash" >>= note (TypeMismatch "PoolMetadataHash")
<<< map PoolMetadataHash
<<< hexToByteArray
url <- obj .: "url" <#> URL
pure $ PoolMetadata { hash, url }
---------------- TX EVALUATION QUERY RESPONSE & PARSING
type RedeemerPointer = { redeemerTag :: RedeemerTag, redeemerIndex :: Natural }
type ExecutionUnits = { memory :: Natural, steps :: Natural }
newtype TxEvaluationR = TxEvaluationR
(Either TxEvaluationFailure TxEvaluationResult)
derive instance Newtype TxEvaluationR _
derive instance Generic TxEvaluationR _
instance Show TxEvaluationR where
show = genericShow
instance DecodeAeson TxEvaluationR where
decodeAeson aeson = (wrap <<< Right <$> decodeAeson aeson) <|>
(wrap <<< Left <$> decodeAeson aeson)
newtype TxEvaluationResult = TxEvaluationResult
(Map RedeemerPointer ExecutionUnits)
derive instance Newtype TxEvaluationResult _
derive instance Generic TxEvaluationResult _
instance Show TxEvaluationResult where
show = genericShow
instance DecodeAeson TxEvaluationResult where
decodeAeson = aesonArray $ \array -> do
TxEvaluationResult <<< Map.fromFoldable <$>
traverse decodeRdmrPtrExUnitsItem array
where
decodeRdmrPtrExUnitsItem :: Aeson -> Either JsonDecodeError (RedeemerPointer /\ ExecutionUnits)
decodeRdmrPtrExUnitsItem elem = do
(redeemerPtrRaw /\ exUnitsAeson) :: String /\ Aeson <- decodeAeson elem
redeemerPtr <- decodeRedeemerPointer redeemerPtrRaw
flip aesonObject exUnitsAeson $ \exUnitsObj -> do
memory <- getField exUnitsObj "memory"
cpu <- getField exUnitsObj "cpu"
pure $ redeemerPtr /\ { memory, steps: cpu }
redeemerPtrTypeMismatch :: JsonDecodeError
redeemerPtrTypeMismatch = TypeMismatch
"Expected redeemer pointer to be encoded as: \
\^(spend|mint|certificate|withdrawal):[0-9]+$"
decodeRedeemerPointer :: String -> Either JsonDecodeError RedeemerPointer
decodeRedeemerPointer redeemerPtrRaw = note redeemerPtrTypeMismatch
case split (Pattern ":") redeemerPtrRaw of
[ tagRaw, indexRaw ] ->
{ redeemerTag: _, redeemerIndex: _ }
<$> RedeemerTag.fromString tagRaw
<*> Natural.fromString indexRaw
_ -> Nothing
type OgmiosDatum = String
type OgmiosScript = String
type OgmiosTxId = String
type OgmiosTxIn = { txId :: OgmiosTxId, index :: Int }
data ScriptFailure
= ExtraRedeemers (Array RedeemerPointer)
| MissingRequiredDatums
{ provided :: Maybe (Array OgmiosDatum), missing :: Array OgmiosDatum }
| MissingRequiredScripts
{ resolved :: Map RedeemerPointer OgmiosScript
, missing :: Array OgmiosScript
}
| ValidatorFailed { error :: String, traces :: Array String }
| UnknownInputReferencedByRedeemer OgmiosTxIn
| NonScriptInputReferencedByRedeemer OgmiosTxIn
| IllFormedExecutionBudget (Maybe ExecutionUnits)
| NoCostModelForLanguage String
derive instance Generic ScriptFailure _
instance Show ScriptFailure where
show = genericShow
-- The following cases are fine to fall through into unparsed error:
-- IncompatibleEra
-- AdditionalUtxoOverlap
-- NotEnoughSynced
-- CannotCreateEvaluationContext
data TxEvaluationFailure
= UnparsedError String
| ScriptFailures (Map RedeemerPointer (Array ScriptFailure))
derive instance Generic TxEvaluationFailure _
instance Show TxEvaluationFailure where
show = genericShow
type ObjectParser = ReaderT (Object Aeson) (Either JsonDecodeError)
liftField
:: forall (a :: Type) (b :: Type)
. DecodeAeson a
=> String
-> (a -> Either JsonDecodeError b)
-> ObjectParser b
liftField f act = ReaderT (flip getField f >=> act)
instance DecodeAeson ScriptFailure where
decodeAeson = aesonObject $ runReaderT cases
where
cases :: ObjectParser ScriptFailure
cases = decodeExtraRedeemers
<|> decodeMissingRequiredDatums
<|> decodeMissingRequiredScripts
<|> decodeValidatorFailed
<|> decodeUnknownInputReferencedByRedeemer
<|> decodeNonScriptInputReferencedByRedeemer
<|> decodeIllFormedExecutionBudget
<|> decodeNoCostModelForLanguage
<|> defaultCase
defaultCase :: ObjectParser ScriptFailure
defaultCase = ReaderT $ const $ Left $ TypeMismatch "Expected ScriptFailure"
decodeExtraRedeemers :: ObjectParser ScriptFailure
decodeExtraRedeemers = ExtraRedeemers <$> liftField "extraRedeemers"
(traverse decodeRedeemerPointer)
decodeMissingRequiredDatums :: ObjectParser ScriptFailure
decodeMissingRequiredDatums = liftField "missingRequiredDatums" \o -> do
pure $ MissingRequiredDatums o
decodeMissingRequiredScripts :: ObjectParser ScriptFailure
decodeMissingRequiredScripts = liftField "missingRequiredScripts" \o -> do
resolvedKV <- ForeignObject.toUnfoldable <$> getField o "resolved"
resolved <- Map.fromFoldable <$> for (resolvedKV :: Array _)
\(k /\ v) -> (_ /\ v) <$> decodeRedeemerPointer k
missing <- getField o "missing"
pure $ MissingRequiredScripts { resolved, missing }
decodeValidatorFailed :: ObjectParser ScriptFailure
decodeValidatorFailed = liftField "validatorFailed" \o -> do
pure $ ValidatorFailed o
decodeUnknownInputReferencedByRedeemer :: ObjectParser ScriptFailure
decodeUnknownInputReferencedByRedeemer = liftField
"unknownInputReferencedByRedeemer"
\o -> do
pure $ UnknownInputReferencedByRedeemer o
decodeNonScriptInputReferencedByRedeemer :: ObjectParser ScriptFailure
decodeNonScriptInputReferencedByRedeemer = liftField
"nonScriptInputReferencedByRedeemer"
\o -> do
pure $ NonScriptInputReferencedByRedeemer o
decodeIllFormedExecutionBudget :: ObjectParser ScriptFailure
decodeIllFormedExecutionBudget = liftField "illFormedExecutionBudget" \o ->
do
pure $ IllFormedExecutionBudget o
decodeNoCostModelForLanguage :: ObjectParser ScriptFailure
decodeNoCostModelForLanguage = liftField "noCostModelForLanguage" \o -> do
pure $ NoCostModelForLanguage o
instance DecodeAeson TxEvaluationFailure where
decodeAeson = aesonObject $ runReaderT cases
where
cases :: ObjectParser TxEvaluationFailure
cases = decodeScriptFailures <|> defaultCase
defaultCase :: ObjectParser TxEvaluationFailure
defaultCase = ReaderT \o ->
pure (UnparsedError (stringifyAeson (encodeAeson o)))
decodeScriptFailures :: ObjectParser TxEvaluationFailure
decodeScriptFailures = ReaderT \o -> do
scriptFailuresKV <- ForeignObject.toUnfoldable
<$> (getField o "EvaluationFailure" >>= flip getField "ScriptFailures")
scriptFailures <- Map.fromFoldable <$> for (scriptFailuresKV :: Array _)
\(k /\ v) -> do
v' <- decodeAeson v
(_ /\ v') <$> decodeRedeemerPointer k
pure $ ScriptFailures scriptFailures
---------------- PROTOCOL PARAMETERS QUERY RESPONSE & PARSING
-- | A version of `Rational` with Aeson instance that decodes from `x/y`
-- | representation, instead of `{ numerator, denominator }`
newtype PParamRational = PParamRational Rational
derive instance Newtype PParamRational _
derive instance Generic PParamRational _
instance Show PParamRational where
show = genericShow
instance DecodeAeson PParamRational where
decodeAeson =
caseAesonString (Left err)
\string -> do
case String.split (Pattern "/") string of
[ numeratorStr, denominatorStr ] -> note err do
numerator <- BigInt.fromString numeratorStr
denominator <- BigInt.fromString denominatorStr
PParamRational <$> numerator % denominator
_ -> Left err
where
err :: JsonDecodeError
err = TypeMismatch "PParamRaional"
rationalToSubcoin :: PParamRational -> Maybe SubCoin
rationalToSubcoin (PParamRational rat) = do
numerator <- BigNum.fromBigInt $ Rational.numerator rat
denominator <- BigNum.fromBigInt $ Rational.denominator rat
pure { numerator, denominator }
-- | A type that corresponds to Ogmios response.
type ProtocolParametersRaw =
{ "minFeeCoefficient" :: UInt
, "minFeeConstant" ::
{ "lovelace" :: UInt }
, "minUtxoDepositCoefficient" :: BigInt
, "maxBlockBodySize" ::
{ "bytes" :: UInt }
, "maxBlockHeaderSize" ::
{ "bytes" :: UInt }
, "maxTransactionSize" ::
{ "bytes" :: UInt }
, "maxValueSize" ::
{ "bytes" :: UInt }
, "stakeCredentialDeposit" ::
{ "lovelace" :: BigInt }
, "stakePoolDeposit" ::
{ "lovelace" :: BigInt }
, "stakePoolRetirementEpochBound" :: BigInt
, "desiredNumberOfStakePools" :: UInt
, "stakePoolPledgeInfluence" :: PParamRational
, "monetaryExpansion" :: PParamRational
, "treasuryExpansion" :: PParamRational
, "version" ::
{ "major" :: UInt
, "minor" :: UInt
}
, "minStakePoolCost" ::
{ "lovelace" :: BigInt }
, "plutusCostModels" ::
{ "plutus:v1" :: Array Csl.Int
, "plutus:v2" :: Maybe (Array Csl.Int)
}
, "scriptExecutionPrices" ::
{ "memory" :: PParamRational
, "cpu" :: PParamRational
}
, "maxExecutionUnitsPerTransaction" ::
{ "memory" :: BigInt
, "cpu" :: BigInt
}
, "maxExecutionUnitsPerBlock" ::
{ "memory" :: BigInt
, "cpu" :: BigInt
}
, "collateralPercentage" :: UInt
, "maxCollateralInputs" :: UInt
}
newtype OgmiosProtocolParameters = OgmiosProtocolParameters ProtocolParameters
derive instance Newtype OgmiosProtocolParameters _
derive instance Generic OgmiosProtocolParameters _
derive instance Eq OgmiosProtocolParameters
instance Show OgmiosProtocolParameters where
show = genericShow
instance DecodeAeson OgmiosProtocolParameters where
decodeAeson aeson = do
ps :: ProtocolParametersRaw <- decodeAeson aeson
prices <- decodePrices ps
pure $ OgmiosProtocolParameters $ ProtocolParameters
{ protocolVersion: ps.version.major /\ ps.version.minor
-- The following two parameters were removed from Babbage
, decentralization: zero
, extraPraosEntropy: Nothing
, maxBlockHeaderSize: ps.maxBlockHeaderSize.bytes
, maxBlockBodySize: ps.maxBlockBodySize.bytes
, maxTxSize: ps.maxTransactionSize.bytes
, txFeeFixed: ps.minFeeConstant.lovelace
, txFeePerByte: ps.minFeeCoefficient
, stakeAddressDeposit: Coin ps.stakeCredentialDeposit.lovelace
, stakePoolDeposit: Coin ps.stakePoolDeposit.lovelace
, minPoolCost: Coin ps.minStakePoolCost.lovelace
, poolRetireMaxEpoch: Epoch ps.stakePoolRetirementEpochBound
, stakePoolTargetNum: ps.desiredNumberOfStakePools
, poolPledgeInfluence: unwrap ps.stakePoolPledgeInfluence
, monetaryExpansion: unwrap ps.monetaryExpansion
, treasuryCut: unwrap ps.treasuryExpansion -- Rational
, coinsPerUtxoUnit: CoinsPerUtxoByte (Coin ps.minUtxoDepositCoefficient)
, costModels: Costmdls $ Map.fromFoldable $ catMaybes
[ pure
( PlutusV1 /\ CostModel
ps.plutusCostModels."plutus:v1"
)
, (PlutusV2 /\ _) <<< CostModel <$>
ps.plutusCostModels."plutus:v2"
]
, prices: prices
, maxTxExUnits: decodeExUnits ps.maxExecutionUnitsPerTransaction
, maxBlockExUnits: decodeExUnits ps.maxExecutionUnitsPerBlock
, maxValueSize: ps.maxValueSize.bytes
, collateralPercent: ps.collateralPercentage
, maxCollateralInputs: ps.maxCollateralInputs
}
where
decodeExUnits
:: { memory :: BigInt, cpu :: BigInt } -> ExUnits
decodeExUnits { memory, cpu } = { mem: memory, steps: cpu }
decodePrices
:: ProtocolParametersRaw -> Either JsonDecodeError ExUnitPrices
decodePrices ps = note (TypeMismatch "ExUnitPrices") do
memPrice <- rationalToSubcoin ps.scriptExecutionPrices.memory
stepPrice <- rationalToSubcoin ps.scriptExecutionPrices.cpu
pure { memPrice, stepPrice } -- ExUnits
---------------- CHAIN TIP QUERY RESPONSE & PARSING
data ChainTipQR
= CtChainOrigin ChainOrigin
| CtChainPoint ChainPoint
derive instance Generic ChainTipQR _
instance Show ChainTipQR where