123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2018 Nomadic Development. <contact@tezcore.com> *)(* Copyright (c) 2021-2022 Nomadic Labs, <contact@nomadic-labs.com> *)(* Copyright (c) 2022 TriliTech <contact@trili.tech> *)(* *)(* 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. *)(* *)(*****************************************************************************)openProtocolopenEnvironmentopenAlpha_contextopenEnvironment.Error_monad(** The assumed number of blocks between operation-creation time and
the actual time when the operation is included in a block. *)letdefault_operation_inclusion_latency=3letparse_operation(op:Operation.raw)=matchData_encoding.Binary.of_bytes_optOperation.protocol_data_encodingop.protowith|Someprotocol_data->ok{shell=op.shell;protocol_data}|None->errorPlugin_errors.Cannot_parse_operationletpath=RPC_path.(open_root/"helpers")letelab_conf=Script_ir_translator_config.make~keep_extra_types_for_interpreter_logging:truemoduleRegistration=structletpatched_services=ref(RPC_directory.empty:Updater.rpc_contextRPC_directory.t)letregister0_fullctxt~chunkedsf=patched_services:=RPC_directory.register~chunked!patched_servicess(functxtqi->Services_registration.rpc_initctxt`Head_level>>=?functxt->fctxtqi)letregister0~chunkedsf=register0_fullctxt~chunkeds(fun{context;_}->fcontext)letregister0_fullctxt_successor_level~chunkedsf=patched_services:=RPC_directory.register~chunked!patched_servicess(functxtqi->letmode=ifq#successor_levelthen`Successor_levelelse`Head_levelinServices_registration.rpc_initctxtmode>>=?functxt->fctxtqi)letregister0_successor_level~chunkedsf=register0_fullctxt_successor_level~chunkeds(fun{context;_}->fcontext)letregister0_noctxt~chunkedsf=patched_services:=RPC_directory.register~chunked!patched_servicess(fun_qi->fqi)letopt_register0_fullctxt~chunkedsf=patched_services:=RPC_directory.opt_register~chunked!patched_servicess(functxtqi->Services_registration.rpc_initctxt`Head_level>>=?functxt->fctxtqi)letopt_register0~chunkedsf=opt_register0_fullctxt~chunkeds(fun{context;_}->fcontext)letregister1_fullctxt~chunkedsf=patched_services:=RPC_directory.register~chunked!patched_servicess(fun(ctxt,arg)qi->Services_registration.rpc_initctxt`Head_level>>=?functxt->fctxtargqi)letopt_register1_fullctxt~chunkedsf=patched_services:=RPC_directory.opt_register~chunked!patched_servicess(fun(ctxt,arg)qi->Services_registration.rpc_initctxt`Head_level>>=?functxt->fctxtargqi)letregister1~chunkedsf=register1_fullctxt~chunkeds(fun{context;_}x->fcontextx)letopt_register1~chunkedsf=opt_register1_fullctxt~chunkeds(fun{context;_}x->fcontextx)letregister2_fullctxt~chunkedsf=patched_services:=RPC_directory.register~chunked!patched_servicess(fun((ctxt,arg1),arg2)qi->Services_registration.rpc_initctxt`Head_level>>=?functxt->fctxtarg1arg2qi)letregister2~chunkedsf=register2_fullctxt~chunkeds(fun{context;_}a1a2qi->fcontexta1a2qi)letregister3_fullctxt~chunkedsf=patched_services:=RPC_directory.register~chunked!patched_servicess(fun(((ctxt,arg1),arg2),arg3)qi->Services_registration.rpc_initctxt`Head_level>>=?functxt->fctxtarg1arg2arg3qi)letregister3~chunkedsf=register3_fullctxt~chunkeds(fun{context;_}a1a2a3qi->fcontexta1a2a3qi)endletunparsing_mode_encoding=letopenScript_ir_unparserinletopenData_encodinginunion~tag_size:`Uint8[case(Tag0)~title:"Readable"(constant"Readable")(functionReadable->Some()|Optimized|Optimized_legacy->None)(fun()->Readable);case(Tag1)~title:"Optimized"(constant"Optimized")(functionOptimized->Some()|Readable|Optimized_legacy->None)(fun()->Optimized);case(Tag2)~title:"Optimized_legacy"(constant"Optimized_legacy")(functionOptimized_legacy->Some()|Readable|Optimized->None)(fun()->Optimized_legacy);]moduleScripts=structmoduleS=structopenData_encodingletpath=RPC_path.(path/"scripts")letrun_code_input_encoding=merge_objs(obj10(req"script"Script.expr_encoding)(req"storage"Script.expr_encoding)(req"input"Script.expr_encoding)(req"amount"Tez.encoding)(opt"balance"Tez.encoding)(req"chain_id"Chain_id.encoding)(opt"source"Contract.encoding)(opt"payer"Contract.implicit_encoding)(opt"self"Contract.originated_encoding)(dft"entrypoint"Entrypoint.simple_encodingEntrypoint.default))(obj4(opt"unparsing_mode"unparsing_mode_encoding)(opt"gas"Gas.Arith.z_integral_encoding)(opt"now"Script_timestamp.encoding)(opt"level"Script_int.n_encoding))letrun_code_output_encoding=conv(fun(storage,operations,lazy_storage_diff)->(storage,operations,lazy_storage_diff))(fun(storage,operations,lazy_storage_diff)->(storage,operations,lazy_storage_diff))(obj3(req"storage"Script.expr_encoding)(req"operations"(listApply_internal_results.internal_operation_encoding))(opt"lazy_storage_diff"Lazy_storage.encoding))lettrace_code_input_encoding=run_code_input_encodinglettrace_encoding:Script_typed_ir.execution_traceencoding=def"scripted.trace"@@list@@obj3(req"location"Script.location_encoding)(req"gas"Gas.Arith.z_fp_encoding)(req"stack"(listScript.expr_encoding))lettrace_code_output_encoding=conv(fun(storage,operations,trace,lazy_storage_diff)->(storage,operations,trace,lazy_storage_diff))(fun(storage,operations,trace,lazy_storage_diff)->(storage,operations,trace,lazy_storage_diff))(obj4(req"storage"Script.expr_encoding)(req"operations"(listApply_internal_results.internal_operation_encoding))(req"trace"trace_encoding)(opt"lazy_storage_diff"Lazy_storage.encoding))letrun_tzip4_view_encoding=letopenData_encodinginobj10(req"contract"Contract.originated_encoding)(req"entrypoint"Entrypoint.simple_encoding)(req"input"Script.expr_encoding)(req"chain_id"Chain_id.encoding)(opt"source"Contract.encoding)(opt"payer"Contract.implicit_encoding)(opt"gas"Gas.Arith.z_integral_encoding)(req"unparsing_mode"unparsing_mode_encoding)(opt"now"Script_timestamp.encoding)(opt"level"Script_int.n_encoding)letrun_script_view_encoding=letopenData_encodinginmerge_objs(obj10(req"contract"Contract.originated_encoding)(req"view"(stringPlain))(req"input"Script.expr_encoding)(dft"unlimited_gas"boolfalse)(req"chain_id"Chain_id.encoding)(opt"source"Contract.encoding)(opt"payer"Contract.implicit_encoding)(opt"gas"Gas.Arith.z_integral_encoding)(req"unparsing_mode"unparsing_mode_encoding)(opt"now"Script_timestamp.encoding))(obj1(opt"level"Script_int.n_encoding))letrun_code=RPC_service.post_service~description:"Run a piece of code in the current context"~query:RPC_query.empty~input:run_code_input_encoding~output:run_code_output_encodingRPC_path.(path/"run_code")lettrace_code=RPC_service.post_service~description:"Run a piece of code in the current context, keeping a trace"~query:RPC_query.empty~input:trace_code_input_encoding~output:trace_code_output_encodingRPC_path.(path/"trace_code")letrun_tzip4_view=RPC_service.post_service~description:"Simulate a call to a view following the TZIP-4 standard. See \
https://gitlab.com/tezos/tzip/-/blob/master/proposals/tzip-4/tzip-4.md#view-entrypoints."~input:run_tzip4_view_encoding~output:(obj1(req"data"Script.expr_encoding))~query:RPC_query.empty(* This path should be deprecated in the future *)RPC_path.(path/"run_view")letrun_script_view=RPC_service.post_service~description:"Simulate a call to a michelson view"~input:run_script_view_encoding~output:(obj1(req"data"Script.expr_encoding))~query:RPC_query.emptyRPC_path.(path/"run_script_view")lettypecheck_code=RPC_service.post_service~description:"Typecheck a piece of code in the current context"~query:RPC_query.empty~input:(obj4(req"program"Script.expr_encoding)(opt"gas"Gas.Arith.z_integral_encoding)(opt"legacy"bool)(opt"show_types"bool))~output:(obj2(req"type_map"Script_tc_errors_registration.type_map_enc)(req"gas"Gas.encoding))RPC_path.(path/"typecheck_code")letscript_size=RPC_service.post_service~description:"Compute the size of a script in the current context"~query:RPC_query.empty~input:(obj4(req"program"Script.expr_encoding)(req"storage"Script.expr_encoding)(opt"gas"Gas.Arith.z_integral_encoding)(opt"legacy"bool))~output:(obj1(req"script_size"int31))RPC_path.(path/"script_size")lettypecheck_data=RPC_service.post_service~description:"Check that some data expression is well formed and of a given type \
in the current context"~query:RPC_query.empty~input:(obj4(req"data"Script.expr_encoding)(req"type"Script.expr_encoding)(opt"gas"Gas.Arith.z_integral_encoding)(opt"legacy"bool))~output:(obj1(req"gas"Gas.encoding))RPC_path.(path/"typecheck_data")letpack_data=RPC_service.post_service~description:"Computes the serialized version of some data expression using the \
same algorithm as script instruction PACK"~input:(obj3(req"data"Script.expr_encoding)(req"type"Script.expr_encoding)(opt"gas"Gas.Arith.z_integral_encoding))~output:(obj2(req"packed"(bytesHex))(req"gas"Gas.encoding))~query:RPC_query.emptyRPC_path.(path/"pack_data")letnormalize_data=RPC_service.post_service~description:"Normalizes some data expression using the requested unparsing mode"~input:(obj4(req"data"Script.expr_encoding)(req"type"Script.expr_encoding)(req"unparsing_mode"unparsing_mode_encoding)(opt"legacy"bool))~output:(obj1(req"normalized"Script.expr_encoding))~query:RPC_query.emptyRPC_path.(path/"normalize_data")letnormalize_script=RPC_service.post_service~description:"Normalizes a Michelson script using the requested unparsing mode"~input:(obj2(req"script"Script.expr_encoding)(req"unparsing_mode"unparsing_mode_encoding))~output:(obj1(req"normalized"Script.expr_encoding))~query:RPC_query.emptyRPC_path.(path/"normalize_script")letnormalize_type=RPC_service.post_service~description:"Normalizes some Michelson type by expanding `pair a b c` as `pair a \
(pair b c)"~input:(obj1(req"type"Script.expr_encoding))~output:(obj1(req"normalized"Script.expr_encoding))~query:RPC_query.emptyRPC_path.(path/"normalize_type")letrun_operation=RPC_service.post_service~description:"Run an operation with the context of the given block and without \
signature checks. Return the operation application result, \
including the consumed gas. This RPC does not support consensus \
operations."~query:RPC_query.empty~input:(obj2(req"operation"Operation.encoding)(req"chain_id"Chain_id.encoding))~output:Apply_results.operation_data_and_metadata_encodingRPC_path.(path/"run_operation")letsimulate_query=letopenRPC_queryinquery(funsuccessor_level->objectmethodsuccessor_level=successor_levelend)|+flag~descr:"If true, the simulation is done on the successor level of the \
current context.""successor_level"(funt->t#successor_level)|>sealletsimulate_operation=RPC_service.post_service~description:"Simulate running an operation at some future moment (based on the \
number of blocks given in the `latency` argument), and return the \
operation application result. The result is the same as \
run_operation except for the consumed gas, which depends on the \
contents of the cache at that future moment. This RPC estimates \
future gas consumption by trying to predict the state of the cache \
using some heuristics."~query:simulate_query~input:(obj4(opt"blocks_before_activation"int32)(req"operation"Operation.encoding)(req"chain_id"Chain_id.encoding)(dft"latency"int16default_operation_inclusion_latency))~output:Apply_results.operation_data_and_metadata_encodingRPC_path.(path/"simulate_operation")letsimulate_tx_rollup_operation=RPC_service.post_service~description:"Simulate a tx rollup operation"~query:RPC_query.empty~input:(obj4(opt"blocks_before_activation"int32)(req"operation"Operation.encoding)(req"chain_id"Chain_id.encoding)(dft"latency"int16default_operation_inclusion_latency))~output:Apply_results.operation_data_and_metadata_encodingRPC_path.(path/"simulate_tx_rollup_operation")letentrypoint_type=RPC_service.post_service~description:"Return the type of the given entrypoint"~query:RPC_query.empty~input:(obj2(req"script"Script.expr_encoding)(dft"entrypoint"Entrypoint.simple_encodingEntrypoint.default))~output:(obj1(req"entrypoint_type"Script.expr_encoding))RPC_path.(path/"entrypoint")letlist_entrypoints=RPC_service.post_service~description:"Return the list of entrypoints of the given script"~query:RPC_query.empty~input:(obj1(req"script"Script.expr_encoding))~output:(obj2(dft"unreachable"(Data_encoding.list(obj1(req"path"(Data_encoding.listMichelson_v1_primitives.prim_encoding))))[])(req"entrypoints"(assocScript.expr_encoding)))RPC_path.(path/"entrypoints")endmoduletypeUNPARSING_MODE=sigvalunparsing_mode:Script_ir_unparser.unparsing_modeendmoduleTraced_interpreter(Unparsing_mode:UNPARSING_MODE)=structtypelog_element=|Log:context*Script.location*('a*'s)*('a,'s)Script_typed_ir.stack_ty->log_elementletunparse_stackctxt(stack,stack_ty)=(* We drop the gas limit as this function is only used for debugging/errors. *)letctxt=Gas.set_unlimitedctxtinletrecunparse_stack:typeas.(a,s)Script_typed_ir.stack_ty*(a*s)->Script.exprlisttzresultLwt.t=function|Bot_t,(EmptyCell,EmptyCell)->return_nil|Item_t(ty,rest_ty),(v,rest)->Script_ir_translator.unparse_datactxtUnparsing_mode.unparsing_modetyv>>=?fun(data,_ctxt)->unparse_stack(rest_ty,rest)>|=?funrest->data::restinunparse_stack(stack_ty,stack)lettrace_loggerctxt:Script_typed_ir.logger=Script_interpreter_logging.make(modulestructletlog:log_elementlistref=ref[]letlog_interp_ctxtlocstystack=log:=Log(ctxt,loc,stack,sty)::!logletlog_entry__ctxt_loc_sty_stack=()letlog_exit_ctxtlocstystack=log:=Log(ctxt,loc,stack,sty)::!logletlog_control_=()letget_log()=List.fold_left_es(fun(old_ctxt,l)(Log(ctxt,loc,stack,stack_ty))->letconsumed_gas=Gas.consumed~since:old_ctxt~until:ctxtintracePlugin_errors.Cannot_serialize_log(unparse_stackctxt(stack,stack_ty))>>=?funstack->return(ctxt,(loc,consumed_gas,stack)::l))(ctxt,[])(List.rev!log)>>=?fun(_ctxt,res)->return(Some(List.revres))end)letexecutectxtstep_constants~script~entrypoint~parameter=letlogger=trace_loggerctxtinScript_interpreter.execute~logger~cached_script:NonectxtUnparsing_mode.unparsing_modestep_constants~script~entrypoint~parameter~internal:true>>=?funres->logger.get_log()>|=?funtrace->lettrace=Option.value~default:[]tracein(res,trace)endlettypecheck_data:legacy:bool->context->Script.expr*Script.expr->contexttzresultLwt.t=fun~legacyctxt(data,exp_ty)->record_trace(Script_tc_errors.Ill_formed_type(None,exp_ty,0))(Script_ir_translator.parse_passable_tyctxt~legacy(Micheline.rootexp_ty))>>?=fun(Ex_tyexp_ty,ctxt)->trace_eval(fun()->letexp_ty=Script_ir_unparser.serialize_ty_for_errorexp_tyinScript_tc_errors.Ill_typed_data(None,data,exp_ty))(letallow_forged=true(* Safe since we ignore the value afterwards. *)inScript_ir_translator.parse_datactxt~elab_conf:(elab_conf~legacy())~allow_forgedexp_ty(Micheline.rootdata))>|=?fun(_,ctxt)->ctxtmoduleUnparse_types=struct(* Same as the unparsing functions for types in Script_ir_translator but
does not consume gas and never folds (pair a (pair b c)) *)openMichelineopenMichelson_v1_primitivesopenScript_typed_irletunparse_memo_size~locmemo_size=letz=Alpha_context.Sapling.Memo_size.unparse_to_zmemo_sizeinInt(loc,z)letrecunparse_ty:typeaacloc.loc:loc->(a,ac)ty->(loc,Script.prim)Micheline.node=fun~locty->letreturn(name,args,annot)=Prim(loc,name,args,annot)inmatchtywith|Unit_t->return(T_unit,[],[])|Int_t->return(T_int,[],[])|Nat_t->return(T_nat,[],[])|Signature_t->return(T_signature,[],[])|String_t->return(T_string,[],[])|Bytes_t->return(T_bytes,[],[])|Mutez_t->return(T_mutez,[],[])|Bool_t->return(T_bool,[],[])|Key_hash_t->return(T_key_hash,[],[])|Key_t->return(T_key,[],[])|Timestamp_t->return(T_timestamp,[],[])|Address_t->return(T_address,[],[])|Tx_rollup_l2_address_t->return(T_tx_rollup_l2_address,[],[])|Operation_t->return(T_operation,[],[])|Chain_id_t->return(T_chain_id,[],[])|Never_t->return(T_never,[],[])|Bls12_381_g1_t->return(T_bls12_381_g1,[],[])|Bls12_381_g2_t->return(T_bls12_381_g2,[],[])|Bls12_381_fr_t->return(T_bls12_381_fr,[],[])|Contract_t(ut,_meta)->lett=unparse_ty~locutinreturn(T_contract,[t],[])|Pair_t(utl,utr,_meta,_)->letannot=[]inlettl=unparse_ty~locutlinlettr=unparse_ty~locutrinreturn(T_pair,[tl;tr],annot)|Union_t(utl,utr,_meta,_)->letannot=[]inlettl=unparse_ty~locutlinlettr=unparse_ty~locutrinreturn(T_or,[tl;tr],annot)|Lambda_t(uta,utr,_meta)->letta=unparse_ty~locutainlettr=unparse_ty~locutrinreturn(T_lambda,[ta;tr],[])|Option_t(ut,_meta,_)->letannot=[]inletut=unparse_ty~locutinreturn(T_option,[ut],annot)|List_t(ut,_meta)->lett=unparse_ty~locutinreturn(T_list,[t],[])|Ticket_t(ut,_meta)->lett=unparse_ty~locutinreturn(T_ticket,[t],[])|Set_t(ut,_meta)->lett=unparse_ty~locutinreturn(T_set,[t],[])|Map_t(uta,utr,_meta)->letta=unparse_ty~locutainlettr=unparse_ty~locutrinreturn(T_map,[ta;tr],[])|Big_map_t(uta,utr,_meta)->letta=unparse_ty~locutainlettr=unparse_ty~locutrinreturn(T_big_map,[ta;tr],[])|Sapling_transaction_tmemo_size->return(T_sapling_transaction,[unparse_memo_size~locmemo_size],[])|Sapling_transaction_deprecated_tmemo_size->return(T_sapling_transaction_deprecated,[unparse_memo_size~locmemo_size],[])|Sapling_state_tmemo_size->return(T_sapling_state,[unparse_memo_size~locmemo_size],[])|Chest_t->return(T_chest,[],[])|Chest_key_t->return(T_chest_key,[],[])endletrecpp_instr_name:typeabcd.Format.formatter->(a,b,c,d)Script_typed_ir.kinstr->unit=letopenScript_typed_irinletopenFormatinfunfmt->function|IDrop_->pp_print_stringfmt"DROP"|IDup_->pp_print_stringfmt"DUP"|ISwap_->pp_print_stringfmt"SWAP"|IConst_->pp_print_stringfmt"CONST"|ICons_pair_->pp_print_stringfmt"PAIR"|ICar_->pp_print_stringfmt"CAR"|ICdr_->pp_print_stringfmt"CDR"|IUnpair_->pp_print_stringfmt"UNPAIR"|ICons_some_->pp_print_stringfmt"SOME"|ICons_none_->pp_print_stringfmt"NONE"|IIf_none_->pp_print_stringfmt"IF_NONE"|IOpt_map_->pp_print_stringfmt"MAP"|ICons_left_->pp_print_stringfmt"LEFT"|ICons_right_->pp_print_stringfmt"RIGHT"|IIf_left_->pp_print_stringfmt"IF_LEFT"|ICons_list_->pp_print_stringfmt"CONS"|INil_->pp_print_stringfmt"NIL"|IIf_cons_->pp_print_stringfmt"IF_CONS"|IList_map_->pp_print_stringfmt"MAP"|IList_iter_->pp_print_stringfmt"ITER"|IList_size_->pp_print_stringfmt"SIZE"|IEmpty_set_->pp_print_stringfmt"EMPTY_SET"|ISet_iter_->pp_print_stringfmt"ITER"|ISet_mem_->pp_print_stringfmt"MEM"|ISet_update_->pp_print_stringfmt"UPDATE"|ISet_size_->pp_print_stringfmt"SIZE"|IEmpty_map_->pp_print_stringfmt"EMPTY_MAP"|IMap_map_->pp_print_stringfmt"MAP"|IMap_iter_->pp_print_stringfmt"ITER"|IMap_mem_->pp_print_stringfmt"MEM"|IMap_get_->pp_print_stringfmt"GET"|IMap_update_->pp_print_stringfmt"UPDATE"|IMap_get_and_update_->pp_print_stringfmt"GET_AND_UPDATE"|IMap_size_->pp_print_stringfmt"SIZE"|IEmpty_big_map_->pp_print_stringfmt"EMPTY_BIG_MAP"|IBig_map_mem_->pp_print_stringfmt"MEM"|IBig_map_get_->pp_print_stringfmt"GET"|IBig_map_update_->pp_print_stringfmt"UPDATE"|IBig_map_get_and_update_->pp_print_stringfmt"GET_AND_UPDATE"|IConcat_string_->pp_print_stringfmt"CONCAT"|IConcat_string_pair_->pp_print_stringfmt"CONCAT"|ISlice_string_->pp_print_stringfmt"SLICE"|IString_size_->pp_print_stringfmt"SIZE"|IConcat_bytes_->pp_print_stringfmt"CONCAT"|IConcat_bytes_pair_->pp_print_stringfmt"CONCAT"|ISlice_bytes_->pp_print_stringfmt"SLICE"|IBytes_size_->pp_print_stringfmt"SIZE"|IBytes_nat_->pp_print_stringfmt"BYTES"|INat_bytes_->pp_print_stringfmt"NAT"|IBytes_int_->pp_print_stringfmt"BYTES"|IInt_bytes_->pp_print_stringfmt"INT"|IAdd_seconds_to_timestamp_->pp_print_stringfmt"ADD"|IAdd_timestamp_to_seconds_->pp_print_stringfmt"ADD"|ISub_timestamp_seconds_->pp_print_stringfmt"SUB"|IDiff_timestamps_->pp_print_stringfmt"DIFF"|IAdd_tez_->pp_print_stringfmt"ADD"|ISub_tez_->pp_print_stringfmt"SUB_MUTEZ"|ISub_tez_legacy_->pp_print_stringfmt"SUB"|IMul_teznat_|IMul_nattez_->pp_print_stringfmt"MUL"|IEdiv_teznat_->pp_print_stringfmt"EDIV"|IEdiv_tez_->pp_print_stringfmt"EDIV"|IOr_->pp_print_stringfmt"OR"|IAnd_->pp_print_stringfmt"AND"|IXor_->pp_print_stringfmt"XOR"|INot_->pp_print_stringfmt"NOT"|IIs_nat_->pp_print_stringfmt"ISNAT"|INeg_->pp_print_stringfmt"NEG"|IAbs_int_->pp_print_stringfmt"ABS"|IInt_nat_->pp_print_stringfmt"INT"|IAdd_int_|IAdd_nat_->pp_print_stringfmt"ADD"|ISub_int_->pp_print_stringfmt"SUB"|IMul_int_|IMul_nat_->pp_print_stringfmt"MUL"|IEdiv_int_|IEdiv_nat_->pp_print_stringfmt"EDIV"|ILsl_nat_->pp_print_stringfmt"LSL"|ILsl_bytes_->pp_print_stringfmt"LSL"|ILsr_nat_->pp_print_stringfmt"LSR"|ILsr_bytes_->pp_print_stringfmt"LSR"|IOr_nat_->pp_print_stringfmt"OR"|IOr_bytes_->pp_print_stringfmt"OR"|IAnd_nat_->pp_print_stringfmt"AND"|IAnd_int_nat_->pp_print_stringfmt"AND"|IAnd_bytes_->pp_print_stringfmt"AND"|IXor_nat_->pp_print_stringfmt"XOR"|IXor_bytes_->pp_print_stringfmt"XOR"|INot_int_->pp_print_stringfmt"NOT"|INot_bytes_->pp_print_stringfmt"NOT"|IIf_->pp_print_stringfmt"IF"|ILoop_->pp_print_stringfmt"LOOP"|ILoop_left_->pp_print_stringfmt"LOOP_LEFT"|IDip_->pp_print_stringfmt"DIP"|IExec_->pp_print_stringfmt"EXEC"|IApply_->pp_print_stringfmt"APPLY"|ILambda(_,Lam_,_)->pp_print_stringfmt"LAMBDA"|ILambda(_,LamRec_,_)->pp_print_stringfmt"LAMBDA_REC"|IFailwith_->pp_print_stringfmt"FAILWITH"|ICompare_->pp_print_stringfmt"COMPARE"|IEq_->pp_print_stringfmt"EQ"|INeq_->pp_print_stringfmt"NEQ"|ILt_->pp_print_stringfmt"LT"|IGt_->pp_print_stringfmt"GT"|ILe_->pp_print_stringfmt"LE"|IGe_->pp_print_stringfmt"GE"|IAddress_->pp_print_stringfmt"ADDRESS"|IContract_->pp_print_stringfmt"CONTACT"|IView_->pp_print_stringfmt"VIEW"|ITransfer_tokens_->pp_print_stringfmt"TRANSFER_TOKENS"|IImplicit_account_->pp_print_stringfmt"IMPLICIT_ACCOUNT"|ICreate_contract_->pp_print_stringfmt"CREATE_CONTRACT"|ISet_delegate_->pp_print_stringfmt"SET_DELEGATE"|INow_->pp_print_stringfmt"NOW"|IMin_block_time_->pp_print_stringfmt"MIN_BLOCK_TIME"|IBalance_->pp_print_stringfmt"BALANCE"|ILevel_->pp_print_stringfmt"LEVEL"|ICheck_signature_->pp_print_stringfmt"CHECK_SIGNATURE"|IHash_key_->pp_print_stringfmt"HASH_KEY"|IPack_->pp_print_stringfmt"PACK"|IBlake2b_->pp_print_stringfmt"BLAKE2B"|ISha3_->pp_print_stringfmt"SHA3"|ISha256_->pp_print_stringfmt"SHA256"|ISha512_->pp_print_stringfmt"SHA512"|IUnpack_->pp_print_stringfmt"UNPACK"|ISource_->pp_print_stringfmt"SOURCE"|ISender_->pp_print_stringfmt"SENDER"|ISelf_->pp_print_stringfmt"SELF"|ISelf_address_->pp_print_stringfmt"SELF_ADDRESS"|IAmount_->pp_print_stringfmt"AMOUNT"|ISapling_empty_state_->pp_print_stringfmt"SAPLING_EMPTY_STATE"|ISapling_verify_update_|ISapling_verify_update_deprecated_->pp_print_stringfmt"SAPLING_VERIFY_UPDATE"|IDig_->pp_print_stringfmt"DIG"|IDug_->pp_print_stringfmt"DUG"|IDipn_->pp_print_stringfmt"DIP"|IDropn_->pp_print_stringfmt"DROP"|IChainId_->pp_print_stringfmt"CHAIN_ID"|INever_->pp_print_stringfmt"NEVER"|IVoting_power_->pp_print_stringfmt"VOTING_POWER"|ITotal_voting_power_->pp_print_stringfmt"TOTAL_VOTING_POWER"|IKeccak_->pp_print_stringfmt"KECCAK"|IAdd_bls12_381_g1_|IAdd_bls12_381_g2_|IAdd_bls12_381_fr_->pp_print_stringfmt"ADD"|IMul_bls12_381_g1_|IMul_bls12_381_g2_|IMul_bls12_381_fr_|IMul_bls12_381_z_fr_|IMul_bls12_381_fr_z_->pp_print_stringfmt"MUL"|IInt_bls12_381_fr_->pp_print_stringfmt"INT"|INeg_bls12_381_g1_|INeg_bls12_381_g2_|INeg_bls12_381_fr_->pp_print_stringfmt"NEG"|IPairing_check_bls12_381_->pp_print_stringfmt"PAIRING_CHECK"|IComb_->pp_print_stringfmt"PAIR"|IUncomb_->pp_print_stringfmt"UNPAIR"|IComb_get_->pp_print_stringfmt"GET"|IComb_set_->pp_print_stringfmt"UPDATE"|IDup_n_->pp_print_stringfmt"DUP"|ITicket_->pp_print_stringfmt"TICKET"|ITicket_deprecated_->pp_print_stringfmt"TICKET_DEPRECATED"|IRead_ticket_->pp_print_stringfmt"READ_TICKET"|ISplit_ticket_->pp_print_stringfmt"SPLIT_TICKET"|IJoin_tickets_->pp_print_stringfmt"JOIN_TICKETS"|IOpen_chest_->pp_print_stringfmt"OPEN_CHEST"|IEmit_->pp_print_stringfmt"EMIT"|IHalt_->pp_print_stringfmt"[halt]"|ILog(_,_,_,_,instr)->Format.fprintffmt"log/%a"pp_instr_nameinstrtypeerror+=Run_operation_does_not_support_consensus_operationslet()=letdescription="The run_operation RPC does not support consensus operations."inregister_error_kind`Permanent~id:"run_operation_does_not_support_consensus_operations"~title:"Run operation does not support consensus operations"~description~pp:(funppf()->Format.fprintfppf"%s"description)Data_encoding.empty(function|Run_operation_does_not_support_consensus_operations->Some()|_->None)(fun()->Run_operation_does_not_support_consensus_operations)(** Validate and apply the operation but skip signature checks; do
not support consensus operations.
Return the unchanged operation protocol data, and the operation
receipt ie. metadata containing balance updates, consumed gas,
application success or failure, etc. *)letrun_operation_servicerpc_ctxt()(packed_operation,chain_id)=let{Services_registration.context;block_header;_}=rpc_ctxtin(matchpacked_operation.protocol_datawith|Operation_data{contents=Single(Preendorsement_);_}|Operation_data{contents=Single(Endorsement_);_}|Operation_data{contents=Single(Dal_attestation_);_}->errorRun_operation_does_not_support_consensus_operations|_->ok())>>?=fun()->letoph=Operation.hash_packedpacked_operationinletvalidity_state=Validate.begin_no_predecessor_infocontextchain_idinValidate.validate_operation~check_signature:falsevalidity_stateophpacked_operation>>=?fun_validate_operation_state->Raw_level.of_int32block_header.level>>?=funpredecessor_level->letapplication_mode=Apply.Partial_construction{predecessor_level;predecessor_fitness=block_header.fitness}inletapplication_state=Apply.{ctxt=context;chain_id;mode=application_mode;op_count=0;migration_balance_updates=[];liquidity_baking_toggle_ema=Liquidity_baking.Toggle_EMA.zero;implicit_operations_results=[];}inApply.apply_operationapplication_stateophpacked_operation>|=?fun(_ctxt,op_metadata)->(packed_operation.protocol_data,op_metadata)(*
The execution of an operation depends on the state of the
cache. In particular, gas consumption is usually impacted by
cache hits and misses.
Unfortunately, the state of the cache is different between the
context at operation-creation time and the context when is
included in a block.
Therefore, the simulation tries to predict the state of the
cache in a [time_in_blocks] assumed to be close to the inclusion
time of the operation.
*)letsimulate_operation_servicerpc_ctxt(_simulate_query:<successor_level:bool>)(blocks_before_activation,op,chain_id,time_in_blocks)=let{Services_registration.context;_}=rpc_ctxtinCache.Admin.future_cache_expectationcontext~time_in_blocks?blocks_before_activation>>=?funcontext->run_operation_service{rpc_ctxtwithcontext}()(op,chain_id)letdefault_from_contextctxtget=function|None->getctxt|Somex->returnx(* A convenience type for return values of [ensure_contracts_exist] below. *)typerun_code_config={balance:Tez.t;self:Contract_hash.t;payer:Tezos_crypto.Signature.public_key_hash;source:Contract.t;}(* 4_000_000 ꜩ *)letdefault_balance=Tez.of_mutez_exn4_000_000_000_000Lletregister()=letoriginate_dummy_contractctxtscriptbalance=letctxt=Origination_nonce.initctxtOperation_hash.zeroinContract.fresh_contract_from_current_noncectxt>>?=fun(ctxt,dummy_contract_hash)->letdummy_contract=Contract.Originateddummy_contract_hashinContract.raw_originatectxt~prepaid_bootstrap_storage:falsedummy_contract_hash~script:(script,None)>>=?functxt->Token.transfer~origin:Simulationctxt`Minted(`Contractdummy_contract)balance>>=?fun(ctxt,_)->return(ctxt,dummy_contract_hash)inletsource_and_payer~src_opt~pay_opt~default_src=match(src_opt,pay_opt)with|None,None->(Contract.Originateddefault_src,Tezos_crypto.Signature.Public_key_hash.zero)|Somec,None->(c,Tezos_crypto.Signature.Public_key_hash.zero)|None,Somec->(Contract.Implicitc,c)|Somesrc,Somepay->(src,pay)inletconfigure_contractsctxtscriptbalance~src_opt~pay_opt~self_opt=(matchself_optwith|None->letbalance=Option.value~default:default_balancebalanceinoriginate_dummy_contractctxtscriptbalance>>=?fun(ctxt,addr)->return(ctxt,addr,balance)|Someaddr->default_from_contextctxt(func->Contract.get_balancec@@Contract.Originatedaddr)balance>>=?funbal->return(ctxt,addr,bal))>>=?fun(ctxt,self,balance)->letsource,payer=source_and_payer~src_opt~pay_opt~default_src:selfinreturn(ctxt,{balance;self;source;payer})inletscript_entrypoint_typectxtexprentrypoint=letctxt=Gas.set_unlimitedctxtinletlegacy=falseinletopenScript_ir_translatorinparse_toplevelctxt~legacyexpr>>=?fun({arg_type;_},ctxt)->Lwt.return(parse_parameter_ty_and_entrypointsctxt~legacyarg_type>>?fun(Ex_parameter_ty_and_entrypoints{arg_type;entrypoints},_)->Gas_monad.runctxt@@Script_ir_translator.find_entrypoint~error_details:(Informative())arg_typeentrypointsentrypoint>>?fun(r,_ctxt)->r>|?fun(Ex_ty_cstr{original_type_expr;_})->Micheline.strip_locationsoriginal_type_expr)inletscript_view_typectxtcontractexprview=letctxt=Gas.set_unlimitedctxtinletlegacy=falseinletopenScript_ir_translatorinparse_toplevelctxt~legacyexpr>>=?fun({views;_},_)->Lwt.return(Script_string.of_stringview>>?funview_name->matchScript_map.getview_nameviewswith|None->error(View_helpers.View_not_found(contract,view))|SomeScript_typed_ir.{input_ty;output_ty;_}->ok(input_ty,output_ty))inRegistration.register0~chunked:trueS.run_code(functxt()((code,storage,parameter,amount,balance,chain_id,src_opt,pay_opt,self_opt,entrypoint),(unparsing_mode,gas,now,level))->letunparsing_mode=Option.value~default:Readableunparsing_modeinletstorage=Script.lazy_exprstorageinletcode=Script.lazy_exprcodeinconfigure_contractsctxt{storage;code}balance~src_opt~pay_opt~self_opt>>=?fun(ctxt,{self;source;payer;balance})->letgas=matchgaswith|Somegas->gas|None->Constants.hard_gas_limit_per_operationctxtinletctxt=Gas.set_limitctxtgasinletnow=matchnowwithNone->Script_timestamp.nowctxt|Somet->tinletlevel=matchlevelwith|None->(Level.currentctxt).level|>Raw_level.to_int32|>Script_int.of_int32|>Script_int.abs|Somez->zinletstep_constants=letopenScript_interpreterinletsource=Destination.Contractsourcein{source;payer;self;amount;balance;chain_id;now;level}inScript_interpreter.executectxtunparsing_modestep_constants~cached_script:None~script:{storage;code}~entrypoint~parameter~internal:true>|=?fun({script=_;code_size=_;Script_interpreter.storage;operations;lazy_storage_diff;ticket_diffs=_;ticket_receipt=_;},_)->(storage,Apply_internal_results.packed_internal_operationsoperations,lazy_storage_diff));Registration.register0~chunked:trueS.trace_code(functxt()((code,storage,parameter,amount,balance,chain_id,src_opt,pay_opt,self_opt,entrypoint),(unparsing_mode,gas,now,level))->letunparsing_mode=Option.value~default:Readableunparsing_modeinletstorage=Script.lazy_exprstorageinletcode=Script.lazy_exprcodeinconfigure_contractsctxt{storage;code}balance~src_opt~pay_opt~self_opt>>=?fun(ctxt,{self;source;payer;balance})->letgas=matchgaswith|Somegas->gas|None->Constants.hard_gas_limit_per_operationctxtinletctxt=Gas.set_limitctxtgasinletnow=matchnowwithNone->Script_timestamp.nowctxt|Somet->tinletlevel=matchlevelwith|None->(Level.currentctxt).level|>Raw_level.to_int32|>Script_int.of_int32|>Script_int.abs|Somez->zinletstep_constants=letopenScript_interpreterinletsource=Destination.Contractsourcein{source;payer;self;amount;balance;chain_id;now;level}inletmoduleUnparsing_mode=structletunparsing_mode=unparsing_modeendinletmoduleInterp=Traced_interpreter(Unparsing_mode)inInterp.executectxtstep_constants~script:{storage;code}~entrypoint~parameter>|=?fun(({script=_;code_size=_;Script_interpreter.storage;operations;lazy_storage_diff;ticket_diffs=_;ticket_receipt=_;},_ctxt),trace)->(storage,Apply_internal_results.packed_internal_operationsoperations,trace,lazy_storage_diff));Registration.register0~chunked:trueS.run_tzip4_view(functxt()(contract_hash,entrypoint,input,chain_id,src_opt,pay_opt,gas,unparsing_mode,now,level)->Contract.get_scriptctxtcontract_hash>>=?fun(ctxt,script_opt)->Option.fold~some:ok~none:(errorView_helpers.Viewed_contract_has_no_script)script_opt>>?=funscript->Script_repr.(force_decodescript.code)>>?=fundecoded_script->script_entrypoint_typectxtdecoded_scriptentrypoint>>=?funview_ty->View_helpers.extract_view_output_typeentrypointview_ty>>?=funty->letcontract=Contract.Originatedcontract_hashinContract.get_balancectxtcontract>>=?funbalance->Error_monad.traceView_helpers.View_callback_origination_failed@@originate_dummy_contractctxt(View_helpers.make_tzip4_viewer_scriptty)Tez.zero>>=?fun(ctxt,viewer_contract)->letsource,payer=source_and_payer~src_opt~pay_opt~default_src:contract_hashinletgas=Option.value~default:(Constants.hard_gas_limit_per_operationctxt)gasinletctxt=Gas.set_limitctxtgasinletnow=matchnowwithNone->Script_timestamp.nowctxt|Somet->tinletlevel=matchlevelwith|None->(Level.currentctxt).level|>Raw_level.to_int32|>Script_int.of_int32|>Script_int.abs|Somez->zinletstep_constants=letopenScript_interpreterinletsource=Destination.Contractsourcein{source;payer;self=contract_hash;amount=Tez.zero;balance;chain_id;now;level;}inletparameter=View_helpers.make_view_parameter(Micheline.rootinput)(Contract.Originatedviewer_contract)inScript_interpreter.executectxtunparsing_modestep_constants~script~cached_script:None~entrypoint~parameter~internal:true>>=?fun({Script_interpreter.operations;script=_;code_size=_;storage=_;lazy_storage_diff=_;ticket_diffs=_;ticket_receipt=_;},_ctxt)->Lwt.return(View_helpers.extract_parameter_from_operationsentrypointoperationsviewer_contract));Registration.register0~chunked:trueS.run_script_view(functxt()((contract_hash,view,input,unlimited_gas,chain_id,src_opt,pay_opt,gas,unparsing_mode,now),level)->Contract.get_scriptctxtcontract_hash>>=?fun(ctxt,script_opt)->Option.fold~some:ok~none:(Error_monad.errorView_helpers.Viewed_contract_has_no_script)script_opt>>?=funscript->Script_repr.(force_decodescript.code)>>?=fundecoded_script->letcontract=Contract.Originatedcontract_hashinscript_view_typectxtcontract_hashdecoded_scriptview>>=?fun(input_ty,output_ty)->Contract.get_balancectxtcontract>>=?funbalance->letsource,payer=source_and_payer~src_opt~pay_opt~default_src:contract_hashinletnow=matchnowwithNone->Script_timestamp.nowctxt|Somet->tin(* Using [Gas.set_unlimited] won't work, since the interpreter doesn't
use this mode (see !4034#note_774734253) and still consumes gas.
Our best shot to emulate this is to use the maximum amount of
milligas possible which is represented by [2^62 - 1] according to
[Saturation_repr.saturated], which is [max_int]. *)letmax_gas=Gas.fp_of_milligas_intmax_intinletgas=Option.value~default:(Constants.hard_gas_limit_per_operationctxt)gasinletctxt=ifunlimited_gasthenGas.set_limitctxtmax_gaselseGas.set_limitctxtgasinletlevel=Option.valuelevel~default:((Level.currentctxt).level|>Raw_level.to_int32|>Script_int.of_int32|>Script_int.abs)inletstep_constants=letsource=Destination.Contractsourcein{Script_interpreter.source;payer;self=contract_hash;amount=Tez.zero;balance;chain_id;now;level;}inletviewer_script=View_helpers.make_michelson_viewer_scriptcontractviewinputinput_tyoutput_tyinletparameter=Micheline.(strip_locations(Prim(0,Script.D_Unit,[],[])))inScript_interpreter.executectxtunparsing_modestep_constants~script:viewer_script~cached_script:None~entrypoint:Entrypoint.default~parameter~internal:true>>=?fun({Script_interpreter.operations=_;script=_;code_size=_;storage;lazy_storage_diff=_;ticket_diffs=_;ticket_receipt=_;},_ctxt)->View_helpers.extract_value_from_storagestorage>>?=funvalue->return(Micheline.strip_locationsvalue));Registration.register0~chunked:falseS.typecheck_code(functxt()(expr,maybe_gas,legacy,show_types)->letlegacy=Option.value~default:falselegacyinletshow_types=Option.value~default:trueshow_typesinletctxt=matchmaybe_gaswith|None->Gas.set_unlimitedctxt|Somegas->Gas.set_limitctxtgasinScript_ir_translator.typecheck_code~legacy~show_typesctxtexpr>|=?fun(res,ctxt)->(res,Gas.levelctxt));Registration.register0~chunked:falseS.script_size(functxt()(expr,storage,maybe_gas,legacy)->letlegacy=Option.value~default:falselegacyinletctxt=matchmaybe_gaswith|None->Gas.set_unlimitedctxt|Somegas->Gas.set_limitctxtgasinletelab_conf=elab_conf~legacy()inletcode=Script.lazy_exprexprinScript_ir_translator.parse_code~elab_confctxt~code>>=?fun(Ex_code(Code{code;arg_type;storage_type;views;entrypoints;code_size;}),ctxt)->Script_ir_translator.parse_data~elab_conf~allow_forged:truectxtstorage_type(Micheline.rootstorage)>>=?fun(storage,_)->letscript=Script_ir_translator.Ex_script(Script{code;arg_type;storage_type;views;entrypoints;code_size;storage;})inletsize,cost=Script_ir_translator.script_sizescriptinGas.consumectxtcost>>?=fun_ctxt->return@@size);Registration.register0~chunked:falseS.typecheck_data(functxt()(data,ty,maybe_gas,legacy)->letlegacy=Option.value~default:falselegacyinletctxt=matchmaybe_gaswith|None->Gas.set_unlimitedctxt|Somegas->Gas.set_limitctxtgasintypecheck_data~legacyctxt(data,ty)>|=?functxt->Gas.levelctxt);Registration.register0~chunked:trueS.pack_data(functxt()(expr,typ,maybe_gas)->letopenScript_ir_translatorinletctxt=matchmaybe_gaswith|None->Gas.set_unlimitedctxt|Somegas->Gas.set_limitctxtgasinparse_packable_tyctxt~legacy:true(Micheline.roottyp)>>?=fun(Ex_tytyp,ctxt)->parse_datactxt~elab_conf:(elab_conf~legacy:true())~allow_forged:truetyp(Micheline.rootexpr)>>=?fun(data,ctxt)->Script_ir_translator.pack_datactxttypdata>|=?fun(bytes,ctxt)->(bytes,Gas.levelctxt));Registration.register0~chunked:trueS.normalize_data(functxt()(expr,typ,unparsing_mode,legacy)->letopenScript_ir_translatorinletlegacy=Option.value~default:falselegacyinletctxt=Gas.set_unlimitedctxtinScript_ir_translator.parse_any_tyctxt~legacy(Micheline.roottyp)>>?=fun(Ex_tytyp,ctxt)->parse_datactxt~elab_conf:(elab_conf~legacy())~allow_forged:truetyp(Micheline.rootexpr)>>=?fun(data,ctxt)->Script_ir_translator.unparse_datactxtunparsing_modetypdata>|=?fun(normalized,_ctxt)->normalized);Registration.register0~chunked:trueS.normalize_script(functxt()(script,unparsing_mode)->letctxt=Gas.set_unlimitedctxtinScript_ir_translator.unparse_codectxtunparsing_mode(Micheline.rootscript)>|=?fun(normalized,_ctxt)->normalized);Registration.register0~chunked:trueS.normalize_type(functxt()typ->letopenScript_typed_irinletctxt=Gas.set_unlimitedctxtin(* Unfortunately, Script_ir_translator.parse_any_ty is not exported *)Script_ir_translator.parse_tyctxt~legacy:true~allow_lazy_storage:true~allow_operation:true~allow_contract:true~allow_ticket:true(Micheline.roottyp)>>?=fun(Ex_tytyp,_ctxt)->letnormalized=Unparse_types.unparse_ty~loc:()typinreturn@@Micheline.strip_locationsnormalized);(* TODO: https://gitlab.com/tezos/tezos/-/issues/3364
Should [run_operation] be registered at successor level? *)Registration.register0_fullctxt~chunked:trueS.run_operationrun_operation_service;Registration.register0_fullctxt_successor_level~chunked:trueS.simulate_operationsimulate_operation_service;Registration.register0~chunked:trueS.entrypoint_type(functxt()(expr,entrypoint)->script_entrypoint_typectxtexprentrypoint);Registration.register0~chunked:trueS.list_entrypoints(functxt()expr->letctxt=Gas.set_unlimitedctxtinletlegacy=falseinletopenScript_ir_translatorinparse_toplevel~legacyctxtexpr>>=?fun({arg_type;_},ctxt)->Lwt.return(parse_parameter_ty_and_entrypointsctxt~legacyarg_type>|?fun(Ex_parameter_ty_and_entrypoints{arg_type;entrypoints},_)->letunreachable_entrypoint,map=Script_ir_translator.list_entrypoints_uncarbonatedarg_typeentrypointsin(unreachable_entrypoint,Entrypoint.Map.fold(funentry(_ex_ty,original_type_expr)acc->(Entrypoint.to_stringentry,Micheline.strip_locationsoriginal_type_expr)::acc)map[])))letrun_code?unparsing_mode?gas?(entrypoint=Entrypoint.default)?balance~script~storage~input~amount~chain_id~source~payer~self~now~levelctxtblock=RPC_context.make_call0S.run_codectxtblock()((script,storage,input,amount,balance,chain_id,source,payer,self,entrypoint),(unparsing_mode,gas,now,level))lettrace_code?unparsing_mode?gas?(entrypoint=Entrypoint.default)?balance~script~storage~input~amount~chain_id~source~payer~self~now~levelctxtblock=RPC_context.make_call0S.trace_codectxtblock()((script,storage,input,amount,balance,chain_id,source,payer,self,entrypoint),(unparsing_mode,gas,now,level))letrun_tzip4_view?gas~contract~entrypoint~input~chain_id~now~level?source?payer~unparsing_modectxtblock=RPC_context.make_call0S.run_tzip4_viewctxtblock()(contract,entrypoint,input,chain_id,source,payer,gas,unparsing_mode,now,level)(** [run_script_view] is an helper function to call the corresponding
RPC. [unlimited_gas] is set to [false] by default. *)letrun_script_view?gas~contract~view~input?(unlimited_gas=false)~chain_id~now~level?source?payer~unparsing_modectxtblock=RPC_context.make_call0S.run_script_viewctxtblock()((contract,view,input,unlimited_gas,chain_id,source,payer,gas,unparsing_mode,now),level)lettypecheck_code?gas?legacy~script?show_typesctxtblock=RPC_context.make_call0S.typecheck_codectxtblock()(script,gas,legacy,show_types)letscript_size?gas?legacy~script~storagectxtblock=RPC_context.make_call0S.script_sizectxtblock()(script,storage,gas,legacy)lettypecheck_data?gas?legacy~data~tyctxtblock=RPC_context.make_call0S.typecheck_datactxtblock()(data,ty,gas,legacy)letpack_data?gas~data~tyctxtblock=RPC_context.make_call0S.pack_datactxtblock()(data,ty,gas)letnormalize_data?legacy~data~ty~unparsing_modectxtblock=RPC_context.make_call0S.normalize_datactxtblock()(data,ty,unparsing_mode,legacy)letnormalize_script~script~unparsing_modectxtblock=RPC_context.make_call0S.normalize_scriptctxtblock()(script,unparsing_mode)letnormalize_type~tyctxtblock=RPC_context.make_call0S.normalize_typectxtblock()tyletrun_operation~op~chain_idctxtblock=RPC_context.make_call0S.run_operationctxtblock()(op,chain_id)letsimulate_operation~op~chain_id~latency?(successor_level=false)?blocks_before_activationctxtblock=RPC_context.make_call0S.simulate_operationctxtblock(objectmethodsuccessor_level=successor_levelend)(blocks_before_activation,op,chain_id,latency)letentrypoint_type~script~entrypointctxtblock=RPC_context.make_call0S.entrypoint_typectxtblock()(script,entrypoint)letlist_entrypointsctxtblock~script=RPC_context.make_call0S.list_entrypointsctxtblock()scriptendmoduleContract=structletticket_balances_encoding=letopenData_encodinginlist(merge_objsTicket_token.unparsed_token_encoding(obj1(req"amount"n)))moduleS=structletpath=(RPC_path.(open_root/"context"/"contracts"):RPC_context.tRPC_path.context)letget_storage_normalized=letopenData_encodinginRPC_service.post_service~description:"Access the data of the contract and normalize it using the \
requested unparsing mode."~input:(obj1(req"unparsing_mode"unparsing_mode_encoding))~query:RPC_query.empty~output:(optionScript.expr_encoding)RPC_path.(path/:Contract.rpc_arg/"storage"/"normalized")letget_script_normalized=letopenData_encodinginRPC_service.post_service~description:"Access the script of the contract and normalize it using the \
requested unparsing mode."~input:(obj2(req"unparsing_mode"unparsing_mode_encoding)(dft"normalize_types"boolfalse))~query:RPC_query.empty~output:(optionScript.encoding)RPC_path.(path/:Contract.rpc_arg/"script"/"normalized")letget_used_storage_space=letopenData_encodinginRPC_service.get_service~description:"Access the used storage space of the contract."~query:RPC_query.empty~output:(optionz)RPC_path.(path/:Contract.rpc_arg/"storage"/"used_space")letget_paid_storage_space=letopenData_encodinginRPC_service.get_service~description:"Access the paid storage space of the contract."~query:RPC_query.empty~output:(optionz)RPC_path.(path/:Contract.rpc_arg/"storage"/"paid_space")letticket_balance=letopenData_encodinginRPC_service.post_service~description:"Access the contract's balance of ticket with specified ticketer, \
content type, and content."~query:RPC_query.empty~input:Ticket_token.unparsed_token_encoding~output:nRPC_path.(path/:Contract.rpc_arg/"ticket_balance")letall_ticket_balances=RPC_service.get_service~description:"Access the complete list of tickets owned by the given contract by \
scanning the contract's storage."~query:RPC_query.empty~output:ticket_balances_encodingRPC_path.(path/:Contract.rpc_arg/"all_ticket_balances")endletget_contractcontractf=matchcontractwith|Contract.Implicit_->return_none|Contract.Originatedcontract->fcontractletregister()=(* Patched RPC: get_storage *)Registration.register1~chunked:trueS.get_storage_normalized(functxtcontract()unparsing_mode->get_contractcontract@@funcontract->Contract.get_scriptctxtcontract>>=?fun(ctxt,script)->matchscriptwith|None->return_none|Somescript->letctxt=Gas.set_unlimitedctxtinletopenScript_ir_translatorinparse_scriptctxt~elab_conf:(elab_conf~legacy:true())~allow_forged_in_storage:truescript>>=?fun(Ex_script(Script{storage;storage_type;_}),ctxt)->unparse_datactxtunparsing_modestorage_typestorage>|=?fun(storage,_ctxt)->Somestorage);(* Patched RPC: get_script *)Registration.register1~chunked:trueS.get_script_normalized(functxtcontract()(unparsing_mode,normalize_types)->get_contractcontract@@funcontract->Contract.get_scriptctxtcontract>>=?fun(ctxt,script)->matchscriptwith|None->return_none|Somescript->letctxt=Gas.set_unlimitedctxtinScript_ir_translator.parse_and_unparse_script_unaccountedctxt~legacy:true~allow_forged_in_storage:trueunparsing_mode~normalize_typesscript>>=?fun(script,_ctxt)->return_somescript);Registration.register1~chunked:falseS.get_used_storage_space(functxtcontract()()->get_contractcontract@@fun_->Contract.used_storage_spacectxtcontract>>=?return_some);Registration.register1~chunked:falseS.get_paid_storage_space(functxtcontract()()->get_contractcontract@@fun_->Contract.paid_storage_spacectxtcontract>>=?return_some);Registration.register1~chunked:falseS.ticket_balance(functxtcontract()Ticket_token.{ticketer;contents_type;contents}->letopenLwt_result_syntaxinlet*ticket_hash,ctxt=Ticket_balance_key.makectxt~owner:(Contractcontract)~ticketer~contents_type:(Micheline.rootcontents_type)~contents:(Micheline.rootcontents)inlet*amount,_ctxt=Ticket_balance.get_balancectxtticket_hashinreturn@@Option.valueamount~default:Z.zero);Registration.opt_register1~chunked:falseS.all_ticket_balances(functxtcontract()()->get_contractcontract@@funcontract->letopenLwt_result_syntaxinlet*ctxt,script=Contract.get_scriptctxtcontractinmatchscriptwith|None->return_none|Somescript->let*Ex_script(Script{storage;storage_type;_}),ctxt=Script_ir_translator.parse_scriptctxt~elab_conf:(elab_conf~legacy:true())~allow_forged_in_storage:truescriptinlet*?has_tickets,ctxt=Ticket_scanner.type_has_ticketsctxtstorage_typeinlet*ticket_token_map,ctxt=Ticket_accounting.ticket_balances_of_valuectxt~include_lazy:truehas_ticketsstorageinlet*ticket_balances,_ctxt=Ticket_token_map.fold_esctxt(functxtaccex_tokenamount->let*unparsed_token,ctxt=Ticket_token_unparser.unparsectxtex_tokeninreturn((unparsed_token,amount)::acc,ctxt))[]ticket_token_mapinreturn_someticket_balances)letget_storage_normalizedctxtblock~contract~unparsing_mode=RPC_context.make_call1S.get_storage_normalizedctxtblock(Contract.Originatedcontract)()unparsing_modeletget_script_normalizedctxtblock~contract~unparsing_mode~normalize_types=RPC_context.make_call1S.get_script_normalizedctxtblock(Contract.Originatedcontract)()(unparsing_mode,normalize_types)letget_used_storage_spacectxtblock~contract=RPC_context.make_call1S.get_used_storage_spacectxtblock(Contract.Originatedcontract)()()letget_paid_storage_spacectxtblock~contract=RPC_context.make_call1S.get_paid_storage_spacectxtblock(Contract.Originatedcontract)()()letget_ticket_balancectxtblockcontractkey=RPC_context.make_call1S.ticket_balancectxtblockcontract()keyletget_all_ticket_balancesctxtblockcontract=RPC_context.make_call1S.all_ticket_balancesctxtblock(Contract.Originatedcontract)()()endmoduleBig_map=structmoduleS=structletpath=(RPC_path.(open_root/"context"/"big_maps"):RPC_context.tRPC_path.context)letbig_map_get_normalized=letopenData_encodinginRPC_service.post_service~description:"Access the value associated with a key in a big map, normalize the \
output using the requested unparsing mode."~query:RPC_query.empty~input:(obj1(req"unparsing_mode"unparsing_mode_encoding))~output:Script.expr_encodingRPC_path.(path/:Big_map.Id.rpc_arg/:Script_expr_hash.rpc_arg/"normalized")endletregister()=Registration.register2~chunked:trueS.big_map_get_normalized(functxtidkey()unparsing_mode->letopenScript_ir_translatorinletctxt=Gas.set_unlimitedctxtinBig_map.existsctxtid>>=?fun(ctxt,types)->matchtypeswith|None->raiseNot_found|Some(_,value_type)->(parse_big_map_value_tyctxt~legacy:true(Micheline.rootvalue_type)>>?=fun(Ex_tyvalue_type,ctxt)->Big_map.get_optctxtidkey>>=?fun(_ctxt,value)->matchvaluewith|None->raiseNot_found|Somevalue->parse_datactxt~elab_conf:(elab_conf~legacy:true())~allow_forged:truevalue_type(Micheline.rootvalue)>>=?fun(value,ctxt)->unparse_datactxtunparsing_modevalue_typevalue>|=?fun(value,_ctxt)->value))letbig_map_get_normalizedctxtblockidkey~unparsing_mode=RPC_context.make_call2S.big_map_get_normalizedctxtblockidkey()unparsing_modeendmoduleSc_rollup=structopenData_encodingmoduleS=structletprefix:RPC_context.tRPC_path.context=RPC_path.(open_root/"context"/"smart_rollups")letpath_sc_rollup:(RPC_context.t,RPC_context.t*Sc_rollup.t)RPC_path.t=RPC_path.(prefix/"smart_rollup"/:Sc_rollup.Address.rpc_arg)letpath_sc_rollups:RPC_context.tRPC_path.context=RPC_path.(prefix/"all")letkind=RPC_service.get_service~description:"Kind of smart rollup"~query:RPC_query.empty~output:Sc_rollup.Kind.encodingRPC_path.(path_sc_rollup/"kind")letinitial_pvm_state_hash=RPC_service.get_service~description:"Initial PVM state hash of smart rollup"~query:RPC_query.empty~output:Sc_rollup.State_hash.encodingRPC_path.(path_sc_rollup/"initial_pvm_state_hash")letgenesis_info=RPC_service.get_service~description:"Genesis information (level and commitment hash) for a smart rollup"~query:RPC_query.empty~output:Sc_rollup.Commitment.genesis_info_encodingRPC_path.(path_sc_rollup/"genesis_info")letlast_cemented_commitment_hash_with_level=RPC_service.get_service~description:"Level and hash of the last cemented commitment for a smart rollup"~query:RPC_query.empty~output:(obj2(req"hash"Sc_rollup.Commitment.Hash.encoding)(req"level"Raw_level.encoding))RPC_path.(path_sc_rollup/"last_cemented_commitment_hash_with_level")letstaked_on_commitment=RPC_service.get_service~description:"The newest commitment on which the operator has staked on for a \
smart rollup. Note that is can return a commitment that is before \
the last cemented one."~query:RPC_query.empty~output:(option(merge_objs(obj1(req"hash"Sc_rollup.Commitment.Hash.encoding))Sc_rollup.Commitment.encoding))RPC_path.(path_sc_rollup/"staker"/:Sc_rollup.Staker.rpc_arg/"staked_on_commitment")letcommitment=RPC_service.get_service~description:"Commitment for a smart rollup from its hash"~query:RPC_query.empty~output:Sc_rollup.Commitment.encodingRPC_path.(path_sc_rollup/"commitment"/:Sc_rollup.Commitment.Hash.rpc_arg)letdal_slot_subscriptions=RPC_service.get_service~description:"List of slot indices to which a rollup is subscribed to at a given \
level"~query:RPC_query.empty~output:(Data_encoding.listDal.Slot_index.encoding)RPC_path.(path_sc_rollup/"dal_slot_subscriptions"/:Raw_level.rpc_arg)letongoing_refutation_games=letoutput=Sc_rollup.(Data_encoding.(list(obj3(req"game"Game.encoding)(req"alice"Staker.encoding)(req"bob"Staker.encoding))))inRPC_service.get_service~description:"Ongoing refutation games for a given staker"~query:RPC_query.empty~outputRPC_path.(path_sc_rollup/"staker"/:Sc_rollup.Staker.rpc_arg/"games")letcommitments=letoutput=Data_encoding.(option(listSc_rollup.Commitment.Hash.encoding))inRPC_service.get_service~description:"List of commitments associated to a rollup for a given inbox level"~query:RPC_query.empty~outputRPC_path.(path_sc_rollup/"inbox_level"/:Raw_level.rpc_arg/"commitments")letstakers_ids=letoutput=Data_encoding.listSc_rollup.Staker.Index.encodinginRPC_service.get_service~description:"List of stakers indexes staking on a given commitment"~query:RPC_query.empty~outputRPC_path.(path_sc_rollup/"commitment"/:Sc_rollup.Commitment.Hash.rpc_arg/"stakers_indexes")letstaker_id=letoutput=Sc_rollup.Staker.Index.encodinginRPC_service.get_service~description:"Staker index associated to a public key hash for a given rollup"~query:RPC_query.empty~outputRPC_path.(path_sc_rollup/"staker"/:Sc_rollup.Staker.rpc_arg/"index")letstakers=letoutput=Data_encoding.listSc_rollup.Staker.encodinginRPC_service.get_service~description:"List of active stakers' public key hashes of a rollup"~query:RPC_query.empty~outputRPC_path.(path_sc_rollup/"stakers")letconflicts=letoutput=Sc_rollup.(Data_encoding.listRefutation_storage.conflict_encoding)inRPC_service.get_service~description:"List of stakers in conflict with the given staker"~query:RPC_query.empty~outputRPC_path.(path_sc_rollup/"staker"/:Sc_rollup.Staker.rpc_arg/"conflicts")lettimeout=letoutput=Data_encoding.optionSc_rollup.Game.timeout_encodinginRPC_service.get_service~description:"Returns the timeout of players."~query:RPC_query.empty~outputRPC_path.(path_sc_rollup/"staker1"/:Sc_rollup.Staker.rpc_arg/"staker2"/:Sc_rollup.Staker.rpc_arg/"timeout")lettimeout_reached=letoutput=Data_encoding.optionSc_rollup.Game.game_result_encodinginRPC_service.get_service~description:"Returns whether the timeout creates a result for the game."~query:RPC_query.empty~outputRPC_path.(path_sc_rollup/"staker1"/:Sc_rollup.Staker.rpc_arg/"staker2"/:Sc_rollup.Staker.rpc_arg/"timeout_reached")letcan_be_cemented=letoutput=Data_encoding.boolinRPC_service.get_service~description:"Returns true if and only if the provided commitment can be cemented."~query:RPC_query.empty~outputRPC_path.(path_sc_rollup/"commitment"/:Sc_rollup.Commitment.Hash.rpc_arg/"can_be_cemented")letorigination_proof=RPC_service.post_service~description:"Proof for a smart rollup origination"~query:RPC_query.empty~input:(obj2(req"kind"Sc_rollup.Kind.encoding)(req"kernel"(stringHex)))~output:Sc_rollup.Proof.serialized_encodingRPC_path.(path_sc_rollups/"origination_proof")letroot=RPC_service.get_service~description:"List of all originated smart rollups"~query:RPC_query.empty~output:(Data_encoding.listSc_rollup.Address.encoding)path_sc_rollupsletinbox=RPC_service.get_service~description:"Inbox for the smart rollups"~query:RPC_query.empty~output:Sc_rollup.Inbox.encodingRPC_path.(path_sc_rollups/"inbox")letticket_balance=letopenData_encodinginRPC_service.post_service~description:"Access the smart rollup's balance of ticket with specified \
ticketer, content type, and content."~query:RPC_query.empty~input:Ticket_token.unparsed_token_encoding~output:nRPC_path.(path_sc_rollup/"ticket_balance")endletkindctxtblocksc_rollup_address=RPC_context.make_call1S.kindctxtblocksc_rollup_address()letregister_inbox()=Registration.register0~chunked:trueS.inbox(functxt()()->Sc_rollup.Inbox.get_inboxctxt>>=?fun(inbox,_ctxt)->returninbox)letregister_origination_proof()=Registration.register0~chunked:trueS.origination_proof(fun_ctxt()(kind,boot_sector)->Proof_helpers.origination_proof~boot_sectorkind)letregister_kind()=Registration.opt_register1~chunked:trueS.kind@@functxtaddress()()->Alpha_context.Sc_rollup.kindctxtaddress>|=?fun(_ctxt,kind)->Somekindletregister_initial_pvm_state_hash()=Registration.opt_register1~chunked:trueS.initial_pvm_state_hash@@functxtaddress()()->Alpha_context.Sc_rollup.kindctxtaddress>|=?fun(_ctxt,kind)->matchkindwith|Sc_rollup.Kind.Example_arith->SomeSc_rollup.ArithPVM.reference_initial_state_hash|Sc_rollup.Kind.Wasm_2_0_0->SomeSc_rollup.Wasm_2_0_0PVM.reference_initial_state_hash(* TODO: https://gitlab.com/tezos/tezos/-/issues/2688 *)letregister_genesis_info()=letopenLwt_result_syntaxinRegistration.register1~chunked:trueS.genesis_info@@functxtaddress()()->let+_ctxt,genesis_info=Alpha_context.Sc_rollup.genesis_infoctxtaddressingenesis_infoletregister_last_cemented_commitment_hash_with_level()=Registration.register1~chunked:falseS.last_cemented_commitment_hash_with_level@@functxtaddress()()->letopenLwt_result_syntaxinlet+last_cemented_commitment,level,_ctxt=Alpha_context.Sc_rollup.Commitment.last_cemented_commitment_hash_with_levelctxtaddressin(last_cemented_commitment,level)letregister_staked_on_commitment()=Registration.register2~chunked:falseS.staked_on_commitment@@functxtaddressstaker()()->letopenLwt_result_syntaxinlet*ctxt,commitment_hash=Alpha_context.Sc_rollup.Stake_storage.find_stakerctxtaddressstakerinmatchcommitment_hashwith|None->return_none|Somecommitment_hash->let*commitment,_ctxt=Alpha_context.Sc_rollup.Commitment.get_commitmentctxtaddresscommitment_hashinreturn_some(commitment_hash,commitment)letregister_commitment()=Registration.register2~chunked:falseS.commitment@@functxtaddresscommitment_hash()()->letopenLwt_result_syntaxinlet+commitment,_=Alpha_context.Sc_rollup.Commitment.get_commitmentctxtaddresscommitment_hashincommitmentletregister_root()=Registration.register0~chunked:trueS.root(funcontext()()->Sc_rollup.list_unaccountedcontext)letregister_ongoing_refutation_games()=Registration.register2~chunked:falseS.ongoing_refutation_games(funcontextrollupstaker()()->letopenLwt_result_syntaxinletopenSc_rollup.Game.IndexinletopenSc_rollup.Refutation_storageinlet*game,_=get_ongoing_games_for_stakercontextrollupstakerinletgame=List.map(fun(game,index)->(game,index.alice,index.bob))gameinreturngame)letregister_commitments()=Registration.register2~chunked:falseS.commitments(funcontextrollupinbox_level()()->Sc_rollup.Stake_storage.commitments_uncarbonatedcontext~rollup~inbox_level)letregister_stakers_ids()=Registration.register2~chunked:falseS.stakers_ids(funcontextrollupcommitment()()->Sc_rollup.Stake_storage.stakers_ids_uncarbonatedcontext~rollup~commitment)letregister_staker_id()=Registration.register2~chunked:falseS.staker_id(funcontextrolluppkh()()->Sc_rollup.Stake_storage.staker_id_uncarbonatedcontext~rollup~pkh)letregister_stakers()=Registration.register1~chunked:falseS.stakers(funcontextrollup()()->letopenLwt_result_syntaxinlet*!stakers_pkhs=Sc_rollup.Stake_storage.stakers_pkhs_uncarbonatedcontext~rollupinreturnstakers_pkhs)letregister_conflicts()=Registration.register2~chunked:falseS.conflicts(funcontextrollupstaker()()->Sc_rollup.Refutation_storage.conflicting_stakers_uncarbonatedcontextrollupstaker)letregister_timeout()=Registration.register3~chunked:falseS.timeout(funcontextrollupstaker1staker2()()->letopenLwt_result_syntaxinletindex=Sc_rollup.Game.Index.makestaker1staker2inlet*!res=Sc_rollup.Refutation_storage.get_timeoutcontextrollupindexinmatchreswith|Ok(timeout,_context)->return_sometimeout|Error_->return_none)letregister_timeout_reached()=Registration.register3~chunked:falseS.timeout_reached(funcontextrollupstaker1staker2()()->letopenLwt_result_syntaxinletindex=Sc_rollup.Game.Index.makestaker1staker2inlet*!res=Sc_rollup.Refutation_storage.timeoutcontextrollupindexinmatchreswith|Ok(game_result,_context)->return_somegame_result|Error_->return_none)letregister_can_be_cemented()=Registration.register2~chunked:falseS.can_be_cemented(funcontextrollupcommitment_hash()()->letopenLwt_result_syntaxinlet*!res=Sc_rollup.Stake_storage.cement_commitmentcontextrollupcommitment_hashinmatchreswithOk_context->return_true|Error_->return_false)letregister_ticket_balance()=Registration.register1~chunked:falseS.ticket_balance(functxtsc_rollup()Ticket_token.{ticketer;contents_type;contents}->letopenLwt_result_syntaxinlet*ticket_hash,ctxt=Ticket_balance_key.makectxt~owner:(Sc_rollupsc_rollup)~ticketer~contents_type:(Micheline.rootcontents_type)~contents:(Micheline.rootcontents)inlet*amount,_ctxt=Ticket_balance.get_balancectxtticket_hashinreturn@@Option.valueamount~default:Z.zero)letregister()=register_kind();register_inbox();register_origination_proof();register_genesis_info();register_last_cemented_commitment_hash_with_level();register_staked_on_commitment();register_commitment();register_root();register_ongoing_refutation_games();register_commitments();register_stakers_ids();register_staker_id();register_stakers();register_conflicts();register_timeout();register_timeout_reached();register_can_be_cemented();register_initial_pvm_state_hash();register_ticket_balance()letlistctxtblock=RPC_context.make_call0S.rootctxtblock()()letinboxctxtblock=RPC_context.make_call0S.inboxctxtblock()()letorigination_proofctxtblockkindboot_sector=RPC_context.make_call0S.origination_proofctxtblock()(kind,boot_sector)letgenesis_infoctxtblocksc_rollup_address=RPC_context.make_call1S.genesis_infoctxtblocksc_rollup_address()()letlast_cemented_commitment_hash_with_levelctxtblocksc_rollup_address=RPC_context.make_call1S.last_cemented_commitment_hash_with_levelctxtblocksc_rollup_address()()letstaked_on_commitmentctxtblocksc_rollup_addressstaker=RPC_context.make_call2S.staked_on_commitmentctxtblocksc_rollup_addressstaker()()letcommitmentctxtblocksc_rollup_addresscommitment_hash=RPC_context.make_call2S.commitmentctxtblocksc_rollup_addresscommitment_hash()()letongoing_refutation_gamesctxtblocksc_rollup_addressstaker=RPC_context.make_call2S.ongoing_refutation_gamesctxtblocksc_rollup_addressstaker()()letcommitmentsctxtrollupinbox_level=RPC_context.make_call2S.commitmentsctxtrollupinbox_levelletstakers_idsctxtrollupcommitment=RPC_context.make_call2S.stakers_idsctxtrollupcommitmentletstaker_idctxtrolluppkh=RPC_context.make_call2S.staker_idctxtrolluppkhletstakersctxtrollup=RPC_context.make_call1S.stakersctxtrollupletconflictsctxtblocksc_rollup_addressstaker=RPC_context.make_call2S.conflictsctxtblocksc_rollup_addressstaker()()lettimeout_reachedctxtblocksc_rollup_addressstaker1staker2=RPC_context.make_call3S.timeout_reachedctxtblocksc_rollup_addressstaker1staker2()()letinitial_pvm_state_hashctxtblocksc_rollup_address=RPC_context.make_call1S.initial_pvm_state_hashctxtblocksc_rollup_address()()letcan_be_cementedctxtblocksc_rollup_addresscommitment_hash=RPC_context.make_call2S.can_be_cementedctxtblocksc_rollup_addresscommitment_hash()()letget_ticket_balancectxtblocksc_rollupkey=RPC_context.make_call1S.ticket_balancectxtblocksc_rollup()keyendmoduleDal=structletpath:RPC_context.tRPC_path.context=RPC_path.(open_root/"context"/"dal")moduleS=structletdal_confirmed_slot_headers_history=letoutput=Data_encoding.optionDal.Slots_history.encodinginletquery=RPC_query.(seal@@query())inRPC_service.get_service~description:"Returns the value of the DAL confirmed slots history skip list if \
DAL is enabled, or [None] otherwise."~output~queryRPC_path.(path/"confirmed_slot_headers_history")letshards_query=RPC_query.(query(funlevel->level)|+opt_field"level"Raw_level.rpc_arg(funt->t)|>seal)letshards=RPC_service.get_service~description:"Get the shard assignements for a given level"~query:shards_query~output:Data_encoding.(list(tup2Signature.Public_key_hash.encoding(tup2int16int16)))RPC_path.(path/"shards")endletregister_dal_confirmed_slot_headers_history()=Registration.register0~chunked:falseS.dal_confirmed_slot_headers_history(functxt()()->if(Constants.parametricctxt).dal.feature_enablethenDal.Slots_storage.get_slot_headers_historyctxt>|=?Option.someelsereturnNone)letdal_confirmed_slots_historyctxtblock=RPC_context.make_call0S.dal_confirmed_slot_headers_historyctxtblock()()letregister_shards()=Registration.register0~chunked:trueS.shards@@functxtlevel()->letlevel=Option.valuelevel~default:(Raw_level.of_int32_exn0l)inDal_services.shardsctxt~levelletregister()=register_dal_confirmed_slot_headers_history();register_shards()endmoduleTx_rollup=structopenData_encodingmoduleS=structletpath:RPC_context.tRPC_path.context=RPC_path.(open_root/"context"/"tx_rollup")lethas_bond=RPC_service.get_service~description:"Returns true if the public key hash already deposited a bond for \
the given rollup"~query:RPC_query.empty~output:boolRPC_path.(path/:Tx_rollup.rpc_arg/"has_bond"/:Signature.Public_key_hash.rpc_arg)endletregister_has_bond()=Registration.register2~chunked:falseS.has_bond(functxtrollupoperator()()->Tx_rollup_commitment.has_bondctxtrollupoperator>>=?fun(_ctxt,has_bond)->returnhas_bond)letregister()=register_has_bond()lethas_bondctxtblockrollupoperator=RPC_context.make_call2S.has_bondctxtblockrollupoperator()()endmoduleForge=structmoduleS=structopenData_encodingletpath=RPC_path.(path/"forge")letoperations=RPC_service.post_service~description:"Forge an operation"~query:RPC_query.empty~input:Operation.unsigned_encoding~output:(bytesHex)RPC_path.(path/"operations")letempty_proof_of_work_nonce=Bytes.makeConstants_repr.proof_of_work_nonce_size'\000'letprotocol_data=RPC_service.post_service~description:"Forge the protocol-specific part of a block header"~query:RPC_query.empty~input:(obj5(req"payload_hash"Block_payload_hash.encoding)(req"payload_round"Round.encoding)(opt"nonce_hash"Nonce_hash.encoding)(dft"proof_of_work_nonce"(Fixed.bytesHexAlpha_context.Constants.proof_of_work_nonce_size)empty_proof_of_work_nonce)Liquidity_baking.(dft"liquidity_baking_toggle_vote"liquidity_baking_toggle_vote_encodingLB_pass))~output:(obj1(req"protocol_data"(bytesHex)))RPC_path.(path/"protocol_data")moduleTx_rollup=structopenData_encodingletpath=RPC_path.(path/"tx_rollup")moduleInbox=structletpath=RPC_path.(path/"inbox")letmessage_hash=RPC_service.post_service~description:"Compute the hash of a message"~query:RPC_query.empty~input:(obj1(req"message"Tx_rollup_message.encoding))~output:(obj1(req"hash"Tx_rollup_message_hash.encoding))RPC_path.(path/"message_hash")letmerkle_tree_hash=RPC_service.post_service~description:"Compute the merkle tree hash of an inbox"~query:RPC_query.empty~input:(obj1(req"message_hashes"(listTx_rollup_message_hash.encoding)))~output:(obj1(req"hash"Tx_rollup_inbox.Merkle.root_encoding))RPC_path.(path/"merkle_tree_hash")letmerkle_tree_path=RPC_service.post_service~description:"Compute a path of an inbox message in a merkle tree"~query:RPC_query.empty~input:(obj2(req"message_hashes"(listTx_rollup_message_hash.encoding))(req"position"int16))~output:(obj1(req"path"Tx_rollup_inbox.Merkle.path_encoding))RPC_path.(path/"merkle_tree_path")endmoduleCommitment=structletpath=RPC_path.(path/"commitment")letmerkle_tree_hash=RPC_service.post_service~description:"Compute the merkle tree hash of a commitment"~query:RPC_query.empty~input:(obj1(req"message_result_hashes"(listTx_rollup_message_result_hash.encoding)))~output:(obj1(req"hash"Tx_rollup_commitment.Merkle_hash.encoding))RPC_path.(path/"merkle_tree_hash")letmerkle_tree_path=RPC_service.post_service~description:"Compute a path of a message result hash in the commitment \
merkle tree"~query:RPC_query.empty~input:(obj2(req"message_result_hashes"(listTx_rollup_message_result_hash.encoding))(req"position"int16))~output:(obj1(req"path"Tx_rollup_commitment.Merkle.path_encoding))RPC_path.(path/"merkle_tree_path")letmessage_result_hash=RPC_service.post_service~description:"Compute the message result hash"~query:RPC_query.empty~input:Tx_rollup_message_result.encoding~output:(obj1(req"hash"Tx_rollup_message_result_hash.encoding))RPC_path.(path/"message_result_hash")endmoduleWithdraw=structletpath=RPC_path.(path/"withdraw")letwithdraw_list_hash=RPC_service.post_service~description:"Compute the hash of a withdraw list"~query:RPC_query.empty~input:(obj1(req"withdraw_list"(listTx_rollup_withdraw.encoding)))~output:(obj1(req"hash"Tx_rollup_withdraw_list_hash.encoding))RPC_path.(path/"withdraw_list_hash")endendendletregister()=Registration.register0_noctxt~chunked:trueS.operations(fun()(shell,proto)->return(Data_encoding.Binary.to_bytes_exnOperation.unsigned_encoding(shell,proto)));Registration.register0_noctxt~chunked:trueS.protocol_data(fun()(payload_hash,payload_round,seed_nonce_hash,proof_of_work_nonce,liquidity_baking_toggle_vote)->return(Data_encoding.Binary.to_bytes_exnBlock_header.contents_encoding{payload_hash;payload_round;seed_nonce_hash;proof_of_work_nonce;liquidity_baking_toggle_vote;}));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Inbox.message_hash(fun()message->return(Tx_rollup_message_hash.hash_uncarbonatedmessage));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Inbox.merkle_tree_hash(fun()message_hashes->return(Tx_rollup_inbox.Merkle.merklize_listmessage_hashes));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Inbox.merkle_tree_path(fun()(message_hashes,position)->Lwt.return(Tx_rollup_inbox.Merkle.compute_pathmessage_hashesposition));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Commitment.merkle_tree_hash(fun()message_result_hashes->letopenTx_rollup_commitment.Merkleinlettree=List.fold_leftsnocnilmessage_result_hashesinreturn(roottree));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Commitment.merkle_tree_path(fun()(message_result_hashes,position)->letopenTx_rollup_commitment.Merkleinlettree=List.fold_leftsnocnilmessage_result_hashesinLwt.return(compute_pathtreeposition));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Commitment.message_result_hash(fun()message_result->return(Tx_rollup_message_result_hash.hash_uncarbonatedmessage_result));Registration.register0_noctxt~chunked:trueS.Tx_rollup.Withdraw.withdraw_list_hash(fun()withdrawals->return(Tx_rollup_withdraw_list_hash.hash_uncarbonatedwithdrawals))moduleManager=structletoperationsctxtblock~branch~source?sourcePubKey~counter~fee~gas_limit~storage_limitoperations=Contract_services.manager_keyctxtblocksource>>=function|Error_ase->Lwt.returne|Okrevealed->letops=List.map(fun(Manageroperation)->Contents(Manager_operation{source;counter;operation;fee;gas_limit;storage_limit}))operationsinletops=match(sourcePubKey,revealed)with|None,_|_,Some_->ops|Somepk,None->letoperation=RevealpkinContents(Manager_operation{source;counter;operation;fee;gas_limit;storage_limit})::opsinEnvironment.wrap_tzresult@@Operation.of_listops>>?=funops->RPC_context.make_call0S.operationsctxtblock()({branch},ops)letrevealctxtblock~branch~source~sourcePubKey~counter~fee()=operationsctxtblock~branch~source~sourcePubKey~counter~fee~gas_limit:Gas.Arith.zero~storage_limit:Z.zero[]lettransactionctxtblock~branch~source?sourcePubKey~counter~amount~destination?(entrypoint=Entrypoint.default)?parameters~gas_limit~storage_limit~fee()=letparameters=Option.fold~some:Script.lazy_expr~none:Script.unit_parameterparametersinoperationsctxtblock~branch~source?sourcePubKey~counter~fee~gas_limit~storage_limit[Manager(Transaction{amount;parameters;destination;entrypoint})]letoriginationctxtblock~branch~source?sourcePubKey~counter~balance?delegatePubKey~script~gas_limit~storage_limit~fee()=operationsctxtblock~branch~source?sourcePubKey~counter~fee~gas_limit~storage_limit[Manager(Origination{delegate=delegatePubKey;script;credit=balance});]letdelegationctxtblock~branch~source?sourcePubKey~counter~feedelegate=operationsctxtblock~branch~source?sourcePubKey~counter~fee~gas_limit:Gas.Arith.zero~storage_limit:Z.zero[Manager(Delegationdelegate)]endletoperationctxtblock~branchoperation=RPC_context.make_call0S.operationsctxtblock()({branch},Contents_list(Singleoperation))letendorsementctxtb~branch~consensus_content()=operationctxtb~branch(Endorsementconsensus_content)letproposalsctxtb~branch~source~period~proposals()=operationctxtb~branch(Proposals{source;period;proposals})letballotctxtb~branch~source~period~proposal~ballot()=operationctxtb~branch(Ballot{source;period;proposal;ballot})letfailing_noopctxtb~branch~message()=operationctxtb~branch(Failing_noopmessage)letseed_nonce_revelationctxtblock~branch~level~nonce()=operationctxtblock~branch(Seed_nonce_revelation{level;nonce})letvdf_revelationctxtblock~branch~solution()=operationctxtblock~branch(Vdf_revelation{solution})letdouble_baking_evidencectxtblock~branch~bh1~bh2()=operationctxtblock~branch(Double_baking_evidence{bh1;bh2})letdouble_endorsement_evidencectxtblock~branch~op1~op2()=operationctxtblock~branch(Double_endorsement_evidence{op1;op2})letdouble_preendorsement_evidencectxtblock~branch~op1~op2()=operationctxtblock~branch(Double_preendorsement_evidence{op1;op2})letempty_proof_of_work_nonce=Bytes.makeConstants_repr.proof_of_work_nonce_size'\000'letprotocol_datactxtblock?(payload_hash=Block_payload_hash.zero)?(payload_round=Round.zero)?seed_nonce_hash?(proof_of_work_nonce=empty_proof_of_work_nonce)~liquidity_baking_toggle_vote()=RPC_context.make_call0S.protocol_datactxtblock()(payload_hash,payload_round,seed_nonce_hash,proof_of_work_nonce,liquidity_baking_toggle_vote)endmoduleParse=structmoduleS=structopenData_encodingletpath=RPC_path.(path/"parse")letoperations=RPC_service.post_service~description:"Parse operations"~query:RPC_query.empty~input:(obj2(req"operations"(list(dynamic_sizeOperation.raw_encoding)))(opt"check_signature"bool))~output:(list(dynamic_sizeOperation.encoding))RPC_path.(path/"operations")letblock=RPC_service.post_service~description:"Parse a block"~query:RPC_query.empty~input:Block_header.raw_encoding~output:Block_header.protocol_data_encodingRPC_path.(path/"block")endletparse_protocol_dataprotocol_data=matchData_encoding.Binary.of_bytes_optBlock_header.protocol_data_encodingprotocol_datawith|None->Stdlib.failwith"Cant_parse_protocol_data"|Someprotocol_data->protocol_dataletregister()=Registration.register0~chunked:trueS.operations(fun_ctxt()(operations,check)->List.map_es(funraw->parse_operationraw>>?=funop->(matchcheckwith|Sometrue->return_unit(* FIXME *)(* I.check_signature ctxt *)(* op.protocol_data.signature op.shell op.protocol_data.contents *)|Somefalse|None->return_unit)>|=?fun()->op)operations);Registration.register0_noctxt~chunked:falseS.block(fun()raw_block->return@@parse_protocol_dataraw_block.protocol_data)letoperationsctxtblock?checkoperations=RPC_context.make_call0S.operationsctxtblock()(operations,check)letblockctxtblockshellprotocol_data=RPC_context.make_call0S.blockctxtblock()({shell;protocol_data}:Block_header.raw)end(* Compute the estimated starting time of a [round] at a future
[level], given the head's level [current_level], timestamp
[current_timestamp], and round [current_round]. Assumes blocks at
intermediate levels are produced at round 0. *)letestimated_timeround_durations~current_level~current_round~current_timestamp~level~round=ifLevel.(level<=current_level)thenResult.return_noneelseRound.timestamp_of_roundround_durations~round~predecessor_timestamp:current_timestamp~predecessor_round:current_round>>?funround_start_at_next_level->letstep=Round.round_durationround_durationsRound.zeroinletdiff=Level.difflevelcurrent_levelinPeriod.mult(Int32.preddiff)step>>?fundelay->Timestamp.(round_start_at_next_level+?delay)>>?funtimestamp->Result.return_sometimestampletrequested_levels~default_levelctxtcycleslevels=match(levels,cycles)with|[],[]->[default_level]|levels,cycles->(* explicitly fail when requested levels or cycle are in the past...
or too far in the future...
TODO: https://gitlab.com/tezos/tezos/-/issues/2335
this old comment (from version Alpha) conflicts with
the specification of the RPCs that use this code.
*)List.sort_uniqLevel.compare(List.rev_append(List.rev_map(Level.from_rawctxt)levels)(List.concat_map(Level.levels_in_cyclectxt)cycles))moduleBaking_rights=structtypet={level:Raw_level.t;delegate:public_key_hash;consensus_key:public_key_hash;round:Round.t;timestamp:Timestamp.toption;}letencoding=letopenData_encodinginconv(fun{level;delegate;consensus_key;round;timestamp}->(level,delegate,round,timestamp,consensus_key))(fun(level,delegate,round,timestamp,consensus_key)->{level;delegate;consensus_key;round;timestamp})(obj5(req"level"Raw_level.encoding)(req"delegate"Tezos_crypto.Signature.Public_key_hash.encoding)(req"round"Round.encoding)(opt"estimated_time"Timestamp.encoding)(req"consensus_key"Tezos_crypto.Signature.Public_key_hash.encoding))letdefault_max_round=64moduleS=structopenData_encodingletpath=RPC_path.(open_root/"helpers"/"baking_rights")typebaking_rights_query={levels:Raw_level.tlist;cycle:Cycle.toption;delegates:Tezos_crypto.Signature.Public_key_hash.tlist;consensus_keys:Tezos_crypto.Signature.Public_key_hash.tlist;max_round:intoption;all:bool;}letbaking_rights_query=letopenRPC_queryinquery(funlevelscycledelegatesconsensus_keysmax_roundall->{levels;cycle;delegates;consensus_keys;max_round;all})|+multi_field"level"Raw_level.rpc_arg(funt->t.levels)|+opt_field"cycle"Cycle.rpc_arg(funt->t.cycle)|+multi_field"delegate"Signature.Public_key_hash.rpc_arg(funt->t.delegates)|+multi_field"consensus_key"Signature.Public_key_hash.rpc_arg(funt->t.consensus_keys)|+opt_field"max_round"RPC_arg.uint(funt->t.max_round)|+flag"all"(funt->t.all)|>sealletbaking_rights=RPC_service.get_service~description:(Format.sprintf"Retrieves the list of delegates allowed to bake a block.\n\
By default, it gives the best baking opportunities (in terms of \
rounds) for bakers that have at least one opportunity below the \
%dth round for the next block.\n\
Parameters `level` and `cycle` can be used to specify the \
(valid) level(s) in the past or future at which the baking \
rights have to be returned.\n\
Parameter `delegate` can be used to restrict the results to the \
given delegates. Parameter `consensus_key` can be used to \
restrict the results to the given consensus_keys. If parameter \
`all` is set, all the baking opportunities for each baker at \
each level are returned, instead of just the first one.\n\
Returns the list of baking opportunities up to round %d. Also \
returns the minimal timestamps that correspond to these \
opportunities. The timestamps are omitted for levels in the \
past, and are only estimates for levels higher that the next \
block's, based on the hypothesis that all predecessor blocks \
were baked at the first round."default_max_rounddefault_max_round)~query:baking_rights_query~output:(listencoding)pathendletbaking_rights_at_levelctxtmax_roundlevel=Round.getctxt>>=?funcurrent_round->letcurrent_level=Level.currentctxtinletcurrent_timestamp=Timestamp.currentctxtinletround_durations=Alpha_context.Constants.round_durationsctxtinletrecloopctxtaccround=ifRound.(round>max_round)then(* returns the ctxt with an updated cache of slot holders *)return(ctxt,List.revacc)elseStake_distribution.baking_rights_ownerctxtlevel~round>>=?fun(ctxt,_slot,{Consensus_key.consensus_pkh;delegate;consensus_pk=_})->estimated_timeround_durations~current_level~current_round~current_timestamp~level~round>>?=funtimestamp->letacc={level=level.level;delegate;consensus_key=consensus_pkh;round;timestamp;}::accinloopctxtacc(Round.succround)inloopctxt[]Round.zeroletremove_duplicated_delegatesrights=List.rev@@fst@@List.fold_left(fun(acc,previous)r->ifTezos_crypto.Signature.Public_key_hash.Set.exists(Tezos_crypto.Signature.Public_key_hash.equalr.delegate)previousthen(acc,previous)else(r::acc,Tezos_crypto.Signature.Public_key_hash.Set.addr.delegateprevious))([],Tezos_crypto.Signature.Public_key_hash.Set.empty)rightsletregister()=Registration.register0~chunked:trueS.baking_rights(functxtq()->letcycles=matchq.cyclewithNone->[]|Somecycle->[cycle]inletlevels=requested_levels~default_level:(Level.succctxt(Level.currentctxt))ctxtcyclesq.levelsinRound.of_int(matchq.max_roundwith|None->default_max_round|Somemax_round->Compare.Int.minmax_round(Constants.consensus_committee_sizectxt))>>?=funmax_round->List.fold_left_map_es(functxtl->baking_rights_at_levelctxtmax_roundl)ctxtlevels>|=?fun(_ctxt,rights)->letrights=ifq.allthenList.concatrightselseList.concat_mapremove_duplicated_delegatesrightsinletrights=matchq.delegateswith|[]->rights|_::_asdelegates->letis_requestedp=List.exists(Tezos_crypto.Signature.Public_key_hash.equalp.delegate)delegatesinList.filteris_requestedrightsinletrights=matchq.consensus_keyswith|[]->rights|_::_asdelegates->letis_requestedp=List.exists(Tezos_crypto.Signature.Public_key_hash.equalp.consensus_key)delegatesinList.filteris_requestedrightsinrights)letgetctxt?(levels=[])?cycle?(delegates=[])?(consensus_keys=[])?(all=false)?max_roundblock=RPC_context.make_call0S.baking_rightsctxtblock{levels;cycle;delegates;consensus_keys;max_round;all}()endmoduleEndorsing_rights=structtypedelegate_rights={delegate:Tezos_crypto.Signature.Public_key_hash.t;consensus_key:Tezos_crypto.Signature.Public_key_hash.t;first_slot:Slot.t;endorsing_power:int;}typet={level:Raw_level.t;delegates_rights:delegate_rightslist;estimated_time:Time.toption;}letdelegate_rights_encoding=letopenData_encodinginconv(fun{delegate;consensus_key;first_slot;endorsing_power}->(delegate,first_slot,endorsing_power,consensus_key))(fun(delegate,first_slot,endorsing_power,consensus_key)->{delegate;first_slot;endorsing_power;consensus_key})(obj4(req"delegate"Tezos_crypto.Signature.Public_key_hash.encoding)(req"first_slot"Slot.encoding)(req"endorsing_power"uint16)(req"consensus_key"Tezos_crypto.Signature.Public_key_hash.encoding))letencoding=letopenData_encodinginconv(fun{level;delegates_rights;estimated_time}->(level,delegates_rights,estimated_time))(fun(level,delegates_rights,estimated_time)->{level;delegates_rights;estimated_time})(obj3(req"level"Raw_level.encoding)(req"delegates"(listdelegate_rights_encoding))(opt"estimated_time"Timestamp.encoding))moduleS=structopenData_encodingletpath=RPC_path.(path/"endorsing_rights")typeendorsing_rights_query={levels:Raw_level.tlist;cycle:Cycle.toption;delegates:Tezos_crypto.Signature.Public_key_hash.tlist;consensus_keys:Tezos_crypto.Signature.Public_key_hash.tlist;}letendorsing_rights_query=letopenRPC_queryinquery(funlevelscycledelegatesconsensus_keys->{levels;cycle;delegates;consensus_keys})|+multi_field"level"Raw_level.rpc_arg(funt->t.levels)|+opt_field"cycle"Cycle.rpc_arg(funt->t.cycle)|+multi_field"delegate"Signature.Public_key_hash.rpc_arg(funt->t.delegates)|+multi_field"consensus_key"Signature.Public_key_hash.rpc_arg(funt->t.consensus_keys)|>sealletendorsing_rights=RPC_service.get_service~description:"Retrieves the delegates allowed to endorse a block.\n\
By default, it gives the endorsing power for delegates that have at \
least one endorsing slot for the next block.\n\
Parameters `level` and `cycle` can be used to specify the (valid) \
level(s) in the past or future at which the endorsing rights have \
to be returned. Parameter `delegate` can be used to restrict the \
results to the given delegates.\n\
Parameter `consensus_key` can be used to restrict the results to \
the given consensus_keys. \n\
Returns the smallest endorsing slots and the endorsing power. Also \
returns the minimal timestamp that corresponds to endorsing at the \
given level. The timestamps are omitted for levels in the past, and \
are only estimates for levels higher that the next block's, based \
on the hypothesis that all predecessor blocks were baked at the \
first round."~query:endorsing_rights_query~output:(listencoding)pathendletendorsing_rights_at_levelctxtlevel=Baking.endorsing_rights_by_first_slotctxtlevel>>=?fun(ctxt,rights)->Round.getctxt>>=?funcurrent_round->letcurrent_level=Level.currentctxtinletcurrent_timestamp=Timestamp.currentctxtinletround_durations=Alpha_context.Constants.round_durationsctxtinestimated_timeround_durations~current_level~current_round~current_timestamp~level~round:Round.zero>>?=funestimated_time->letrights=Slot.Map.fold(funfirst_slot({Consensus_key.delegate;consensus_pk=_;consensus_pkh=consensus_key;},endorsing_power)acc->{delegate;consensus_key;first_slot;endorsing_power}::acc)rights[]in(* returns the ctxt with an updated cache of slot holders *)return(ctxt,{level=level.level;delegates_rights=rights;estimated_time})letregister()=Registration.register0~chunked:trueS.endorsing_rights(functxtq()->letcycles=matchq.cyclewithNone->[]|Somecycle->[cycle]inletlevels=requested_levels~default_level:(Level.currentctxt)ctxtcyclesq.levelsinList.fold_left_map_esendorsing_rights_at_levelctxtlevels>|=?fun(_ctxt,rights_per_level)->letrights_per_level=match(q.consensus_keys,q.delegates)with|[],[]->rights_per_level|_,_->letis_requestedp=List.exists(Tezos_crypto.Signature.Public_key_hash.equalp.consensus_key)q.consensus_keys||List.exists(Tezos_crypto.Signature.Public_key_hash.equalp.delegate)q.delegatesinList.filter_map(funrights_at_level->matchList.filteris_requestedrights_at_level.delegates_rightswith|[]->None|delegates_rights->Some{rights_at_levelwithdelegates_rights})rights_per_levelinrights_per_level)letgetctxt?(levels=[])?cycle?(delegates=[])?(consensus_keys=[])block=RPC_context.make_call0S.endorsing_rightsctxtblock{levels;cycle;delegates;consensus_keys}()endmoduleValidators=structtypet={level:Raw_level.t;delegate:Tezos_crypto.Signature.Public_key_hash.t;consensus_key:Tezos_crypto.Signature.public_key_hash;slots:Slot.tlist;}letencoding=letopenData_encodinginconv(fun{level;delegate;consensus_key;slots}->(level,delegate,slots,consensus_key))(fun(level,delegate,slots,consensus_key)->{level;delegate;consensus_key;slots})(obj4(req"level"Raw_level.encoding)(req"delegate"Tezos_crypto.Signature.Public_key_hash.encoding)(req"slots"(listSlot.encoding))(req"consensus_key"Tezos_crypto.Signature.Public_key_hash.encoding))moduleS=structopenData_encodingletpath=RPC_path.(path/"validators")typevalidators_query={levels:Raw_level.tlist;delegates:Tezos_crypto.Signature.Public_key_hash.tlist;consensus_keys:Tezos_crypto.Signature.Public_key_hash.tlist;}letvalidators_query=letopenRPC_queryinquery(funlevelsdelegatesconsensus_keys->{levels;delegates;consensus_keys})|+multi_field"level"Raw_level.rpc_arg(funt->t.levels)|+multi_field"delegate"Signature.Public_key_hash.rpc_arg(funt->t.delegates)|+multi_field"consensus_key"Signature.Public_key_hash.rpc_arg(funt->t.consensus_keys)|>sealletvalidators=RPC_service.get_service~description:"Retrieves the level, the endorsement slots and the public key hash \
of each delegate allowed to endorse a block.\n\
By default, it provides this information for the next level.\n\
Parameter `level` can be used to specify the (valid) level(s) in \
the past or future at which the endorsement rights have to be \
returned. Parameter `delegate` can be used to restrict the results \
results to the given delegates. Parameter `consensus_key` can be \
used to restrict the results to the given consensus_keys.\n"~query:validators_query~output:(listencoding)pathendletadd_endorsing_slots_at_level(ctxt,acc)level=Baking.endorsing_rightsctxtlevel>|=?fun(ctxt,rights)->(ctxt,Signature.Public_key_hash.Map.fold(fun_pkh{Baking.delegate;consensus_key;slots}acc->{level=level.level;delegate;consensus_key;slots}::acc)rightsacc)letregister()=Registration.register0~chunked:trueS.validators(functxtq()->letlevels=requested_levels~default_level:(Level.currentctxt)ctxt[]q.levelsinList.fold_left_esadd_endorsing_slots_at_level(ctxt,[])(List.revlevels)>|=?fun(_ctxt,rights)->letrights=matchq.delegateswith|[]->rights|_::_asdelegates->letis_requestedp=List.exists(Tezos_crypto.Signature.Public_key_hash.equalp.delegate)delegatesinList.filteris_requestedrightsinletrights=matchq.consensus_keyswith|[]->rights|_::_asdelegates->letis_requestedp=List.exists(Tezos_crypto.Signature.Public_key_hash.equalp.consensus_key)delegatesinList.filteris_requestedrightsinrights)letgetctxt?(levels=[])?(delegates=[])?(consensus_keys=[])block=RPC_context.make_call0S.validatorsctxtblock{levels;delegates;consensus_keys}()endmoduleS=structopenData_encodingtypelevel_query={offset:int32}letlevel_query:level_queryRPC_query.t=letopenRPC_queryinquery(funoffset->{offset})|+field"offset"RPC_arg.int320l(funt->t.offset)|>sealletcurrent_level=RPC_service.get_service~description:"Returns the level of the interrogated block, or the one of a block \
located `offset` blocks after it in the chain. For instance, the next \
block if `offset` is 1. The offset cannot be negative."~query:level_query~output:Level.encodingRPC_path.(path/"current_level")letlevels_in_current_cycle=RPC_service.get_service~description:"Levels of a cycle"~query:level_query~output:(obj2(req"first"Raw_level.encoding)(req"last"Raw_level.encoding))RPC_path.(path/"levels_in_current_cycle")letround=RPC_service.get_service~description:"Returns the round of the interrogated block, or the one of a block \
located `offset` blocks after in the chain (or before when negative). \
For instance, the next block if `offset` is 1."~query:RPC_query.empty~output:Round.encodingRPC_path.(path/"round")endtypeEnvironment.Error_monad.error+=Negative_level_offsetlet()=Environment.Error_monad.register_error_kind`Permanent~id:"negative_level_offset"~title:"The specified level offset is negative"~description:"The specified level offset is negative"~pp:(funppf()->Format.fprintfppf"The specified level offset should be positive.")Data_encoding.unit(functionNegative_level_offset->Some()|_->None)(fun()->Negative_level_offset)letregister()=Scripts.register();Forge.register();Parse.register();Contract.register();Big_map.register();Baking_rights.register();Endorsing_rights.register();Validators.register();Sc_rollup.register();Dal.register();Tx_rollup.register();Registration.register0~chunked:falseS.current_level(functxtq()->ifq.offset<0lthentzfailNegative_level_offsetelseLwt.return(Level.from_raw_with_offsetctxt~offset:q.offset(Level.currentctxt).level));Registration.opt_register0~chunked:trueS.levels_in_current_cycle(functxtq()->letrev_levels=Level.levels_in_current_cyclectxt~offset:q.offset()inmatchrev_levelswith|[]->return_none|[level]->return(Some(level.level,level.level))|last::default_first::rest->(* The [rev_levels] list is reversed, the last level is the head *)letfirst=List.lastdefault_firstrestinreturn(Some(first.level,last.level)));Registration.register0~chunked:falseS.round(functxt()()->Round.getctxt)letcurrent_levelctxt?(offset=0l)block=RPC_context.make_call0S.current_levelctxtblock{offset}()letlevels_in_current_cyclectxt?(offset=0l)block=RPC_context.make_call0S.levels_in_current_cyclectxtblock{offset}()letrpc_services=register();RPC_directory.mergerpc_services!Registration.patched_services