/
Error.hs
1132 lines (1066 loc) · 50.2 KB
/
Error.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 DataKinds #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
-- |
-- Copyright: © 2018-2022 IOHK
-- License: Apache-2.0
--
-- 'IsServerError' definition along with most instances
--
module Cardano.Wallet.Api.Http.Server.Error
( IsServerError (..)
, liftHandler
, liftE
, apiError
, err425
, showT
, handler
)
where
import Prelude
import Cardano.Address.Script
( Cosigner (..) )
import Cardano.Ledger.Alonzo.TxInfo
( TranslationError (..) )
import Cardano.Tx.Balance.Internal.CoinSelection
( SelectionBalanceError (..)
, SelectionCollateralError
, SelectionError (..)
, SelectionOutputError (..)
, SelectionOutputErrorInfo (..)
, SelectionOutputSizeExceedsLimitError
, SelectionOutputTokenQuantityExceedsLimitError (..)
, UnableToConstructChangeError (..)
, WalletSelectionContext
)
import Cardano.Wallet
( ErrAddCosignerKey (..)
, ErrCannotJoin (..)
, ErrCannotQuit (..)
, ErrConstructSharedWallet (..)
, ErrConstructTx (..)
, ErrCreateMigrationPlan (..)
, ErrCreateRandomAddress (..)
, ErrDerivePublicKey (..)
, ErrFetchRewards (..)
, ErrGetPolicyId (..)
, ErrGetTransaction (..)
, ErrImportAddress (..)
, ErrImportRandomAddress (..)
, ErrInvalidDerivationIndex (..)
, ErrListTransactions (..)
, ErrMkTransaction (..)
, ErrNoSuchTransaction (..)
, ErrNoSuchWallet (..)
, ErrNotASequentialWallet (..)
, ErrPostTx (..)
, ErrReadAccountPublicKey (..)
, ErrReadPolicyPublicKey (..)
, ErrReadRewardAccount (..)
, ErrRemoveTx (..)
, ErrSelectAssets (..)
, ErrSignMetadataWith (..)
, ErrSignPayment (..)
, ErrStakePoolDelegation (..)
, ErrStartTimeLaterThanEndTime (..)
, ErrSubmitTransaction (..)
, ErrSubmitTx (..)
, ErrUpdatePassphrase (..)
, ErrUpdateSealedTx (..)
, ErrWalletAlreadyExists (..)
, ErrWalletNotInitialized (..)
, ErrWalletNotResponding (..)
, ErrWithRootKey (..)
, ErrWithdrawalNotBeneficial (..)
, ErrWitnessTx (..)
, ErrWritePolicyPublicKey (..)
, ErrWriteTxEra (..)
, ErrWrongPassphrase (..)
, WalletException (..)
)
import Cardano.Wallet.Address.Derivation
( DerivationType (Hardened, Soft), Index (Index) )
import Cardano.Wallet.Address.Discovery.Shared
( ErrAddCosigner (..), ErrScriptTemplate (..) )
import Cardano.Wallet.Api.Hex
( hexText )
import Cardano.Wallet.Api.Types
( ApiCosignerIndex (..)
, ApiCredentialType (..)
, Iso8601Time (..)
, toApiEra
)
import Cardano.Wallet.Api.Types.Error
( ApiError (..)
, ApiErrorBalanceTxUnderestimatedFee (..)
, ApiErrorInfo (..)
, ApiErrorMessage (..)
, ApiErrorNodeNotYetInRecentEra (..)
, ApiErrorSharedWalletNoSuchCosigner (..)
, ApiErrorTxOutputLovelaceInsufficient (..)
)
import Cardano.Wallet.Primitive.Slotting
( PastHorizonException )
import Cardano.Wallet.Primitive.Types.TokenMap
( Flat (..) )
import Cardano.Wallet.Primitive.Types.Tx.SealedTx
( serialisedTx )
import Cardano.Wallet.Shelley.Transaction
( KeyWitnessCount (..) )
import Cardano.Wallet.Transaction
( ErrAssignRedeemers (..), ErrSignTx (..) )
import Cardano.Wallet.Write.Tx.Balance
( ErrBalanceTx (..), ErrBalanceTxInternalError (..) )
import Control.Monad.Except
( ExceptT, lift, withExceptT )
import Control.Monad.Trans.Except
( throwE )
import Data.Generics.Internal.VL
( view, (^.) )
import Data.IntCast
( intCast, intCastMaybe )
import Data.List
( isInfixOf, isPrefixOf, isSubsequenceOf )
import Data.Maybe
( isJust )
import Data.Quantity
( Quantity (Quantity) )
import Data.Text
( Text )
import Data.Text.Class
( ToText (..) )
import Data.Word
( Word32 )
import Fmt
( blockListF', build, fmt, listF, pretty )
import Network.HTTP.Media
( renderHeader )
import Network.HTTP.Types
( hContentType )
import Network.Wai
( Request (pathInfo) )
import Safe
( fromJustNote )
import Servant
( Accept (contentType), JSON, Proxy (Proxy) )
import Servant.Server
( Handler (Handler)
, ServerError (..)
, err400
, err403
, err404
, err409
, err500
, err501
, err503
)
import qualified Cardano.Api as Cardano
import qualified Cardano.Wallet.Primitive.Types.Coin as Coin
import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle
import qualified Cardano.Wallet.Primitive.Types.TokenMap as TokenMap
import qualified Cardano.Wallet.Write.Tx as Write
import qualified Data.Aeson as Aeson
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.Foldable as F
import qualified Data.List as L
import qualified Data.List.NonEmpty as NE
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
-- | Maps types to servant error responses.
class IsServerError e where
-- | A structured human-readable error code to return to API clients.
toServerError :: e -> ServerError
-- | Lift our wallet layer into servant 'Handler', by mapping each error to a
-- corresponding servant error.
liftHandler :: IsServerError e => ExceptT e IO a -> Handler a
liftHandler action = Handler (withExceptT toServerError action)
liftE :: IsServerError e => e -> Handler a
liftE = liftHandler . throwE
-- | Lift an IO action into servant 'Handler'
handler :: IO a -> Handler a
handler = Handler . lift
apiError :: ServerError -> ApiErrorInfo -> Text -> ServerError
apiError err info messageUnformatted = err
{ errBody = Aeson.encode ApiError {info, message}
, errHeaders =
(hContentType, renderHeader $ contentType $ Proxy @JSON)
: errHeaders err
}
where
message = ApiErrorMessage (T.replace "\n" " " messageUnformatted)
err425 :: ServerError
err425 = ServerError 425 "Too early" "" []
-- | Small helper to easy show things to Text
showT :: Show a => a -> Text
showT = T.pack . show
instance IsServerError WalletException where
toServerError = \case
ExceptionNoSuchWallet e -> toServerError e
ExceptionSignMetadataWith e -> toServerError e
ExceptionDerivePublicKey e -> toServerError e
ExceptionAddCosignerKey e -> toServerError e
ExceptionConstructSharedWallet e -> toServerError e
ExceptionReadAccountPublicKey e -> toServerError e
ExceptionSignPayment e -> toServerError e
ExceptionBalanceTx e -> toServerError e
ExceptionWriteTxEra e -> toServerError e
ExceptionBalanceTxInternalError e -> toServerError e
ExceptionSubmitTransaction e -> toServerError e
ExceptionConstructTx e -> toServerError e
ExceptionGetPolicyId e -> toServerError e
ExceptionWitnessTx e -> toServerError e
ExceptionSubmitTx e -> toServerError e
ExceptionUpdatePassphrase e -> toServerError e
ExceptionWithRootKey e -> toServerError e
ExceptionListTransactions e -> toServerError e
ExceptionGetTransaction e -> toServerError e
ExceptionStartTimeLaterThanEndTime e -> toServerError e
ExceptionCreateMigrationPlan e -> toServerError e
ExceptionSelectAssets e -> toServerError e
ExceptionStakePoolDelegation e -> toServerError e
ExceptionFetchRewards e -> toServerError e
ExceptionWalletNotResponding e -> toServerError e
ExceptionCreateRandomAddress e -> toServerError e
ExceptionImportRandomAddress e -> toServerError e
ExceptionNotASequentialWallet e -> toServerError e
ExceptionReadRewardAccount e -> toServerError e
ExceptionWithdrawalNotBeneficial e -> toServerError e
ExceptionReadPolicyPublicKey e -> toServerError e
ExceptionWritePolicyPublicKey e -> toServerError e
ExceptionSoftDerivationIndex e -> toServerError e
ExceptionHardenedDerivationIndex e -> toServerError e
instance IsServerError ErrNoSuchWallet where
toServerError = \case
ErrNoSuchWallet wid ->
apiError err404 NoSuchWallet $ mconcat
[ "I couldn't find a wallet with the given id: "
, toText wid
]
instance IsServerError ErrWalletNotInitialized where
toServerError = \case
ErrWalletNotInitialized ->
apiError err404 NoSuchWallet $ mconcat
[ "The database for the requested wallet is not initialized. "
]
instance IsServerError ErrWalletNotResponding where
toServerError = \case
ErrWalletNotResponding wid ->
apiError err500 WalletNotResponding $ T.unwords
[ "That's embarrassing. My associated worker for", toText wid
, "is no longer responding. This is not something that is supposed"
, "to happen. The worker must have left a trace in the logs of"
, "severity 'Error' when it died which might explain the cause."
, "Said differently, this wallet won't be accessible until the"
, "server is restarted but there are good chances it'll recover"
, "itself upon restart."
]
instance IsServerError ErrWalletAlreadyExists where
toServerError = \case
ErrWalletAlreadyExists wid ->
apiError err409 WalletAlreadyExists $ mconcat
[ "This operation would yield a wallet with the following id: "
, toText wid
, " However, I already know of a wallet with this id."
]
instance IsServerError ErrWithRootKey where
toServerError = \case
ErrWithRootKeyNoRootKey wid ->
apiError err403 NoRootKey $ mconcat
[ "I couldn't find a root private key for the given wallet: "
, toText wid, ". However, this operation requires that I do "
, "have such a key. Either there's no such wallet, or I don't "
, "fully own it."
]
ErrWithRootKeyWrongPassphrase wid ErrWrongPassphrase ->
apiError err403 WrongEncryptionPassphrase $ mconcat
[ "The given encryption passphrase doesn't match the one I use "
, "to encrypt the root private key of the given wallet: "
, toText wid
]
ErrWithRootKeyWrongMnemonic wid ->
apiError err403 WrongMnemonic $ mconcat
[ "The given mnemonic doesn't match the one this wallet was created with "
, ": "
, toText wid
]
ErrWithRootKeyWrongPassphrase wid (ErrPassphraseSchemeUnsupported s) ->
apiError err501 WrongEncryptionPassphrase $ mconcat
[ "This build is not compiled with support for the "
, toText s <> " scheme used by the given wallet: "
, toText wid
]
instance IsServerError ErrSignPayment where
toServerError = \case
ErrSignPaymentMkTx e -> toServerError e
ErrSignPaymentWithRootKey e@ErrWithRootKeyNoRootKey{} -> (toServerError e)
{ errHTTPCode = 403
, errReasonPhrase = errReasonPhrase err403
}
ErrSignPaymentWithRootKey e@ErrWithRootKeyWrongPassphrase{} -> toServerError e
ErrSignPaymentWithRootKey e@ErrWithRootKeyWrongMnemonic{} -> toServerError e
ErrSignPaymentIncorrectTTL e -> toServerError e
instance IsServerError ErrWitnessTx where
toServerError = \case
ErrWitnessTxSignTx e -> toServerError e
ErrWitnessTxWithRootKey e@ErrWithRootKeyNoRootKey{} -> (toServerError e)
{ errHTTPCode = 403
, errReasonPhrase = errReasonPhrase err403
}
ErrWitnessTxWithRootKey e@ErrWithRootKeyWrongPassphrase{} -> toServerError e
ErrWitnessTxWithRootKey e@ErrWithRootKeyWrongMnemonic{} -> toServerError e
ErrWitnessTxIncorrectTTL e -> toServerError e
instance IsServerError ErrSignTx where
toServerError = \case
ErrSignTxAddressUnknown txin ->
apiError err500 KeyNotFoundForAddress $ mconcat
[ "I couldn't sign the given transaction because I "
, "could not resolve the address of a transaction input "
, "that I should be tracking: ", showT txin, "."
]
ErrSignTxUnimplemented ->
apiError err501 NotImplemented
"This feature is not yet implemented."
instance IsServerError ErrMkTransaction where
toServerError = \case
ErrMkTransactionTxBodyError hint ->
apiError err500 CreatedInvalidTransaction hint
ErrMkTransactionTokenQuantityExceedsLimit e ->
apiError err403 OutputTokenQuantityExceedsLimit $ mconcat
[ "One of the token quantities you've specified is greater "
, "than the maximum quantity allowed in a single transaction "
, "output. "
, "Try splitting this quantity across two or more outputs. "
, "Destination address: "
, pretty (view #address e)
, ". Token policy identifier: "
, pretty (view #tokenPolicyId $ asset e)
, ". Asset name: "
, pretty (view #tokenName $ asset e)
, ". Token quantity specified: "
, pretty (view #quantity e)
, ". Maximum allowable token quantity: "
, pretty (view #quantityMaxBound e)
, "."
]
ErrMkTransactionInvalidEra _era ->
apiError err500 CreatedInvalidTransaction $ mconcat
[ "Whoops, it seems like I just experienced a hard-fork in the "
, "middle of other tasks. This is a pretty rare situation but "
, "as a result, I must throw away what I was doing. Please "
, "retry your request."
]
ErrMkTransactionJoinStakePool e -> toServerError e
ErrMkTransactionQuitStakePool e -> toServerError e
ErrMkTransactionIncorrectTTL e -> toServerError e
instance IsServerError ErrConstructTx where
toServerError = \case
ErrConstructTxWrongPayload ->
apiError err403 CreatedInvalidTransaction $ mconcat
[ "It looks like I've created an empty transaction "
, "that does not have any payments, withdrawals, delegations, "
, "metadata nor minting. Include at least one of them."
]
ErrConstructTxBody e -> toServerError e
ErrConstructTxReadRewardAccount e -> toServerError e
ErrConstructTxIncorrectTTL e -> toServerError e
ErrConstructTxMultidelegationNotSupported ->
apiError err403 CreatedMultidelegationTransaction $ mconcat
[ "It looks like I've created a transaction "
, "with multiple delegations, which is not supported at this moment. "
, "Please use at most one delegation action: join, quit or none."
]
ErrConstructTxMultiaccountNotSupported ->
apiError err403 CreatedMultiaccountTransaction $ mconcat
[ "It looks like I've created a transaction "
, "with a delegation, which uses a stake key for the unsupported account. "
, "Please use delegation action engaging '0H' account."
]
ErrConstructTxWrongMintingBurningTemplate ->
apiError err403 CreatedWrongPolicyScriptTemplate $ mconcat
[ "It looks like I've created a transaction with a minting/burning "
, "policy script that either does not pass validation, contains "
, "more than one cosigner, or has a cosigner that is different "
, "from cosigner#0."
]
ErrConstructTxAssetNameTooLong ->
apiError err403 AssetNameTooLong $ mconcat
[ "Attempted to create a transaction with an asset name that is "
, "too long. The maximum length is 32 bytes."
]
ErrConstructTxMintOrBurnAssetQuantityOutOfBounds ->
apiError err403 MintOrBurnAssetQuantityOutOfBounds $ mconcat
[ "Attempted to mint or burn an asset quantity that is out of "
, "bounds. The asset quantity must be greater than zero and must "
, "not exceed 9223372036854775807 (2^63 - 1)."
]
ErrConstructTxWrongValidityBounds ->
apiError err403 InvalidValidityBounds $ T.unwords
[ "Attempted to create a transaction with invalid validity bounds."
, "Please make sure that the 'invalid_before' bound precedes the"
, "'invalid_hereafter' bound, and that you have not used negative"
, "time values."
]
ErrConstructTxValidityIntervalNotWithinScriptTimelock ->
apiError err403 ValidityIntervalNotInsideScriptTimelock $ T.unwords
[ "Attempted to create a transaction with a validity interval"
, "that is not a subinterval of an associated script's timelock"
, "interval."
]
ErrConstructTxSharedWalletIncomplete ->
apiError err403 SharedWalletIncomplete $ T.unwords
[ "I cannot construct a transaction for a shared wallet that is"
, "in the 'incomplete' state. Please update your wallet accordingly"
, "with"
, "'PATCH /shared-wallets/{walletId}/payment-script-template'"
, "or"
, "'PATCH /shared-wallets/{walletId}/delegation-script-template'"
, "to make it suitable for constructing transactions."
]
ErrConstructTxDelegationInvalid ->
apiError err403 DelegationInvalid $ T.unwords
[ "I cannot construct a delegating transaction for a shared wallet "
, "that is lacking a delegation script template."
]
instance IsServerError ErrGetPolicyId where
toServerError = \case
ErrGetPolicyIdReadPolicyPubliKey e -> toServerError e
ErrGetPolicyIdWrongMintingBurningTemplate ->
apiError err403 CreatedWrongPolicyScriptTemplate $ mconcat
[ "It looks like policy id is requested for a "
, "policy script that either does not pass validation, contains "
, "more than one cosigner, or has a cosigner that is different "
, "from cosigner#0."
]
instance IsServerError ErrWriteTxEra where
toServerError = \case
ErrNodeNotYetInRecentEra (Cardano.AnyCardanoEra era) ->
apiError err403 (NodeNotYetInRecentEra info) $ T.unwords
[ "This operation requires the node to be synchronised to a"
, "recent era, but the node is currently only synchronised to the"
, showT era
, "era. Please wait until the node is fully synchronised and"
, "try again."
]
where
info = ApiErrorNodeNotYetInRecentEra
{ nodeEra = toApiEra $ Cardano.AnyCardanoEra era
, supportedRecentEras =
map (toApiEra . Write.toAnyCardanoEra) [minBound .. maxBound]
}
instance IsServerError ErrBalanceTx where
toServerError = \case
ErrBalanceTxUpdateError (ErrExistingKeyWitnesses n) ->
apiError err403 BalanceTxExistingKeyWitnesses $ mconcat
[ "The transaction could not be balanced, because it contains "
, T.pack (show n), " "
, "existing key-witnesses which would be invalid after "
, "the transaction body is modified. "
, "Please sign the transaction after it is balanced instead."
]
ErrBalanceTxSelectAssets err -> toServerError err
ErrBalanceTxAssignRedeemers err -> toServerError err
ErrBalanceTxConflictingNetworks ->
apiError err403 BalanceTxConflictingNetworks $ T.unwords
[ "There are withdrawals for multiple networks (e.g. both"
, "mainnet and testnet) in the provided transaction. This"
, "makes no sense, and I'm confused."
]
ErrBalanceTxExistingCollateral ->
apiError err403 BalanceTxExistingCollateral
"I cannot balance transactions with pre-defined collateral."
ErrBalanceTxExistingTotalCollateral ->
apiError err403 BalanceTxExistingTotalCollateral $ T.unwords
[ "I cannot balance transactions"
, "with pre-defined total collateral."
]
ErrBalanceTxExistingReturnCollateral ->
apiError err403 BalanceTxExistingReturnCollateral $ T.unwords
[ "Balancing transactions with pre-defined"
, "collateral return outputs is not yet supported."
]
ErrBalanceTxInternalError e -> toServerError e
ErrBalanceTxMaxSizeLimitExceeded ->
apiError err403 TransactionIsTooBig $ T.unwords
[ "I was not able to balance the transaction without exceeding"
, "the maximum transaction size."
]
ErrBalanceTxUnresolvedInputs ins ->
apiError err400 UnresolvedInputs $ T.unwords
[ "There are inputs in the transaction for which corresponding"
, "outputs could not be found:\n"
, pretty $ NE.toList ins
]
ErrBalanceTxInputResolutionConflicts conflicts -> do
let conflictF (a, b) = build a <> "\nvs\n" <> build b
apiError err400 InputResolutionConflicts $ mconcat
[ "At least one of the inputs you've told me about has an"
, "asset quantity or address that is different from that"
, "recorded in the wallet's UTxO set."
, "\n"
, "The conflict(s) are:\n"
, fmt $ blockListF' "-" conflictF conflicts
]
instance IsServerError ErrBalanceTxInternalError where
toServerError = \case
ErrUnderestimatedFee coin candidateTx (KeyWitnessCount nWits nBootWits) ->
apiError err500 (BalanceTxUnderestimatedFee info) $ T.unwords
[ "I have somehow underestimated the fee of the transaction by"
, pretty coin, "and cannot finish balancing."
]
where
info = ApiErrorBalanceTxUnderestimatedFee
{ underestimation = Quantity $ Coin.toNatural coin
, candidateTxHex = hexText $ serialisedTx candidateTx
, candidateTxReadable = T.pack (show candidateTx)
, estimatedNumberOfKeyWits = intCast nWits
, estimatedNumberOfBootstrapKeyWits = intCast nBootWits
}
ErrFailedBalancing v ->
apiError err500 BalanceTxInternalError $ T.unwords
[ "I have somehow failed to balance the transaction."
, "The balance is"
, T.pack (show v)
]
instance IsServerError ErrRemoveTx where
toServerError = \case
ErrRemoveTxNoSuchTransaction (ErrNoSuchTransaction tid) ->
apiError err404 NoSuchTransaction $ mconcat
[ "I couldn't find a transaction with the given id: "
, toText tid
]
ErrRemoveTxAlreadyInLedger tid ->
apiError err403 TransactionAlreadyInLedger $ mconcat
[ "The transaction with id: ", toText tid,
" cannot be forgotten as it is already in the ledger."
]
instance IsServerError ErrPostTx where
toServerError = \case
ErrPostTxValidationError err ->
apiError err500 CreatedInvalidTransaction $ mconcat
[ "The submitted transaction was rejected by the local "
, "node. Here's an error message that may help with "
, "debugging:\n", err
]
ErrPostTxMempoolFull ->
apiError err425
{errBody = "Mempool is full, please try resubmitting again later."}
MempoolIsFull $ mconcat
[ "The submitted transaction was rejected by the Cardano node "
, "because its mempool was full."
]
instance IsServerError ErrSubmitTransaction where
toServerError = \case
ErrSubmitTransactionForeignWallet ->
apiError err403 ForeignTransaction $ mconcat
[ "The transaction to be submitted is foreign to the current wallet "
, "and cannot be sent. Submit a transaction that has either input "
, "or withdrawal belonging to the wallet."
]
ErrSubmitTransactionPartiallySignedOrNoSignedTx expectedWitsNo foundWitsNo ->
apiError err403 MissingWitnessesInTransaction $ mconcat
[ "The transaction expects ", toText expectedWitsNo
, " witness(es) to be fully-signed but ", toText foundWitsNo, " was provided."
, " Submit fully-signed transaction."
]
ErrSubmitTransactionMultidelegationNotSupported ->
apiError err403 CreatedMultidelegationTransaction $ mconcat
[ "It looks like the transaction to be sent contains"
, "multiple delegations, which is not supported at this moment."
, "Please use at most one delegation action in a submitted transaction: join, quit or none."
]
instance IsServerError ErrSubmitTx where
toServerError = \case
ErrSubmitTxNetwork e -> toServerError e
ErrSubmitTxImpossible e -> toServerError e
instance IsServerError ErrUpdatePassphrase where
toServerError = \case
ErrUpdatePassphraseWithRootKey e -> toServerError e
instance IsServerError ErrListTransactions where
toServerError = \case
ErrListTransactionsStartTimeLaterThanEndTime e -> toServerError e
ErrListTransactionsMinWithdrawalWrong ->
apiError err400 MinWithdrawalWrong
"The minimum withdrawal value must be at least 1 Lovelace."
ErrListTransactionsPastHorizonException e -> toServerError e
instance IsServerError ErrStartTimeLaterThanEndTime where
toServerError err = apiError err400 StartTimeLaterThanEndTime $ mconcat
[ "The specified start time '"
, toText $ Iso8601Time $ errStartTime err
, "' is later than the specified end time '"
, toText $ Iso8601Time $ errEndTime err
, "'."
]
instance IsServerError PastHorizonException where
toServerError _ = apiError err503 PastHorizon $ mconcat
[ "Tried to convert something that is past the horizon"
, " (due to uncertainty about the next hard fork)."
, " Wait for the node to finish syncing to the hard fork."
, " Depending on the blockchain, this process can take an"
, " unknown amount of time."
]
instance IsServerError ErrGetTransaction where
toServerError = \case
ErrGetTransactionNoSuchTransaction e -> toServerError e
instance IsServerError ErrNoSuchTransaction where
toServerError = \case
ErrNoSuchTransaction tid ->
apiError err404 NoSuchTransaction $ mconcat
[ "I couldn't find a transaction with the given id: "
, toText tid
]
instance IsServerError ErrStakePoolDelegation where
toServerError = \case
ErrStakePoolJoin e -> toServerError e
ErrStakePoolQuit e -> toServerError e
instance IsServerError ErrCannotJoin where
toServerError = \case
ErrAlreadyDelegating pid ->
apiError err403 PoolAlreadyJoined $ mconcat
[ "I couldn't join a stake pool with the given id: "
, toText pid
, ". I have already joined this pool;"
, " joining again would incur an unnecessary fee!"
]
ErrNoSuchPool pid ->
apiError err404 NoSuchPool $ mconcat
[ "I couldn't find any stake pool with the given id: "
, toText pid
]
instance IsServerError ErrCannotQuit where
toServerError = \case
ErrNotDelegatingOrAboutTo ->
apiError err403 NotDelegatingTo $ mconcat
[ "It seems that you're trying to retire from delegation "
, "although you're not even delegating, nor won't be in an "
, "immediate future."
]
ErrNonNullRewards rewards ->
apiError err403 NonNullRewards $ mconcat
[ "It seems that you're trying to retire from delegation "
, "although you've unspoiled rewards in your rewards "
, "account! Make sure to withdraw your ", pretty rewards
, " lovelace first."
]
instance IsServerError ErrFetchRewards where
toServerError = \case
ErrFetchRewardsReadRewardAccount e -> toServerError e
ErrFetchRewardsMissingRewardAccount ->
apiError err500 MissingRewardAccount $ mconcat
[ "I couldn't read a reward account which is required for reward "
, "detection. Either there is db malfunction or managing rewards "
, "was used for shared wallets missing delegation template."
]
instance IsServerError ErrReadRewardAccount where
toServerError = \case
ErrReadRewardAccountNotAShelleyWallet ->
apiError err403 InvalidWalletType $ mconcat
[ "It is regrettable but you've just attempted an operation "
, "that is invalid for this type of wallet. Only new 'Shelley' "
, "wallets can do something with rewards and this one isn't."
]
instance IsServerError ErrReadPolicyPublicKey where
toServerError = \case
ErrReadPolicyPublicKeyNotAShelleyWallet ->
apiError err403 InvalidWalletType $ mconcat
[ "You have attempted an operation that is invalid for this "
, "type of wallet. Only wallets from the Shelley era onwards "
, "can have rewards, but this wallet is from an era before "
, "Shelley."
]
ErrReadPolicyPublicKeyAbsent ->
apiError err403 MissingPolicyPublicKey $ T.unwords
[ "It seems the wallet lacks a policy public key. Therefore"
, "it's not possible to create a minting/burning"
, "transaction or get a policy id. Please first POST to endpoint"
, "/wallets/{walletId}/policy-key to set a policy key."
]
instance IsServerError ErrWritePolicyPublicKey where
toServerError = \case
ErrWritePolicyPublicKeyWithRootKey e -> toServerError e
instance IsServerError ErrCreateRandomAddress where
toServerError = \case
ErrCreateAddrWithRootKey e -> toServerError e
ErrIndexAlreadyExists ix ->
apiError err409 AddressAlreadyExists $ mconcat
[ "I cannot derive a new unused address #", pretty (fromEnum ix)
, " because I already know of such address."
]
ErrCreateAddressNotAByronWallet ->
apiError err403 InvalidWalletType $ mconcat
[ "I cannot derive new address for this wallet type."
, " Make sure to use Byron random wallet id."
]
instance IsServerError ErrImportRandomAddress where
toServerError = \case
ErrImportAddressNotAByronWallet ->
apiError err403 InvalidWalletType $ mconcat
[ "I cannot derive new address for this wallet type."
, " Make sure to use Byron random wallet id."
]
ErrImportAddr ErrAddrDoesNotBelong{} ->
apiError err403 KeyNotFoundForAddress $ mconcat
[ "I couldn't identify this address as one of mine. It likely "
, "belongs to another wallet and I will therefore not import it."
]
instance IsServerError ErrNotASequentialWallet where
toServerError = \case
ErrNotASequentialWallet ->
apiError err403 InvalidWalletType $ mconcat
[ "I cannot derive new address for this wallet type. "
, "Make sure to use a sequential wallet style, like Icarus."
]
instance IsServerError ErrWithdrawalNotBeneficial where
toServerError = \case
ErrWithdrawalNotBeneficial ->
apiError err403 WithdrawalNotBeneficial $ mconcat
[ "I've noticed that you're requesting a withdrawal from an "
, "account that is either empty or doesn't have a balance big "
, "enough to deserve being withdrawn. I won't proceed with that "
, "request."
]
instance IsServerError ErrSignMetadataWith where
toServerError = \case
ErrSignMetadataWithRootKey e -> toServerError e
ErrSignMetadataWithInvalidIndex e -> toServerError e
instance IsServerError ErrReadAccountPublicKey where
toServerError = \case
ErrReadAccountPublicKeyRootKey e -> toServerError e
ErrReadAccountPublicKeyInvalidAccountIndex e -> toServerError e
ErrReadAccountPublicKeyInvalidPurposeIndex e -> toServerError e
instance IsServerError ErrDerivePublicKey where
toServerError = \case
ErrDerivePublicKeyInvalidIndex e -> toServerError e
instance IsServerError ErrAddCosignerKey where
toServerError = \case
ErrAddCosignerKeyWalletMetadataNotFound ->
apiError err503 WalletMetadataNotFound $ T.unwords
[ "It was not possible to find any metadata for the given"
, "wallet within the database. This could be because the"
, "wallet has yet to become active after being in the"
, "incomplete state."
]
ErrAddCosignerKey WalletAlreadyActive ->
apiError err403 SharedWalletActive $ T.unwords
[ "It looks like you've tried to add a cosigner key for a"
, "shared wallet that is active. This can be done only for"
, "an incomplete shared wallet."
]
ErrAddCosignerKey NoDelegationTemplate ->
apiError err403 SharedWalletNoDelegationTemplate $ T.unwords
[ "It looks like you've tried to add a cosigner key to"
, "a shared wallet's delegation template. This cannot be done"
, "for a wallet that does not define any delegation template."
]
ErrAddCosignerKey (KeyAlreadyPresent cred) ->
apiError err403 SharedWalletKeyAlreadyExists $ T.unwords
[ "It looks like you've tried to add a cosigner key to a"
, "shared wallet's", toText cred, "template that is already"
, "ascribed to another cosigner. Please make sure to assign a"
, "different key to each cosigner."
]
ErrAddCosignerKey (NoSuchCosigner credType (Cosigner cosignerIndex)) ->
let errorInfo = SharedWalletNoSuchCosigner
ApiErrorSharedWalletNoSuchCosigner
{ cosignerIndex =
ApiCosignerIndex cosignerIndex
, credentialType =
ApiCredentialType credType
}
errorMessage = T.unwords
[ "It looks like you've tried to add a cosigner key to a"
, "shared wallet's"
, toText credType
, "template for a non-existing cosigner index:"
, pretty cosignerIndex
]
in
apiError err403 errorInfo errorMessage
ErrAddCosignerKey CannotUpdateSharedWalletKey ->
apiError err403 SharedWalletCannotUpdateKey $ T.unwords
[ "It looks like you've tried to update the key of a cosigner"
, "having a shared wallet's account key. Only other cosigner"
, "key(s) can be updated."
]
instance IsServerError ErrConstructSharedWallet where
toServerError = \case
ErrConstructSharedWalletWrongScriptTemplate (ErrScriptTemplateInvalid cred reason) ->
handleTemplateErr cred (toText reason)
ErrConstructSharedWalletWrongScriptTemplate (ErrScriptTemplateMissingKey cred reason) ->
handleTemplateErr cred reason
ErrConstructSharedWalletInvalidIndex e -> toServerError e
where
handleTemplateErr cred reason =
apiError err403 SharedWalletScriptTemplateInvalid $ mconcat
[ "It looks like you've tried to create a shared wallet "
, "with a template script for ", toText cred, " credential that does not "
, "pass validation. The problem is: ", reason
]
instance IsServerError (ErrInvalidDerivationIndex 'Soft level) where
toServerError = \case
ErrIndexOutOfBound minIx maxIx _ix ->
apiError err403 SoftDerivationRequired $ mconcat
[ "It looks like you've provided a derivation index that is "
, "out of bound. The index is well-formed, but I require "
, "indexes valid for soft derivation only. That is, indexes "
, "between ", pretty minIx, " and ", pretty maxIx, " without a suffix."
]
instance IsServerError (SelectionOutputError WalletSelectionContext) where
toServerError (SelectionOutputError index info) = case info of
SelectionOutputCoinInsufficient e ->
flip (apiError err403) selectionOutputCoinInsufficientMessage $
UtxoTooSmall ApiErrorTxOutputLovelaceInsufficient
{ txOutputIndex =
flip fromJustNote (intCastMaybe @Int @Word32 index) $
unwords
[ "SelectionOutputError: index out of bounds:"
, show index
]
, txOutputLovelaceSpecified =
Coin.toQuantity $ TokenBundle.getCoin $ snd $ view #output e
, txOutputLovelaceRequiredMinimum =
Coin.toQuantity $ view #minimumExpectedCoin e
}
SelectionOutputSizeExceedsLimit e ->
toServerError e
SelectionOutputTokenQuantityExceedsLimit e ->
toServerError e
where
selectionOutputCoinInsufficientMessage = T.unwords
[ "One of the outputs you've specified has an ada quantity that is"
, "below the minimum required. Either increase the ada quantity to"
, "at least the minimum, or specify an ada quantity of zero, in"
, "which case the wallet will automatically assign the correct"
, "minimum ada quantity to the output."
]
instance IsServerError
(SelectionOutputSizeExceedsLimitError WalletSelectionContext)
where
toServerError e = apiError err403 OutputTokenBundleSizeExceedsLimit $
mconcat
[ "One of the outputs you've specified contains too many assets. "
, "Try splitting these assets across two or more outputs. "
, "Destination address: "
, pretty (fst output)
, ". Asset count: "
, pretty (TokenMap.size $ snd output ^. #tokens)
, "."
]
where
output = view #outputThatExceedsLimit e
instance IsServerError
(SelectionOutputTokenQuantityExceedsLimitError WalletSelectionContext)
where
toServerError e = apiError err403 OutputTokenQuantityExceedsLimit $ mconcat
[ "One of the token quantities you've specified is greater than the "
, "maximum quantity allowed in a single transaction output. Try "
, "splitting this quantity across two or more outputs. "
, "Destination address: "
, pretty (view #address e)
, ". Token policy identifier: "
, pretty (view #tokenPolicyId $ asset e)
, ". Asset name: "
, pretty (view #tokenName $ asset e)
, ". Token quantity specified: "
, pretty (view #quantity e)
, ". Maximum allowable token quantity: "
, pretty (view #quantityMaxBound e)
, "."
]
instance IsServerError ErrCreateMigrationPlan where
toServerError = \case
ErrCreateMigrationPlanEmpty ->
apiError err403 NothingToMigrate $ mconcat
[ "I wasn't able to construct a migration plan. This could be "
, "because your wallet is empty, or it could be because the "
, "amount of ada in your wallet is insufficient to pay for "
, "any of the funds to be migrated. Try adding some ada to "
, "your wallet before trying again."
]
instance IsServerError ErrSelectAssets where
toServerError = \case
ErrSelectAssetsPrepareOutputsError e -> toServerError e
ErrSelectAssetsAlreadyWithdrawing tx ->
apiError err403 AlreadyWithdrawing $ mconcat
[ "I already know of a pending transaction with withdrawals: "
, toText (tx ^. #txId)
, ". Note that when I withdraw rewards, I "
, "need to withdraw them fully for the Ledger to accept it. "
, "There's therefore no point creating another conflicting "
, "transaction; if, for some reason, you really want a new "
, "transaction, then cancel the previous one first."
]
ErrSelectAssetsSelectionError (SelectionBalanceErrorOf e) ->
toServerError e
ErrSelectAssetsSelectionError (SelectionCollateralErrorOf e) ->
toServerError e
ErrSelectAssetsSelectionError (SelectionOutputErrorOf e) ->
toServerError e
instance IsServerError (SelectionBalanceError WalletSelectionContext) where
toServerError = \case
BalanceInsufficient e ->
apiError err403 NotEnoughMoney $ mconcat
[ "I can't process this payment as there are not "
, "enough funds available in the wallet. I am "
, "missing: ", pretty . Flat $ e ^. #utxoBalanceShortfall
]
UnableToConstructChange e ->
apiError err403 CannotCoverFee $ T.unwords
[ "I am unable to finalize the transaction, as there"
, "is not enough ada available to pay for the fee and"
, "also pay for the minimum ada quantities of all"
, "change outputs. I need approximately"
, pretty (shortfall e)
, "ada to proceed. Try increasing your wallet balance"
, "or sending a smaller amount."
]
EmptyUTxO ->
apiError err403 NotEnoughMoney $ T.unwords
[ "Cannot create a transaction because the wallet"
, "has no UTxO entries. At least one UTxO entry is"
, "required in order to create a transaction."
]
instance IsServerError (SelectionCollateralError WalletSelectionContext) where
toServerError e =
apiError err403 InsufficientCollateral $ T.unwords
[ "I'm unable to create this transaction because the balance"
, "of pure ada UTxOs in your wallet is insufficient to cover"
, "the minimum amount of collateral required."
, "I need an ada amount of at least:"
, pretty (view #minimumSelectionAmount e)
, "The largest combination of pure ada UTxOs I could find is:"
, pretty $ listF $ L.sort $ F.toList $
view #largestCombinationAvailable e