package tezos-client-017-PtNairob

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file client_proto_args.ml

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
(*****************************************************************************)
(*                                                                           *)
(* Open Source License                                                       *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com>     *)
(* Copyright (c) 2019 Nomadic Labs <contact@nomadic-labs.com>                *)
(*                                                                           *)
(* Permission is hereby granted, free of charge, to any person obtaining a   *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense,  *)
(* and/or sell copies of the Software, and to permit persons to whom the     *)
(* Software is furnished to do so, subject to the following conditions:      *)
(*                                                                           *)
(* The above copyright notice and this permission notice shall be included   *)
(* in all copies or substantial portions of the Software.                    *)
(*                                                                           *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL   *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING   *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER       *)
(* DEALINGS IN THE SOFTWARE.                                                 *)
(*                                                                           *)
(*****************************************************************************)

open Protocol_client_context
open Protocol
open Alpha_context

type error += Bad_tez_arg of string * string (* Arg_name * value *)

type error += Bad_max_priority of string

type error += Bad_minimal_fees of string

type error += Bad_max_waiting_time of string

type error += Bad_endorsement_delay of string

type error += Bad_preserved_levels of string

type error += Forbidden_Negative_int of string

let () =
  register_error_kind
    `Permanent
    ~id:"badTezArg"
    ~title:"Bad Tez Arg"
    ~description:"Invalid \xEA\x9C\xA9 notation in parameter."
    ~pp:(fun ppf (arg_name, literal) ->
      Format.fprintf
        ppf
        "Invalid \xEA\x9C\xA9 notation in parameter %s: '%s'"
        arg_name
        literal)
    Data_encoding.(obj2 (req "parameter" string) (req "literal" string))
    (function
      | Bad_tez_arg (parameter, literal) -> Some (parameter, literal)
      | _ -> None)
    (fun (parameter, literal) -> Bad_tez_arg (parameter, literal)) ;
  register_error_kind
    `Permanent
    ~id:"badMaxPriorityArg"
    ~title:"Bad -max-priority arg"
    ~description:"invalid priority in -max-priority"
    ~pp:(fun ppf literal ->
      Format.fprintf ppf "invalid priority '%s' in -max-priority" literal)
    Data_encoding.(obj1 (req "parameter" string))
    (function Bad_max_priority parameter -> Some parameter | _ -> None)
    (fun parameter -> Bad_max_priority parameter) ;
  register_error_kind
    `Permanent
    ~id:"badMinimalFeesArg"
    ~title:"Bad -minimal-fees arg"
    ~description:"invalid fee threshold in -fee-threshold"
    ~pp:(fun ppf literal ->
      Format.fprintf ppf "invalid minimal fees '%s'" literal)
    Data_encoding.(obj1 (req "parameter" string))
    (function Bad_minimal_fees parameter -> Some parameter | _ -> None)
    (fun parameter -> Bad_minimal_fees parameter) ;
  register_error_kind
    `Permanent
    ~id:"badMaxWaitingTimeArg"
    ~title:"Bad -max-waiting-time arg"
    ~description:"invalid duration in -max-waiting-time"
    ~pp:(fun ppf literal ->
      Format.fprintf
        ppf
        "Bad argument value for -max-waiting-time. Expected an integer, but \
         given '%s'"
        literal)
    Data_encoding.(obj1 (req "parameter" string))
    (function Bad_max_waiting_time parameter -> Some parameter | _ -> None)
    (fun parameter -> Bad_max_waiting_time parameter) ;
  register_error_kind
    `Permanent
    ~id:"badEndorsementDelayArg"
    ~title:"Bad -endorsement-delay arg"
    ~description:"invalid duration in -endorsement-delay"
    ~pp:(fun ppf literal ->
      Format.fprintf
        ppf
        "Bad argument value for -endorsement-delay. Expected an integer, but \
         given '%s'"
        literal)
    Data_encoding.(obj1 (req "parameter" string))
    (function Bad_endorsement_delay parameter -> Some parameter | _ -> None)
    (fun parameter -> Bad_endorsement_delay parameter) ;
  register_error_kind
    `Permanent
    ~id:"badPreservedLevelsArg"
    ~title:"Bad -preserved-levels arg"
    ~description:"invalid number of levels in -preserved-levels"
    ~pp:(fun ppf literal ->
      Format.fprintf
        ppf
        "Bad argument value for -preserved_levels. Expected a positive \
         integer, but given '%s'"
        literal)
    Data_encoding.(obj1 (req "parameter" string))
    (function Bad_preserved_levels parameter -> Some parameter | _ -> None)
    (fun parameter -> Bad_preserved_levels parameter) ;
  register_error_kind
    `Permanent
    ~id:"ForbiddenNegativeInt"
    ~title:"Forbidden negative int"
    ~description:"invalid number, must a non negative natural "
    Data_encoding.(obj1 (req "invalid_natural" string))
    ~pp:(fun ppf literal ->
      Format.fprintf
        ppf
        "Bad argument value for natural. Expected a non negative integer, but \
         given '%s'"
        literal)
    (function Forbidden_Negative_int str -> Some str | _ -> None)
    (fun str -> Forbidden_Negative_int str)

let string_parameter = Tezos_clic.parameter (fun _ x -> return x)

let int_parameter =
  Tezos_clic.parameter (fun (cctxt : #Client_context.full) p ->
      try return (int_of_string p) with _ -> cctxt#error "Cannot read int")

let uri_parameter = Tezos_clic.parameter (fun _ x -> return (Uri.of_string x))

let bytes_of_prefixed_string (cctxt : #Client_context.full) s =
  match
    if String.length s < 2 || s.[0] <> '0' || s.[1] <> 'x' then None
    else Hex.to_bytes (`Hex (String.sub s 2 (String.length s - 2)))
  with
  | Some s -> return s
  | None ->
      cctxt#error
        "Invalid bytes, expecting hexadecimal notation (e.g. 0x1234abcd)"

let bytes_parameter = Tezos_clic.parameter bytes_of_prefixed_string

type 'a file_or_text = File of {path : string; content : 'a} | Text of 'a

let content_of_file_or_text = function
  | File {content; _} | Text content -> content

let parse_file ~from_text ~read_file ~path =
  let open Lwt_result_syntax in
  let* content = read_file path in
  from_text content

let file_or_text ~from_text ~read_file =
  let open Lwt_result_syntax in
  Client_aliases.parse_alternatives
    [
      ( "file",
        fun path ->
          let* content = parse_file ~from_text ~read_file ~path in
          return (File {path; content}) );
      ( "text",
        fun text ->
          let* content = from_text text in
          return (Text content) );
    ]

let file_or_text_with_origin_parameter ~from_text () =
  Tezos_clic.parameter (fun (cctxt : #Client_context.full) ->
      file_or_text ~from_text:(from_text cctxt) ~read_file:cctxt#read_file)

let file_or_text_parameter ~from_text () =
  file_or_text_with_origin_parameter ~from_text ()
  |> Tezos_clic.map_parameter ~f:content_of_file_or_text

let json_with_origin_parameter =
  let from_text (cctxt : #Client_context.full) s =
    match Data_encoding.Json.from_string s with
    | Ok json -> return json
    | Error err ->
        cctxt#error "'%s' is not a valid JSON-encoded value: %s" s err
  in
  file_or_text_with_origin_parameter ~from_text ()

let json_parameter =
  Tezos_clic.map_parameter ~f:content_of_file_or_text json_with_origin_parameter

let data_parameter =
  let open Lwt_syntax in
  let from_text (_cctxt : #Client_context.full) input =
    return @@ Tezos_micheline.Micheline_parser.no_parsing_error
    @@ Michelson_v1_parser.parse_expression input
  in
  file_or_text_parameter ~from_text ()

let safe_decode_json (cctxt : #Client_context.full) ~name
    ?(pp_error = fun _json fmt exn -> Data_encoding.Json.print_error fmt exn)
    encoding json =
  let open Lwt_result_syntax in
  match Data_encoding.Json.destruct encoding json with
  | exception (Data_encoding.Json.Cannot_destruct _ as exn) ->
      cctxt#error
        "@[<v 2>could not decode %s JSON:@,%a@]"
        name
        (pp_error json)
        exn
  | exception ((Stack_overflow | Out_of_memory) as exc) -> raise exc
  | exception exc ->
      cctxt#error "could not decode json (%s)" (Printexc.to_string exc)
  | expr -> return expr

let json_encoded_with_origin_parameter ~name ?pp_error encoding =
  let open Lwt_result_syntax in
  Tezos_clic.map_es_parameter
    ~f:(fun (cctxt : #Client_context.full) json_with_origin ->
      match json_with_origin with
      | File {path; content} ->
          let+ content =
            safe_decode_json ~name ?pp_error cctxt encoding content
          in
          File {path; content}
      | Text content ->
          let+ content = safe_decode_json ~name cctxt encoding content in
          Text content)
    json_with_origin_parameter

let json_encoded_parameter ~name ?pp_error encoding =
  Tezos_clic.map_parameter
    ~f:content_of_file_or_text
    (json_encoded_with_origin_parameter ~name ?pp_error encoding)

let json_encoded_param ~name ~desc ?pp_error encoding =
  Tezos_clic.param ~name ~desc (json_encoded_parameter ~name ?pp_error encoding)

let binary_encoded_parameter ~name encoding =
  let open Lwt_result_syntax in
  let from_text (cctxt : #Client_context.full) s =
    match Data_encoding.Binary.of_bytes_opt encoding (Bytes.of_string s) with
    | None -> cctxt#error "Invalid %s parameter" name
    | Some x -> return x
  in
  file_or_text_parameter ~from_text ()

let micheline_parameter =
  Tezos_clic.parameter (fun _ source ->
      Lwt.return @@ Tezos_micheline.Micheline_parser.no_parsing_error
      @@
      let tokens, lexing_errors =
        Tezos_micheline.Micheline_parser.tokenize source
      in
      let ast, parsing_errors =
        Tezos_micheline.Micheline_parser.parse_expression tokens
      in
      ((ast, source), lexing_errors @ parsing_errors))

let entrypoint_parameter =
  Tezos_clic.parameter (fun _ str ->
      Lwt.return @@ Environment.wrap_tzresult @@ Entrypoint.of_string_lax str)

let init_arg =
  Tezos_clic.default_arg
    ~long:"init"
    ~placeholder:"data"
    ~doc:"initial value of the contract's storage"
    ~default:"Unit"
    string_parameter

let global_constant_param ~name ~desc next =
  Tezos_clic.param ~name ~desc string_parameter next

let arg_arg =
  Tezos_clic.arg
    ~long:"arg"
    ~placeholder:"data"
    ~doc:"argument passed to the contract's script, if needed"
    string_parameter

let default_arg_arg =
  Tezos_clic.arg
    ~long:"default-arg"
    ~placeholder:"data"
    ~doc:"default argument passed to each contract's script, if needed"
    string_parameter

let delegate_arg =
  Client_keys.Public_key_hash.source_arg
    ~long:"delegate"
    ~placeholder:"address"
    ~doc:"delegate of the contract\nMust be a known address."
    ()

let source_arg =
  Tezos_clic.arg
    ~long:"source"
    ~placeholder:"address"
    ~doc:"source of the deposits to be paid\nMust be a known address."
    string_parameter

let entrypoint_arg =
  Tezos_clic.arg
    ~long:"entrypoint"
    ~placeholder:"name"
    ~doc:"entrypoint of the smart contract"
    entrypoint_parameter

let default_entrypoint_arg =
  Tezos_clic.arg
    ~long:"default-entrypoint"
    ~placeholder:"name"
    ~doc:"default entrypoint of the smart contracts"
    entrypoint_parameter

let force_switch =
  Tezos_clic.switch
    ~long:"force"
    ~short:'f'
    ~doc:
      "disables the node's injection checks\n\
       Force the injection of branch-invalid operation or force  the injection \
       of block without a fitness greater than the  current head."
    ()

let no_endorse_switch =
  Tezos_clic.switch
    ~long:"no-endorse"
    ~doc:"Do not let the client automatically endorse a block that it baked."
    ()

let minimal_timestamp_switch =
  Tezos_clic.switch
    ~long:"minimal-timestamp"
    ~doc:
      "Use the minimal timestamp instead of the current date as timestamp of \
       the baked block."
    ()

let tez_format =
  "Text format: `DDDDDDD.DDDDDD`.\n\
   Tez and mutez and separated by a period sign. Trailing and pending zeroes \
   are allowed."

let tez_parameter param =
  Tezos_clic.parameter (fun _ s ->
      match Tez.of_string s with
      | Some tez -> return tez
      | None -> fail (Bad_tez_arg (param, s)))

let tez_arg ~default ~parameter ~doc =
  Tezos_clic.default_arg
    ~long:parameter
    ~placeholder:"amount"
    ~doc
    ~default
    (tez_parameter ("--" ^ parameter))

let tez_opt_arg ~parameter ~doc =
  Tezos_clic.arg
    ~long:parameter
    ~placeholder:"amount"
    ~doc
    (tez_parameter ("--" ^ parameter))

let tez_param ~name ~desc next =
  Tezos_clic.param
    ~name
    ~desc:(desc ^ " in \xEA\x9C\xA9\n" ^ tez_format)
    (tez_parameter name)
    next

let non_negative_z_parameter =
  Tezos_clic.parameter (fun (cctxt : #Client_context.full) s ->
      try
        let v = Z.of_string s in
        error_when Compare.Z.(v < Z.zero) (Forbidden_Negative_int s)
        >>?= fun () -> return v
      with _ -> cctxt#error "Invalid number, must be a non negative number.")

let non_negative_z_param ~name ~desc next =
  Tezos_clic.param ~name ~desc non_negative_z_parameter next

let counter_parameter =
  Tezos_clic.parameter (fun (cctxt : #Client_context.full) s ->
      match Manager_counter.Internal_for_injection.of_string s with
      | None -> cctxt#error "Invalid counter, must be a non-negative number."
      | Some c -> return c)

let non_negative_parameter =
  Tezos_clic.parameter (fun _ s ->
      match int_of_string_opt s with
      | Some i when i >= 0 -> return i
      | _ -> failwith "Parameter should be a non-negative integer literal")

let fee_arg =
  Tezos_clic.arg
    ~long:"fee"
    ~placeholder:"amount"
    ~doc:"fee in \xEA\x9C\xA9 to pay to the baker"
    (tez_parameter "--fee")

let default_fee_arg =
  Tezos_clic.arg
    ~long:"default-fee"
    ~placeholder:"amount"
    ~doc:"default fee in \xEA\x9C\xA9 to pay to the baker for each transaction"
    (tez_parameter "--default-fee")

let level_kind =
  Tezos_clic.parameter (fun (cctxt : #Client_context.full) s ->
      match Option.bind (Script_int.of_string s) Script_int.is_nat with
      | Some n -> return n
      | None -> cctxt#error "invalid level (must be a positive number)")

let level_arg =
  Tezos_clic.arg
    ~long:"level"
    ~placeholder:"level"
    ~doc:"Set the level to be returned by the LEVEL instruction"
    level_kind

let raw_level_parameter =
  Tezos_clic.parameter (fun (cctxt : #Client_context.full) s ->
      match Int32.of_string_opt s with
      | Some i when i >= 0l ->
          Lwt.return @@ Environment.wrap_tzresult (Raw_level.of_int32 i)
      | _ ->
          cctxt#error
            "'%s' is not a valid level (should be a non-negative int32 value)"
            s)

let timestamp_parameter =
  Tezos_clic.parameter (fun (cctxt : #Client_context.full) s ->
      match Script_timestamp.of_string s with
      | Some time -> return time
      | None ->
          cctxt#error
            "invalid timestamp, must be either a RFC 3339 string or a number \
             of seconds since epoch.")

let now_arg =
  Tezos_clic.arg
    ~long:"now"
    ~placeholder:"timestamp"
    ~doc:
      "Set the timestamp to be returned by the NOW instruction. Allowed format \
       are RFC 3339 (YYYY-MM-DDTHH:MM:SSZ) or number of seconds since epoch."
    timestamp_parameter

let gas_limit_kind =
  Tezos_clic.parameter (fun (cctxt : #Client_context.full) s ->
      try
        let v = Z.of_string s in
        return (Gas.Arith.integral_exn v)
      with _ -> cctxt#error "invalid gas limit (must be a positive number)")

let gas_limit_arg =
  Tezos_clic.arg
    ~long:"gas-limit"
    ~short:'G'
    ~placeholder:"amount"
    ~doc:
      "Set the gas limit of the transaction instead of letting the client \
       decide based on a simulation"
    gas_limit_kind

let default_gas_limit_arg =
  Tezos_clic.arg
    ~long:"default-gas-limit"
    ~short:'G'
    ~placeholder:"amount"
    ~doc:
      "Set the default gas limit for each transaction instead of letting the \
       client decide based on a simulation"
    gas_limit_kind

let run_gas_limit_arg =
  Tezos_clic.arg
    ~long:"gas"
    ~short:'G'
    ~doc:"Initial quantity of gas for typechecking and execution"
    ~placeholder:"gas"
    gas_limit_kind

let unlimited_gas_arg =
  Tezos_clic.switch
    ~long:"unlimited-gas"
    ~doc:"Allows interpretation with virtually unlimited gas"
    ()

let storage_limit_kind =
  Tezos_clic.parameter (fun (cctxt : #Client_context.full) s ->
      try
        let v = Z.of_string s in
        assert (Compare.Z.(v >= Z.zero)) ;
        return v
      with _ ->
        cctxt#error "invalid storage limit (must be a positive number of bytes)")

let storage_limit_arg =
  Tezos_clic.arg
    ~long:"storage-limit"
    ~short:'S'
    ~placeholder:"amount"
    ~doc:
      "Set the storage limit of the transaction instead of letting the client \
       decide based on a simulation"
    storage_limit_kind

let default_storage_limit_arg =
  Tezos_clic.arg
    ~long:"default-storage-limit"
    ~short:'S'
    ~placeholder:"amount"
    ~doc:
      "Set the default storage limit for each transaction instead of letting \
       the client decide based on a simulation"
    storage_limit_kind

let counter_arg =
  Tezos_clic.arg
    ~long:"counter"
    ~short:'C'
    ~placeholder:"counter"
    ~doc:"Set the counter to be used by the transaction"
    counter_parameter

let max_priority_arg =
  Tezos_clic.arg
    ~long:"max-priority"
    ~placeholder:"slot"
    ~doc:"maximum allowed baking slot"
    (Tezos_clic.parameter (fun _ s ->
         try return (int_of_string s) with _ -> fail (Bad_max_priority s)))

let default_minimal_fees =
  match Tez.of_mutez 100L with None -> assert false | Some t -> t

let default_minimal_nanotez_per_gas_unit = Q.of_int 100

let default_minimal_nanotez_per_byte = Q.of_int 1000

let minimal_fees_arg =
  Tezos_clic.default_arg
    ~long:"minimal-fees"
    ~placeholder:"amount"
    ~doc:"exclude operations with fees lower than this threshold (in tez)"
    ~default:(Tez.to_string default_minimal_fees)
    (Tezos_clic.parameter (fun _ s ->
         match Tez.of_string s with
         | Some t -> return t
         | None -> fail (Bad_minimal_fees s)))

let minimal_nanotez_per_gas_unit_arg =
  Tezos_clic.default_arg
    ~long:"minimal-nanotez-per-gas-unit"
    ~placeholder:"amount"
    ~doc:
      "exclude operations with fees per gas lower than this threshold (in \
       nanotez)"
    ~default:(Q.to_string default_minimal_nanotez_per_gas_unit)
    (Tezos_clic.parameter (fun _ s ->
         try return (Q.of_string s) with _ -> fail (Bad_minimal_fees s)))

let minimal_nanotez_per_byte_arg =
  Tezos_clic.default_arg
    ~long:"minimal-nanotez-per-byte"
    ~placeholder:"amount"
    ~default:(Q.to_string default_minimal_nanotez_per_byte)
    ~doc:
      "exclude operations with fees per byte lower than this threshold (in \
       nanotez)"
    (Tezos_clic.parameter (fun _ s ->
         try return (Q.of_string s) with _ -> fail (Bad_minimal_fees s)))

let replace_by_fees_arg =
  Tezos_clic.switch
    ~long:"replace"
    ~doc:
      "Replace an existing pending transaction from the same source, if any, \
       with another one with higher fees. There are no guarantees that the \
       first operation will not be included or that the second one will be. \
       But, only one of the operations at most will end in a block (in \
       precheck mode)."
    ()

let successor_level_arg =
  Tezos_clic.switch
    ~long:"simulate-successor-level"
    ~doc:"Make the simulate on the successor level of the current head."
    ()

let preserved_levels_arg =
  Tezos_clic.default_arg
    ~long:"preserved-levels"
    ~placeholder:"threshold"
    ~doc:"Number of effective levels kept in the accuser's memory"
    ~default:"200"
    (Tezos_clic.parameter (fun _ s ->
         try
           let preserved_cycles = int_of_string s in
           if preserved_cycles < 0 then fail (Bad_preserved_levels s)
           else return preserved_cycles
         with _ -> fail (Bad_preserved_levels s)))

let no_print_source_flag =
  Tezos_clic.switch
    ~long:"no-print-source"
    ~short:'q'
    ~doc:
      "don't print the source code\n\
       If an error is encountered, the client will print the contract's source \
       code by default.\n\
       This option disables this behaviour."
    ()

let no_confirmation =
  Tezos_clic.switch
    ~long:"no-confirmation"
    ~doc:"don't print wait for the operation to be confirmed."
    ()

let signature_parameter =
  Tezos_clic.parameter (fun (cctxt : #Client_context.full) s ->
      match Signature.of_b58check_opt s with
      | Some s -> return s
      | None -> cctxt#error "Not given a valid signature")

let unparsing_mode_parameter =
  Tezos_clic.parameter
    ~autocomplete:(fun _cctxt ->
      return ["Readable"; "Optimized"; "Optimized_legacy"])
    (fun (cctxt : #Client_context.full) s ->
      match s with
      | "Readable" -> return Script_ir_unparser.Readable
      | "Optimized" -> return Script_ir_unparser.Optimized
      | "Optimized_legacy" -> return Script_ir_unparser.Optimized_legacy
      | _ -> cctxt#error "Unknown unparsing mode %s" s)

let unparsing_mode_arg ~default =
  Tezos_clic.default_arg
    ~long:"unparsing-mode"
    ~placeholder:"mode"
    ~doc:
      "Unparsing mode to use\n\
       One of \"Readable\", \"Optimized\", or \"Optimized_legacy\".\n\
       This option affects the way the values of the following Michelson types \
       are represented:\n\
       - timestamp: the Readable representation is a RFC3339 string, the \
       Optimized and Optimized_legacy representations are the number of \
       seconds since Epoch\n\
       - key, signature, key_hash, address, contract, chain_id: the Readable \
       representation is a Base58Check string, the Optimized and \
       Optimized_legacy representations are byte sequences\n\
       - nested pairs: in Readable mode, the Pair constructor is used even \
       with arity bigger than 2 such as in Pair 0 1 2; in Optimized_legacy \
       mode, the Pair constructor is always use with arity 2 such as in Pair 0 \
       (Pair 1 2); in Optimized mode, a sequence is used if there are at least \
       4 elements and the behavior is the same as in Optimized_legacy mode \
       otherwise.\n"
    ~default
    unparsing_mode_parameter

let enforce_indentation_flag =
  Tezos_clic.switch
    ~long:"enforce-indentation"
    ~doc:
      "Check that the Micheline expression passed to this command is \
       well-indented."
    ()

let display_names_flag =
  Tezos_clic.switch
    ~long:"display-names"
    ~doc:"Print names of scripts passed to this command"
    ()

module Daemon = struct
  let baking_switch =
    Tezos_clic.switch ~long:"baking" ~short:'B' ~doc:"run the baking daemon" ()

  let endorsement_switch =
    Tezos_clic.switch
      ~long:"endorsement"
      ~short:'E'
      ~doc:"run the endorsement daemon"
      ()

  let denunciation_switch =
    Tezos_clic.switch
      ~long:"denunciation"
      ~short:'D'
      ~doc:"run the denunciation daemon"
      ()
end

module Sc_rollup_params = struct
  let convert_address sc_rollup_address =
    sc_rollup_address
    |> Data_encoding.Binary.to_bytes_exn
         Tezos_crypto.Hashed.Smart_rollup_address.encoding
    |> Data_encoding.Binary.of_bytes_exn Sc_rollup.Address.encoding

  let sc_rollup_address_parameter =
    Tezos_clic.map_parameter
      (Smart_rollup_alias.Address.parameter ())
      ~f:convert_address

  let sc_rollup_address_param ?(name = "smart rollup address")
      ?(desc = "the address of the targeted smart rollup") next =
    let desc =
      String.concat
        "\n"
        [
          desc;
          "Can be an alias or a literal (autodetected in order).\n\
           Use 'alias:name' or 'text:literal' to force.";
        ]
    in
    Tezos_clic.param ~name ~desc sc_rollup_address_parameter next

  let rollup_kind_parameter =
    Tezos_clic.parameter (fun (cctxt : #Client_context.full) name ->
        match Sc_rollup.Kind.of_string name with
        | None ->
            cctxt#error
              "Parameter '%s' is not a valid rollup name (must be one of %s)"
              name
              (String.concat ", " Sc_rollup.Kind.(List.map to_string all))
        | Some k -> return k)

  let boot_sector_parameter =
    let from_text (cctxt : #Client_context.full) s =
      return (fun (Sc_rollup.PVM.Packed (module R)) ->
          R.parse_boot_sector s |> function
          | None -> cctxt#error "Invalid kernel"
          | Some boot_sector -> return boot_sector)
    in
    file_or_text_parameter ~from_text ()

  let messages_parameter =
    let open Lwt_result_syntax in
    let from_json (cctxt : #Client_context.full) text =
      try
        match Ezjsonm.from_string text with
        | `A messages -> return (`Json (`A (`String "raw" :: messages)))
        | _ -> cctxt#error "Expecting a list of string"
      with Ezjsonm.Parse_error _ ->
        cctxt#error "Given text is not valid JSON: '%s'" text
    in
    let from_json_hex (cctxt : #Client_context.full) text =
      try
        match Ezjsonm.from_string text with
        | `A messages -> return (`Json (`A (`String "hex" :: messages)))
        | _ -> cctxt#error "Expecting a list of hex-encoded string"
      with Ezjsonm.Parse_error _ ->
        cctxt#error "Given text is not valid JSON: '%s'" text
    in
    let from_bin_file (cctxt : #Client_context.full) path =
      let* bin = cctxt#read_file path in
      return (`Bin bin)
    in
    let from_json_file (cctxt : #Client_context.full) path =
      let* json_string = cctxt#read_file path in
      from_json cctxt json_string
    in
    Tezos_clic.parameter (fun (cctxt : #Client_context.full) p ->
        Client_aliases.parse_alternatives
          [
            ("text", from_json cctxt);
            ("hex", from_json_hex cctxt);
            ("file", from_json_file cctxt);
            ("bin", from_bin_file cctxt);
          ]
          p)

  let commitment_hash_parameter =
    Tezos_clic.parameter (fun (cctxt : #Client_context.full) commitment_hash ->
        match Sc_rollup.Commitment.Hash.of_b58check_opt commitment_hash with
        | None ->
            cctxt#error
              "Parameter '%s' is not a valid B58-encoded rollup commitment hash"
              commitment_hash
        | Some hash -> return hash)

  let unchecked_payload_parameter =
    file_or_text_parameter ~from_text:(fun _cctxt -> return) ()

  let compressed_state_parameter =
    Tezos_clic.parameter (fun (cctxt : #Client_context.full) state_hash ->
        match Sc_rollup.State_hash.of_b58check_opt state_hash with
        | None ->
            cctxt#error
              "Parameter '%s' is not a valid B58-encoded compressed state"
              state_hash
        | Some hash -> return hash)

  let number_of_ticks_parameter =
    Tezos_clic.parameter (fun (cctxt : #Client_context.full) nb_of_ticks ->
        match Int64.of_string_opt nb_of_ticks with
        | Some nb_of_ticks -> (
            match Sc_rollup.Number_of_ticks.of_value nb_of_ticks with
            | None ->
                cctxt#error
                  "Parameter '%Ld' is out of bounds, it should be between %Ld \
                   and %Ld"
                  nb_of_ticks
                  Sc_rollup.Number_of_ticks.min_value
                  Sc_rollup.Number_of_ticks.max_value
            | Some nb_of_ticks -> return nb_of_ticks)
        | None ->
            cctxt#error "'%s' is not valid, should be a int64 value" nb_of_ticks)
end

module Zk_rollup_params = struct
  let address_parameter =
    let open Lwt_result_syntax in
    Tezos_clic.parameter (fun (cctxt : #Client_context.full) s ->
        match Zk_rollup.Address.of_b58check_opt s with
        | Some c -> return c
        | None -> cctxt#error "Parameter '%s' is an invalid Epoxy address" s)

  let plonk_public_parameters_parameter =
    binary_encoded_parameter
      ~name:"PlonK public"
      Plonk.Main_protocol.verifier_public_parameters_encoding

  let update_parameter =
    binary_encoded_parameter ~name:"Epoxy Update" Zk_rollup.Update.encoding

  let operations_parameter =
    binary_encoded_parameter
      ~name:"Epoxy Operations"
      Data_encoding.(
        list
        @@ tup2 Zk_rollup.Operation.encoding (option Zk_rollup.Ticket.encoding))

  let state_parameter =
    binary_encoded_parameter ~name:"Epoxy State" Zk_rollup.State.encoding

  let circuits_info_parameter =
    binary_encoded_parameter
      ~name:"Epoxy Circuits_info map"
      Zk_rollup.Account.circuits_info_encoding
end

let fee_parameter_args =
  let open Tezos_clic in
  let force_low_fee_arg =
    switch
      ~long:"force-low-fee"
      ~doc:"Don't check that the fee is lower than the estimated default value"
      ()
  in
  let fee_cap_arg =
    default_arg
      ~long:"fee-cap"
      ~placeholder:"amount"
      ~default:"1.0"
      ~doc:"Set the fee cap"
      (parameter (fun (cctxt : #Client_context.full) s ->
           match Tez.of_string s with
           | Some t -> return t
           | None -> cctxt#error "Bad fee cap"))
  in
  let burn_cap_arg =
    default_arg
      ~long:"burn-cap"
      ~placeholder:"amount"
      ~default:"0"
      ~doc:"Set the burn cap"
      (parameter (fun (cctxt : #Client_context.full) s ->
           match Tez.of_string s with
           | Some t -> return t
           | None -> cctxt#error "Bad burn cap"))
  in
  Tezos_clic.map_arg
    ~f:
      (fun _cctxt
           ( minimal_fees,
             minimal_nanotez_per_byte,
             minimal_nanotez_per_gas_unit,
             force_low_fee,
             fee_cap,
             burn_cap ) ->
      return
        {
          Injection.minimal_fees;
          minimal_nanotez_per_byte;
          minimal_nanotez_per_gas_unit;
          force_low_fee;
          fee_cap;
          burn_cap;
        })
    (Tezos_clic.aggregate
       (Tezos_clic.args6
          minimal_fees_arg
          minimal_nanotez_per_byte_arg
          minimal_nanotez_per_gas_unit_arg
          force_low_fee_arg
          fee_cap_arg
          burn_cap_arg))
OCaml

Innovation. Community. Security.