12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755(*****************************************************************************)(* *)(* 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))letstack_encoding=list(obj2(req"type"Script.expr_encoding)(req"val"Script.expr_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))letnormalize_stack_input_encoding=obj3(req"input"stack_encoding)(req"unparsing_mode"unparsing_mode_encoding)(opt"legacy"bool)letnormalize_stack_output_encoding=obj1(req"output"stack_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_stack=RPC_service.post_service~description:"Normalize a Michelson stack using the requested unparsing mode"~query:RPC_query.empty~input:normalize_stack_input_encoding~output:normalize_stack_output_encodingRPC_path.(path/"normalize_stack")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)|Or_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,[],[])endmoduleNormalize_stack=structtypeex_stack=|Ex_stack:('a,'s)Script_typed_ir.stack_ty*'a*'s->ex_stackletrecparse_stack:context->legacy:bool->(Script.node*Script.node)list->(ex_stack*context)tzresultLwt.t=functxt~legacyl->matchlwith|[]->return(Ex_stack(Bot_t,EmptyCell,EmptyCell),ctxt)|(ty_node,data_node)::l->Lwt.return@@Script_ir_translator.parse_tyctxt~legacy~allow_lazy_storage:true~allow_operation:true~allow_contract:true~allow_ticket:truety_node>>=?fun(Ex_tyty,ctxt)->letelab_conf=elab_conf~legacy()inScript_ir_translator.parse_datactxt~elab_conf~allow_forged:truetydata_node>>=?fun(x,ctxt)->parse_stackctxt~legacyl>>=?fun(Ex_stack(sty,y,st),ctxt)->return(Ex_stack(Item_t(ty,sty),x,(y,st)),ctxt)letrecunparse_stack:typeas.context->Script_ir_unparser.unparsing_mode->(a,s)Script_typed_ir.stack_ty->a->s->((Script.expr*Script.expr)list*context)tzresultLwt.t=letloc=Micheline.dummy_locationinfunctxtunparsing_modestyxst->match(sty,x,st)with|Bot_t,EmptyCell,EmptyCell->return([],ctxt)|Item_t(ty,sty),x,(y,st)->Script_ir_unparser.unparse_ty~locctxtty>>?=fun(ty_node,ctxt)->Script_ir_translator.unparse_datactxtunparsing_modetyx>>=?fun(data_node,ctxt)->unparse_stackctxtunparsing_modestyyst>>=?fun(l,ctxt)->return((Micheline.strip_locationsty_node,data_node)::l,ctxt)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"|IPush_->pp_print_stringfmt"PUSH"|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->letapplication_mode=Apply.Partial_construction{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: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,Signature.Public_key_hash.zero)|Somec,None->(c,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_stack(functxt()(stack,unparsing_mode,legacy)->letlegacy=Option.value~default:falselegacyinletctxt=Gas.set_unlimitedctxtinletnodes=List.map(fun(a,b)->(Micheline.roota,Micheline.rootb))stackinNormalize_stack.parse_stackctxt~legacynodes>>=?fun(Normalize_stack.Ex_stack(st_ty,x,st),ctxt)->Normalize_stack.unparse_stackctxtunparsing_modest_tyxst>|=?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_stack?legacy~stack~unparsing_modectxtblock=RPC_context.make_call0S.normalize_stackctxtblock()(stack,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_commitmentcontextrollupinmatchreswith|Ok(_context,_cemented_commitment,cemented_commitment_hash)whenSc_rollup.Commitment.Hash.equalcommitment_hashcemented_commitment_hash->return_true|Ok_|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 (the default is the \
current 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()()letdal_shardsctxtblock?level()=RPC_context.make_call0S.shardsctxtblocklevel()letregister_shards()=Registration.register0~chunked:trueS.shards@@functxtlevel()->letlevel=Option.valuelevel~default:(Level.currentctxt).levelinDal_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"Signature.Public_key_hash.encoding)(req"round"Round.encoding)(opt"estimated_time"Timestamp.encoding)(req"consensus_key"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:Signature.Public_key_hash.tlist;consensus_keys: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->ifSignature.Public_key_hash.Set.exists(Signature.Public_key_hash.equalr.delegate)previousthen(acc,previous)else(r::acc,Signature.Public_key_hash.Set.addr.delegateprevious))([],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(Signature.Public_key_hash.equalp.delegate)delegatesinList.filteris_requestedrightsinletrights=matchq.consensus_keyswith|[]->rights|_::_asdelegates->letis_requestedp=List.exists(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}()endmoduleAttestation_rights=structtypedelegate_rights={delegate:Signature.Public_key_hash.t;consensus_key:Signature.Public_key_hash.t;first_slot:Slot.t;attestation_power:int;}typet={level:Raw_level.t;delegates_rights:delegate_rightslist;estimated_time:Time.toption;}letdelegate_rights_encodinguse_endorsement=letopenData_encodinginconv(fun{delegate;consensus_key;first_slot;attestation_power}->(delegate,first_slot,attestation_power,consensus_key))(fun(delegate,first_slot,attestation_power,consensus_key)->{delegate;first_slot;attestation_power;consensus_key})(obj4(req"delegate"Signature.Public_key_hash.encoding)(req"first_slot"Slot.encoding)(req(ifuse_endorsementthen"endorsing_power"else"attestation_power")uint16)(req"consensus_key"Signature.Public_key_hash.encoding))letencoding~use_endorsement=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"(list(delegate_rights_encodinguse_endorsement)))(opt"estimated_time"Timestamp.encoding))moduleS=structopenData_encodingletattestation_path=RPC_path.(path/"attestation_rights")letendorsing_path=RPC_path.(path/"endorsing_rights")typeattestation_rights_query={levels:Raw_level.tlist;cycle:Cycle.toption;delegates:Signature.Public_key_hash.tlist;consensus_keys:Signature.Public_key_hash.tlist;}letattestation_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)|>sealletattestation_rights=RPC_service.get_service~description:"Retrieves the delegates allowed to attest a block.\n\
By default, it gives the attestation power for delegates that have \
at least one attestation 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 attestation 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 attestation slots and the attestation power. \
Also returns the minimal timestamp that corresponds to attestation \
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:attestation_rights_query~output:(list(encoding~use_endorsement:false))attestation_path(* TODO: https://gitlab.com/tezos/tezos/-/issues/5156
endorsing_rights RPC should be removed once the depreciation period
will be over *)letendorsing_rights=RPC_service.get_service~description:"Deprecated: use `attestation_rights` instead.\n\
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:attestation_rights_query~output:(list(encoding~use_endorsement:true))endorsing_pathendletattestation_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;},attestation_power)acc->{delegate;consensus_key;first_slot;attestation_power}::acc)rights[]in(* returns the ctxt with an updated cache of slot holders *)return(ctxt,{level=level.level;delegates_rights=rights;estimated_time})letget_attestation_rightsctxt(q:S.attestation_rights_query)=letcycles=matchq.cyclewithNone->[]|Somecycle->[cycle]inletlevels=requested_levels~default_level:(Level.currentctxt)ctxtcyclesq.levelsinList.fold_left_map_esattestation_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(Signature.Public_key_hash.equalp.consensus_key)q.consensus_keys||List.exists(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_levelletregister()=Registration.register0~chunked:trueS.attestation_rights(functxtq()->get_attestation_rightsctxtq);Registration.register0~chunked:trueS.endorsing_rights(functxtq()->get_attestation_rightsctxtq)letgetctxt?(levels=[])?cycle?(delegates=[])?(consensus_keys=[])block=RPC_context.make_call0S.attestation_rightsctxtblock{levels;cycle;delegates;consensus_keys}()endmoduleValidators=structtypet={level:Raw_level.t;delegate:Signature.Public_key_hash.t;consensus_key: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"Signature.Public_key_hash.encoding)(req"slots"(listSlot.encoding))(req"consensus_key"Signature.Public_key_hash.encoding))moduleS=structopenData_encodingletpath=RPC_path.(path/"validators")typevalidators_query={levels:Raw_level.tlist;delegates:Signature.Public_key_hash.tlist;consensus_keys: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(Signature.Public_key_hash.equalp.delegate)delegatesinList.filteris_requestedrightsinletrights=matchq.consensus_keyswith|[]->rights|_::_asdelegates->letis_requestedp=List.exists(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();Attestation_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