forked from Plutonomicon/cardano-transaction-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContract.purs
2182 lines (1952 loc) · 77.8 KB
/
Contract.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
module Test.Ctl.Testnet.Contract
( suite
) where
import Prelude
import Cardano.AsCbor (decodeCbor)
import Cardano.Plutus.ApplyArgs (applyArgs)
import Cardano.Serialization.Lib (fromBytes)
import Cardano.Transaction.Builder
( DatumWitness(DatumValue)
, OutputWitness(PlutusScriptOutput)
, ScriptWitness(ScriptValue)
, TransactionBuilderStep(Pay, SpendOutput)
)
import Cardano.Types
( Address(EnterpriseAddress)
, Credential(PubKeyHashCredential, ScriptHashCredential)
, GeneralTransactionMetadata
, PaymentCredential(PaymentCredential)
, StakeCredential(StakeCredential)
, TransactionUnspentOutput(TransactionUnspentOutput)
, _input
, _output
)
import Cardano.Types.AssetName as AssetName
import Cardano.Types.Coin as Coin
import Cardano.Types.Int as Int
import Cardano.Types.Mint as Mint
import Cardano.Types.PlutusData (unit) as PlutusData
import Cardano.Types.PlutusScript as PlutusScript
import Cardano.Types.PrivateKey (toPublicKey) as PrivateKey
import Cardano.Types.PublicKey (hash) as PublicKey
import Cardano.Types.RedeemerDatum as RedeemerDatum
import Cardano.Types.TransactionUnspentOutput (toUtxoMap)
import Cardano.Types.Value (lovelaceValueOf)
import Contract.Address
( PaymentPubKeyHash(PaymentPubKeyHash)
, StakePubKeyHash
, getNetworkId
, mkAddress
)
import Contract.AuxiliaryData (setGeneralTxMetadata)
import Contract.BalanceTxConstraints
( BalanceTxConstraintsBuilder
, mustUseAdditionalUtxos
) as BalanceTxConstraints
import Contract.BalanceTxConstraints
( mustNotSpendUtxosWithOutRefs
, mustUseCollateralUtxos
)
import Contract.Chain (currentTime, waitUntilSlot)
import Contract.Config (KnownWallet(Nami, Gero, Flint, Lode, NuFi), walletName)
import Contract.Hashing (datumHash, nativeScriptHash)
import Contract.Keys (privateKeyFromBytes)
import Contract.Log (logInfo')
import Contract.Metadata as Metadatum
import Contract.Monad (Contract, liftContractE, liftContractM, liftedM)
import Contract.Numeric.BigNum as BigNum
import Contract.PlutusData
( PlutusData(Bytes, Integer, List)
, getDatumByHash
, getDatumsByHashes
, getDatumsByHashesWithErrors
, unitRedeemer
)
import Contract.Prelude (liftM, mconcat)
import Contract.Prim.ByteArray
( byteArrayFromAscii
, hexToByteArray
, hexToByteArrayUnsafe
, hexToRawBytes
)
import Contract.ScriptLookups as Lookups
import Contract.Scripts
( ValidatorHash
, getScriptByHash
, getScriptsByHashes
, validatorHash
)
import Contract.Test (ContractTest)
import Contract.Test.Assert (runChecks)
import Contract.Test.Testnet
( InitialUTxOs
, InitialUTxOsWithStakeKey
, withStakeKey
, withWallets
)
import Contract.Time (Slot(Slot), getEraSummaries)
import Contract.Transaction
( BalanceTxError(BalanceInsufficientError, InsufficientCollateralUtxos)
, DataHash
, NativeScript(ScriptPubkey, ScriptNOfK, ScriptAll)
, OutputDatum(OutputDatum, OutputDatumHash)
, ScriptRef(PlutusScriptRef, NativeScriptRef)
, TransactionHash(TransactionHash)
, TransactionInput(TransactionInput)
, TransactionOutput(TransactionOutput)
, awaitTxConfirmed
, balanceTx
, balanceTxE
, buildTx
, createAdditionalUtxos
, getTxAuxiliaryData
, lookupTxHash
, signTransaction
, submit
, submitTxFromConstraints
, withBalancedTx
, withBalancedTxs
)
import Contract.TxConstraints (TxConstraints)
import Contract.TxConstraints as Constraints
import Contract.UnbalancedTx (mkUnbalancedTx, mkUnbalancedTxE)
import Contract.Utxos (UtxoMap, utxosAt)
import Contract.Value (Coin(Coin), Value, coinToValue)
import Contract.Value as Value
import Contract.Wallet
( getWalletAddresses
, getWalletBalance
, getWalletCollateral
, getWalletUtxos
, isWalletAvailable
, ownDrepPubKey
, ownDrepPubKeyHash
, ownPaymentPubKeyHashes
, ownRegisteredPubStakeKeys
, ownStakePubKeyHashes
, ownUnregisteredPubStakeKeys
, signData
, withKeyWallet
)
import Control.Monad.Error.Class (try)
import Control.Monad.Trans.Class (lift)
import Control.Parallel (parallel, sequential)
import Ctl.Examples.AdditionalUtxos (contract) as AdditionalUtxos
import Ctl.Examples.AlwaysMints (alwaysMintsPolicy)
import Ctl.Examples.AlwaysSucceeds as AlwaysSucceeds
import Ctl.Examples.AwaitTxConfirmedWithTimeout as AwaitTxConfirmedWithTimeout
import Ctl.Examples.BalanceTxConstraints as BalanceTxConstraintsExample
import Ctl.Examples.Cip30 as Cip30
import Ctl.Examples.ContractTestUtils as ContractTestUtils
import Ctl.Examples.ECDSA as ECDSA
import Ctl.Examples.Helpers (mkAssetName, mustPayToPubKeyStakeAddress)
import Ctl.Examples.IncludeDatum as IncludeDatum
import Ctl.Examples.Lose7Ada as AlwaysFails
import Ctl.Examples.ManyAssets as ManyAssets
import Ctl.Examples.MintsMultipleTokens (contract) as MintsMultipleTokens
import Ctl.Examples.NativeScriptMints (contract) as NativeScriptMints
import Ctl.Examples.OneShotMinting (contract) as OneShotMinting
import Ctl.Examples.PaysWithDatum (contract) as PaysWithDatum
import Ctl.Examples.PlutusV2.InlineDatum as InlineDatum
import Ctl.Examples.PlutusV2.OneShotMinting (contract) as OneShotMintingV2
import Ctl.Examples.PlutusV2.ReferenceInputsAndScripts (contract) as ReferenceInputsAndScripts
import Ctl.Examples.PlutusV2.Scripts.AlwaysMints (alwaysMintsPolicyScriptV2)
import Ctl.Examples.PlutusV2.Scripts.AlwaysSucceeds (alwaysSucceedsScriptV2)
import Ctl.Examples.Schnorr as Schnorr
import Ctl.Examples.SendsToken (contract) as SendsToken
import Ctl.Examples.TxChaining (contract) as TxChaining
import Ctl.Internal.Test.UtxoDistribution (TestWalletSpec)
import Ctl.Internal.Types.Interval (getSlotLength)
import Ctl.Internal.Wallet.Cip30Mock (withCip30Mock)
import Data.Array (head, (!!))
import Data.Array (singleton) as Array
import Data.Either (Either(Left, Right), hush, isLeft, isRight)
import Data.Foldable (fold, foldM, length)
import Data.Lens (view)
import Data.Map as Map
import Data.Maybe (Maybe(Just, Nothing), fromJust, fromMaybe, isJust)
import Data.Newtype (unwrap, wrap)
import Data.Traversable (traverse, traverse_)
import Data.Tuple (Tuple(Tuple))
import Data.Tuple.Nested (type (/\), (/\))
import Data.UInt (UInt)
import Effect.Class (liftEffect)
import Effect.Exception (error, throw)
import JS.BigInt as BigInt
import Mote (group, skip, test)
import Mote.TestPlanM (TestPlanM)
import Partial.Unsafe (unsafePartial)
import Safe.Coerce (coerce)
import Test.Ctl.Fixtures
( fullyAppliedScriptFixture
, nativeScriptFixture1
, nativeScriptFixture2
, nativeScriptFixture3
, nativeScriptFixture4
, nativeScriptFixture5
, nativeScriptFixture6
, nativeScriptFixture7
, partiallyAppliedScriptFixture
, unappliedScriptFixture
)
import Test.Ctl.Testnet.Common (privateDrepKey, privateStakeKey)
import Test.Ctl.Testnet.Utils (getLockedInputs, submitAndLog)
import Test.Ctl.Testnet.UtxoDistribution (checkUtxoDistribution)
import Test.Spec.Assertions
( expectError
, shouldEqual
, shouldNotEqual
, shouldReturn
, shouldSatisfy
)
suite :: TestPlanM ContractTest Unit
suite = do
group "WaitUntilSlot" do
test "wait for slot far in the future" do
withWallets unit \_ -> do
void $ waitUntilSlot $ Slot $ BigNum.fromInt 10
void $ waitUntilSlot $ Slot $ BigNum.fromInt 160
void $ waitUntilSlot $ Slot $ BigNum.fromInt 161
group "Regressions" do
skip $ test
"#1441 - Mint many assets at once - fails with TooManyAssetsInOutput"
do
let
distribution :: InitialUTxOs
distribution =
[ BigNum.fromInt 1000_000_000
, BigNum.fromInt 2000_000_000
]
withWallets distribution \alice -> do
withKeyWallet alice ManyAssets.contract
test
"#1509 - Collateral set to one of the inputs in mustNotSpendUtxosWithOutRefs "
do
let
someUtxos =
[ BigNum.fromInt 5_000_000
, BigNum.fromInt 5_000_000
]
withWallets someUtxos \alice -> do
withKeyWallet alice do
pkh <- liftedM "Failed to get PKH" $ head <$> withKeyWallet alice
ownPaymentPubKeyHashes
stakePkh <- join <<< head <$> withKeyWallet alice
ownStakePubKeyHashes
utxos <- fromMaybe Map.empty <$> getWalletUtxos
let
constraints :: Constraints.TxConstraints
constraints = mustPayToPubKeyStakeAddress pkh stakePkh
$ Value.lovelaceValueOf
$ BigNum.fromInt 2_000_000
lookups :: Lookups.ScriptLookups
lookups = mempty
ubTx /\ usedUtxos <- mkUnbalancedTx lookups constraints
res <-
( balanceTxE ubTx usedUtxos
(mustNotSpendUtxosWithOutRefs $ Map.keys utxos)
)
res `shouldSatisfy` isLeft
test "#1480 - test that does nothing but fails" do
let
someUtxos =
[ BigNum.fromInt 2_000_000
, BigNum.fromInt 3_000_000
]
privateStakeKey1 =
wrap $ unsafePartial $ fromJust
$ privateKeyFromBytes =<< hexToRawBytes
"63361c4c4a075a538d37e062c1ed0706d3f0a94b013708e8f5ab0a0ca1df163d"
privateStakeKey2 =
wrap $ unsafePartial $ fromJust
$ privateKeyFromBytes =<< hexToRawBytes
"6ffb1c4c4a075a538d37e062c1ed0706d3f0a94b013708e8f5ab0a0ca1df163d"
distribution =
[ withStakeKey privateStakeKey someUtxos
, withStakeKey privateStakeKey1 someUtxos
, withStakeKey privateStakeKey2 someUtxos
]
withWallets distribution \_ → pure unit
group "Contract interface" do
test
"mustUseCollateralUtxos should not fail if enough UTxOs are provided"
do
let
someUtxos =
[ BigNum.fromInt 5_000_000
, BigNum.fromInt 5_000_000
]
withWallets (someUtxos /\ someUtxos) \(alice /\ bob) -> do
bobsCollateral <- withKeyWallet bob do
fromMaybe Map.empty <$> getWalletUtxos
withKeyWallet alice do
validator <- AlwaysSucceeds.alwaysSucceedsScript
let vhash = validatorHash validator
logInfo' "Attempt to lock value"
txId <- AlwaysSucceeds.payToAlwaysSucceeds vhash
awaitTxConfirmed txId
logInfo' "Try to spend locked values"
scriptAddress <- mkAddress (wrap $ ScriptHashCredential vhash)
Nothing
utxos <- utxosAt scriptAddress
utxo <-
liftM
( error
( "The id "
<> show txId
<> " does not have output locked at: "
<> show scriptAddress
)
)
$ head (lookupTxHash txId utxos)
let
usedUtxos = Map.union utxos $ toUtxoMap [ utxo ]
ubTx <- buildTx
[ SpendOutput
utxo
( Just
$ PlutusScriptOutput (ScriptValue validator)
RedeemerDatum.unit
$ Just
$ DatumValue
$ PlutusData.unit
)
]
res <- balanceTxE ubTx usedUtxos
(mustUseCollateralUtxos bobsCollateral)
res `shouldSatisfy` isRight
test
"mustUseCollateralUtxos should fail if not enough UTxOs are provided"
do
let
someUtxos =
[ BigNum.fromInt 5_000_000
, BigNum.fromInt 5_000_000
]
withWallets someUtxos \alice -> do
withKeyWallet alice do
validator <- AlwaysSucceeds.alwaysSucceedsScript
let vhash = validatorHash validator
logInfo' "Attempt to lock value"
txId <- AlwaysSucceeds.payToAlwaysSucceeds vhash
awaitTxConfirmed txId
logInfo' "Try to spend locked values"
scriptAddress <- mkAddress (wrap $ ScriptHashCredential vhash)
Nothing
utxos <- utxosAt scriptAddress
utxo <-
liftM
( error
( "The id "
<> show txId
<> " does not have output locked at: "
<> show scriptAddress
)
)
$ head (lookupTxHash txId utxos)
let
usedUtxos = Map.union utxos $ toUtxoMap [ utxo ]
ubTx <- buildTx
[ SpendOutput
utxo
( Just
$ PlutusScriptOutput (ScriptValue validator)
RedeemerDatum.unit
$ Just
$ DatumValue
$ PlutusData.unit
)
]
res <- balanceTxE ubTx usedUtxos (mustUseCollateralUtxos Map.empty)
res `shouldSatisfy` case _ of
Left (InsufficientCollateralUtxos mp) -> Map.isEmpty mp
_ -> false
test "Collateral selection: UTxO with lower amount is selected" do
let
distribution :: InitialUTxOs /\ InitialUTxOs
distribution =
[ BigNum.fromInt 10_000_000
, BigNum.fromInt 20_000_000
] /\
[ BigNum.fromInt 2_000_000_000 ]
withWallets distribution \(alice /\ bob) -> do
withKeyWallet alice do
getWalletCollateral >>= liftEffect <<< case _ of
Nothing -> throw "Unable to get collateral"
Just
[ TransactionUnspentOutput
{ output: output }
] -> do
let amount = (unwrap output).amount
unless (amount == lovelaceValueOf (BigNum.fromInt 10_000_000))
$ throw "Wrong UTxO selected as collateral"
Just _ -> do
-- not a bug, but unexpected
throw "More than one UTxO in collateral"
withKeyWallet bob do
pure unit -- sign, balance, submit, etc.
test
"Payment keyhash to payment keyhash transaction (Pkh2Pkh example)"
do
let
distribution :: InitialUTxOs
distribution =
[ BigNum.fromInt 10_000_000
, BigNum.fromInt 20_000_000
, BigNum.fromInt 20_000_000
]
withWallets distribution \alice -> do
logInfo' "407 hi"
checkUtxoDistribution distribution alice
pkh <- liftedM "Failed to get PKH" $ head <$> withKeyWallet alice
ownPaymentPubKeyHashes
stakePkh <- join <<< head <$> withKeyWallet alice ownStakePubKeyHashes
withKeyWallet alice $ pkh2PkhContract pkh stakePkh
test
"Base Address to Base Address transaction (Pkh2Pkh example, but with stake keys)"
do
let
aliceUtxos =
[ BigNum.fromInt 20_000_000
, BigNum.fromInt 20_000_000
]
distribution = withStakeKey privateStakeKey aliceUtxos
withWallets distribution \alice -> do
checkUtxoDistribution distribution alice
pkh <- liftedM "Failed to get PKH" $ head <$> withKeyWallet alice
ownPaymentPubKeyHashes
stakePkh <- join <<< head <$> withKeyWallet alice
ownStakePubKeyHashes
stakePkh `shouldSatisfy` isJust
withKeyWallet alice $ pkh2PkhContract pkh stakePkh
test
"Payment key hash to payment key hash Tx: running two contracts in parallel (Pkh2Pkh example)"
do
let
aliceUtxos =
[ BigNum.fromInt 20_000_000
, BigNum.fromInt 20_000_000
]
bobUtxos =
[ BigNum.fromInt 20_000_000
, BigNum.fromInt 20_000_000
]
distribution :: InitialUTxOs /\ InitialUTxOs
distribution = aliceUtxos /\ bobUtxos
withWallets distribution \wallets@(alice /\ bob) -> do
checkUtxoDistribution distribution wallets
sequential ado
parallel $ withKeyWallet alice do
pkh <- liftedM "Failed to get PKH" $ head <$> withKeyWallet bob
ownPaymentPubKeyHashes
stakePkh <- join <<< head <$> withKeyWallet bob
ownStakePubKeyHashes
pkh2PkhContract pkh stakePkh
parallel $ withKeyWallet bob do
pkh <- liftedM "Failed to get PKH" $ head <$> withKeyWallet alice
ownPaymentPubKeyHashes
stakePkh <- join <<< head <$> withKeyWallet alice
ownStakePubKeyHashes
pkh2PkhContract pkh stakePkh
in unit
test
"Base Address to Base Address hash Tx: running two contracts in parallel (Pkh2Pkh example)"
do
let
aliceUtxos =
[ BigNum.fromInt 1_000_000_000
, BigNum.fromInt 20_000_000
]
bobUtxos =
[ BigNum.fromInt 1_000_000_000
, BigNum.fromInt 20_000_000
]
distribution =
withStakeKey privateStakeKey aliceUtxos
/\ withStakeKey privateStakeKey bobUtxos
withWallets distribution \wallets@(alice /\ bob) ->
do
checkUtxoDistribution distribution wallets
sequential ado
parallel $ withKeyWallet alice do
pkh <- liftedM "Failed to get PKH" $ head <$> withKeyWallet bob
ownPaymentPubKeyHashes
stakePkh <- join <<< head <$> withKeyWallet bob
ownStakePubKeyHashes
pkh2PkhContract pkh stakePkh
parallel $ withKeyWallet bob do
pkh <- liftedM "Failed to get PKH" $ head <$> withKeyWallet
alice
ownPaymentPubKeyHashes
stakePkh <- join <<< head <$> withKeyWallet alice
ownStakePubKeyHashes
pkh2PkhContract pkh stakePkh
in unit
test "Tx confirmation fails after timeout (awaitTxConfirmedWithTimeout)" do
let
distribution = withStakeKey privateStakeKey
[ BigNum.fromInt 1_000_000_000 ]
withWallets distribution \_ ->
AwaitTxConfirmedWithTimeout.contract
test "NativeScript (multisig) support: require all signers" do
let
distribution
:: InitialUTxOs /\ InitialUTxOs /\ InitialUTxOs /\ InitialUTxOs
distribution =
[ BigNum.fromInt 20_000_000
, BigNum.fromInt 20_000_000
]
/\
[ BigNum.fromInt 20_000_000
, BigNum.fromInt 20_000_000
]
/\
[ BigNum.fromInt 20_000_000
, BigNum.fromInt 20_000_000
]
/\
[ BigNum.fromInt 20_000_000
, BigNum.fromInt 20_000_000
]
withWallets distribution \(alice /\ bob /\ charlie /\ dan) ->
do
alicePaymentPKH <- liftedM "Unable to get Alice's PKH" $
(coerce <<< head) <$> withKeyWallet alice ownPaymentPubKeyHashes
bobPaymentPKH <- liftedM "Unable to get Bob's PKH" $
(coerce <<< head) <$> withKeyWallet bob ownPaymentPubKeyHashes
charliePaymentPKH <- liftedM "Unable to get Charlie's PKH" $
(coerce <<< head) <$> withKeyWallet charlie
ownPaymentPubKeyHashes
danPaymentPKH <- liftedM "Unable to get Dan's PKH" $
(coerce <<< head) <$> withKeyWallet dan ownPaymentPubKeyHashes
let
nativeScript = ScriptAll
[ ScriptPubkey alicePaymentPKH
, ScriptPubkey bobPaymentPKH
, ScriptPubkey charliePaymentPKH
, ScriptPubkey danPaymentPKH
]
nsHash = nativeScriptHash nativeScript
-- Alice locks 10 ADA at mutlisig script
txId <- withKeyWallet alice do
let
constraints :: TxConstraints
constraints = Constraints.mustPayToNativeScript nsHash
$ Value.lovelaceValueOf
$ BigNum.fromInt 10_000_000
lookups :: Lookups.ScriptLookups
lookups = mempty
ubTx /\ usedUtxos <- mkUnbalancedTx lookups constraints
bsTx <- signTransaction =<< balanceTx ubTx usedUtxos mempty
txId <- submit bsTx
awaitTxConfirmed txId
pure txId
-- Bob attempts to unlock and send Ada to Charlie
withKeyWallet bob do
-- First, he should find the transaction input where Ada is locked
nsAddr <- mkAddress (wrap $ ScriptHashCredential nsHash) Nothing
utxos <- utxosAt nsAddr
txInput <- liftContractM "Unable to get UTxO" $
view _input <$> lookupTxHash txId utxos !! 0
let
constraints :: TxConstraints
constraints =
Constraints.mustPayToPubKey (coerce alicePaymentPKH)
(Value.lovelaceValueOf $ BigNum.fromInt 10_000_000)
<> Constraints.mustSpendNativeScriptOutput txInput
nativeScript
-- Note that specifying required signers is optional:
--
-- <> Constraints.mustBeSignedBy (coerce alicePaymentPKH)
-- <> Constraints.mustBeSignedBy (coerce bobPaymentPKH)
-- <> Constraints.mustBeSignedBy (coerce charliePaymentPKH)
-- <> Constraints.mustBeSignedBy (coerce danPaymentPKH)
--
-- The maximum needed number of signers is calculated from
-- the script itself, so we know how much space to allocate
-- for signatures on fee calculation stage.
lookups :: Lookups.ScriptLookups
lookups = Lookups.unspentOutputs utxos
ubTx /\ usedUtxos <- mkUnbalancedTx lookups constraints
tx <- signTransaction =<< balanceTx ubTx usedUtxos mempty
let
signWithWallet txToSign wallet =
withKeyWallet wallet (signTransaction txToSign)
txSigned <- foldM signWithWallet tx [ alice, bob, charlie, dan ]
submit txSigned >>= awaitTxConfirmed
test "NativeScript support: require N=2 of K=4 signers" do
let
distribution
:: InitialUTxOs /\ InitialUTxOs /\ InitialUTxOs /\ InitialUTxOs
distribution =
[ BigNum.fromInt 50_000_000
, BigNum.fromInt 50_000_000
]
/\
[ BigNum.fromInt 50_000_000
, BigNum.fromInt 50_000_000
]
/\
[ BigNum.fromInt 50_000_000
, BigNum.fromInt 50_000_000
]
/\
[ BigNum.fromInt 50_000_000
, BigNum.fromInt 50_000_000
]
withWallets distribution \(alice /\ bob /\ charlie /\ dan) ->
do
alicePaymentPKH <- liftedM "Unable to get Alice's PKH" $
(coerce <<< head) <$> withKeyWallet alice ownPaymentPubKeyHashes
bobPaymentPKH <- liftedM "Unable to get Bob's PKH" $
(coerce <<< head) <$> withKeyWallet bob ownPaymentPubKeyHashes
charliePaymentPKH <- liftedM "Unable to get Charlie's PKH" $
(coerce <<< head) <$> withKeyWallet charlie
ownPaymentPubKeyHashes
danPaymentPKH <- liftedM "Unable to get Dan's PKH" $
(coerce <<< head) <$> withKeyWallet dan ownPaymentPubKeyHashes
let
nativeScript = ScriptNOfK 2
[ ScriptPubkey alicePaymentPKH
, ScriptPubkey bobPaymentPKH
, ScriptPubkey charliePaymentPKH
, ScriptPubkey danPaymentPKH
]
nsHash = nativeScriptHash nativeScript
-- Alice locks 10 ADA at mutlisig script
txId <- withKeyWallet alice do
let
constraints :: TxConstraints
constraints = Constraints.mustPayToNativeScript nsHash
$ Value.lovelaceValueOf
$ BigNum.fromInt 10_000_000
lookups :: Lookups.ScriptLookups
lookups = mempty
ubTx /\ usedUtxos <- mkUnbalancedTx lookups constraints
bsTx <- signTransaction =<< balanceTx ubTx usedUtxos mempty
txId <- submit bsTx
awaitTxConfirmed txId
pure txId
-- Bob attempts to unlock and send Ada to Charlie
withKeyWallet bob do
-- First, he should find the transaction input where Ada is locked
nsAddr <- mkAddress (wrap $ ScriptHashCredential nsHash) Nothing
utxos <- utxosAt nsAddr
txInput <- liftContractM "Unable to get UTxO" $
view _input <$> lookupTxHash txId utxos !! 0
let
constraints :: TxConstraints
constraints =
Constraints.mustPayToPubKey (coerce alicePaymentPKH)
(Value.lovelaceValueOf $ BigNum.fromInt 10_000_000)
<> Constraints.mustSpendNativeScriptOutput txInput
nativeScript
lookups :: Lookups.ScriptLookups
lookups = Lookups.unspentOutputs utxos
ubTx /\ usedUtxos <- mkUnbalancedTx lookups constraints
-- Bob signs the tx
tx <- signTransaction =<< balanceTx ubTx usedUtxos mempty
let
signWithWallet txToSign wallet =
withKeyWallet wallet (signTransaction txToSign)
-- Dan signs the tx
txSigned <- foldM signWithWallet tx [ dan ]
submit txSigned >>= awaitTxConfirmed
test "An always-succeeding minting policy" do
let
distribution :: InitialUTxOs
distribution =
[ BigNum.fromInt 5_000_000
, BigNum.fromInt 50_000_000
]
withWallets distribution \alice -> do
withKeyWallet alice do
mp <- alwaysMintsPolicy
let cs = PlutusScript.hash mp
tn <- liftContractM "Cannot make token name"
$ AssetName.mkAssetName
=<< byteArrayFromAscii "TheToken"
let
constraints :: Constraints.TxConstraints
constraints = Constraints.mustMintValue
$ Mint.singleton cs tn
$ Int.fromInt 100
lookups :: Lookups.ScriptLookups
lookups = Lookups.plutusMintingPolicy mp
ubTx /\ usedUtxos <- mkUnbalancedTx lookups constraints
bsTx <- signTransaction =<< balanceTx ubTx usedUtxos mempty
submitAndLog bsTx
test "mustProduceAtLeast spends native token" do
let
distribution :: InitialUTxOs
distribution =
[ BigNum.fromInt 5_000_000
, BigNum.fromInt 50_000_000
]
withWallets distribution \alice -> do
withKeyWallet alice do
mp <- alwaysMintsPolicy
let cs = PlutusScript.hash mp
tn <- mkAssetName "TheToken"
-- Minting
let
constraints :: Constraints.TxConstraints
constraints = Constraints.mustMintValue
$ Mint.singleton cs tn
$ Int.fromInt 100
lookups :: Lookups.ScriptLookups
lookups = Lookups.plutusMintingPolicy mp
txHash <- submitTxFromConstraints lookups constraints
awaitTxConfirmed txHash
-- Spending same amount
pkh <-
liftedM "Failed to get own PKH" $ head <$> ownPaymentPubKeyHashes
let
constraints' :: Constraints.TxConstraints
constraints' = Constraints.mustProduceAtLeast
$ Value.singleton cs tn
$ BigNum.fromInt 100
lookups' = lookups <> Lookups.ownPaymentPubKeyHash pkh
txHash' <- submitTxFromConstraints lookups' constraints'
void $ awaitTxConfirmed txHash'
test "mustProduceAtLeast fails to produce more tokens than there is" do
let
distribution :: InitialUTxOs
distribution =
[ BigNum.fromInt 5_000_000
, BigNum.fromInt 50_000_000
]
withWallets distribution \alice -> do
withKeyWallet alice do
mp <- alwaysMintsPolicy
let cs = PlutusScript.hash mp
tn <- mkAssetName "TheToken"
-- Minting
let
constraints :: Constraints.TxConstraints
constraints = Constraints.mustMintValue
$ Mint.singleton cs tn
$ Int.fromInt 100
lookups :: Lookups.ScriptLookups
lookups = Lookups.plutusMintingPolicy mp
txHash <- submitTxFromConstraints lookups constraints
awaitTxConfirmed txHash
-- Spending more than minted amount
pkh <-
liftedM "Failed to get own PKH" $ head <$> ownPaymentPubKeyHashes
let
constraints' :: Constraints.TxConstraints
constraints' = Constraints.mustProduceAtLeast
$ Value.singleton cs tn
$ BigNum.fromInt 101
lookups' = lookups <> Lookups.ownPaymentPubKeyHash pkh
ubTx /\ usedUtxos <- mkUnbalancedTx lookups' constraints'
result <- balanceTxE ubTx usedUtxos mempty
result `shouldSatisfy` isLeft
test "mustSpendAtLeast succeeds to spend" do
let
distribution :: InitialUTxOs
distribution =
[ BigNum.fromInt 5_000_000
, BigNum.fromInt 50_000_000
]
withWallets distribution \alice -> do
withKeyWallet alice do
mp <- alwaysMintsPolicy
let cs = PlutusScript.hash mp
tn <- mkAssetName "TheToken"
-- Minting
let
constraints :: Constraints.TxConstraints
constraints = Constraints.mustMintValue
$ Mint.singleton cs tn
$ Int.fromInt 100
lookups :: Lookups.ScriptLookups
lookups = Lookups.plutusMintingPolicy mp
txHash <- submitTxFromConstraints lookups constraints
awaitTxConfirmed txHash
-- Spending same amount
pkh <-
liftedM "Failed to get own PKH" $ head <$> ownPaymentPubKeyHashes
let
constraints' :: Constraints.TxConstraints
constraints' = Constraints.mustSpendAtLeast
$ Value.singleton cs tn
$ BigNum.fromInt 100
lookups' = lookups <> Lookups.ownPaymentPubKeyHash pkh
txHash' <- submitTxFromConstraints lookups' constraints'
void $ awaitTxConfirmed txHash'
test "mustSpendAtLeast fails to spend more token that there is" do
let
distribution :: InitialUTxOs
distribution =
[ BigNum.fromInt 5_000_000
, BigNum.fromInt 50_000_000
]
withWallets distribution \alice -> do
withKeyWallet alice do
mp <- alwaysMintsPolicy
let cs = PlutusScript.hash mp
tn <- mkAssetName "TheToken"
-- Minting
let
constraints :: Constraints.TxConstraints
constraints = Constraints.mustMintValue
$ Mint.singleton cs tn
$ Int.fromInt 100
lookups :: Lookups.ScriptLookups
lookups = Lookups.plutusMintingPolicy mp
txHash <- submitTxFromConstraints lookups constraints
awaitTxConfirmed txHash
-- Spending more than minted amount
pkh <-
liftedM "Failed to get own PKH" $ head <$> ownPaymentPubKeyHashes
let
constraints' :: Constraints.TxConstraints
constraints' = Constraints.mustSpendAtLeast
$ Value.singleton cs tn
$ BigNum.fromInt 101
lookups' = lookups <> Lookups.ownPaymentPubKeyHash pkh
ubTx /\ usedUtxos <- mkUnbalancedTx lookups' constraints'
result <- balanceTxE ubTx usedUtxos mempty
result `shouldSatisfy` isLeft
test "Minting using NativeScript (multisig) as a policy" do
let
distribution :: InitialUTxOs
distribution =
[ BigNum.fromInt 5_000_000
, BigNum.fromInt 50_000_000
]
withWallets distribution \alice -> do
withKeyWallet alice NativeScriptMints.contract
test "Getting datums by hashes" do
withWallets unit \_ -> do
let
mkDatumHash :: String -> DataHash
mkDatumHash str = unsafePartial $ fromJust $ decodeCbor <<< wrap =<<
hexToByteArray str
-- Nothing is expected, because we are in an empty chain.
-- This test only checks for ability to connect to the datum-querying
-- backend.
logInfo' <<< show =<< getDatumByHash
( mkDatumHash
"42be572a6d9a8a2ec0df04f14b0d4fcbe4a7517d74975dfff914514f12316252"
)
logInfo' <<< show =<< getDatumsByHashes
[ mkDatumHash
"777093fe6dfffdb3bd2033ad71745f5e2319589e36be4bc9c8cca65ac2bfeb8f"
, mkDatumHash
"e8cb7d18e81b0be160c114c563c020dcc7bf148a1994b73912db3ea1318d488b"
]
logInfo' <<< show =<< getDatumsByHashesWithErrors
[ mkDatumHash
"777093fe6dfffdb3bd2033ad71745f5e2319589e36be4bc9c8cca65ac2bfeb8f"
, mkDatumHash
"e8cb7d18e81b0be160c114c563c020dcc7bf148a1994b73912db3ea1318d488b"
]
-- FIXME: script integrity hash mismatch
skip $ test "GetDatumsByHashes" do
let
distribution :: InitialUTxOs
distribution =
[ BigNum.fromInt 5_000_000
, BigNum.fromInt 50_000_000
]
datum1 = Integer $ BigInt.fromInt 1
datum2 = Integer $ BigInt.fromInt 2
datums :: Array PlutusData
datums = [ datum2, datum1 ]
let
payToTest :: ValidatorHash -> Contract TransactionHash
payToTest vhash = do
let
constraints = mconcat
[ Constraints.mustPayToScript vhash datum1
Constraints.DatumWitness
(Value.lovelaceValueOf $ BigNum.fromInt 1_000_000)
, Constraints.mustPayToScript vhash datum2
Constraints.DatumWitness
(Value.lovelaceValueOf $ BigNum.fromInt 1_000_000)
, Constraints.mustIncludeDatum datum1
, Constraints.mustIncludeDatum datum2
]
lookups :: Lookups.ScriptLookups
lookups = mempty
submitTxFromConstraints lookups constraints
withWallets distribution \alice -> do
withKeyWallet alice do
validator <- AlwaysSucceeds.alwaysSucceedsScript
let vhash = validatorHash validator
logInfo' "Running GetDatums submittx"
txId <- payToTest vhash
awaitTxConfirmed txId
logInfo' "Tx submitted successfully, trying to fetch datum"
let
hash1 = datumHash datum1
hash2 = datumHash datum2
hashes = map datumHash datums
actualDatums1 <- getDatumsByHashes hashes
actualDatums1 `shouldEqual`
( Map.fromFoldable
[ hash1 /\ datum1
, hash2 /\ datum2
]
)
actualDatums2 <- getDatumsByHashesWithErrors hashes
actualDatums2 `shouldEqual`
( Map.fromFoldable
[ hash1 /\ Right datum1
, hash2 /\ Right datum2
]
)
test "GetScriptByHash" do
let
distribution :: InitialUTxOs
distribution = [ BigNum.fromInt 50_000_000 ]
withWallets distribution \alice -> do
withKeyWallet alice do
validator1 <- AlwaysSucceeds.alwaysSucceedsScript