std:EVM/Contract

lib/EVM/Contract.omg

lib/EVM/Contract.omg2241 lines
1{- Contracts with modifiers carried by typed handler constructors.
2
3   The declaration is an existential package: it exposes neither editable
4   mutability metadata nor a raw executable entry. The compiler supplies its
5   consumer after the handlers have been constructed, so a handler cannot
6   capture that consumer's unrestricted EVM operations.
7-}
8let O = std:EVM/Operations
9let E = std:EVM/Effect
10let S = std:EVM/Signature
11let Runtime = std:EVM/Runtime
12let Solidity = std:EVM/Solidity
13let Base = std:EVM/Base
14let Codec = std:EVM/Native/Codec
15let Storage = std:EVM/State
16let Layout = std:EVM/State/Layout
17let Owners = std:EVM/State/Owners
18let Certificate = std:Certificate
19let Immutable = std:EVM/Immutable
20let Allocate = std:Region/Allocate
21let Eq = std:Equal
22let L = std:List
23let Word256 = Word 256
24let Outcome = std:Result.Result
25-- Logical invocation data has no access to storage, raw calldata, mutable
26-- return buffers or physical code identities. Addresses retain their width.
27let Context = { caller : Word 160, address : Word 160, value : Word256, timestamp : Word256 }
28let ReadCalls =
29      \(m : Type -> Type) ->
30        { invoke : forall (A B : Type) -> Runtime.Boundary -> Word 160 -> A -> m B
31        , optional : forall (A B : Type) -> Runtime.Boundary -> Word 160 -> A -> m (Optional B)
32        , attempt : forall (E A B : Type) -> Runtime.Boundary -> Word 160 -> A -> m (Outcome E B)
33        }
34let Guard = \(m : Type -> Type) -> { run : forall (A : Type) -> Word256 -> m A -> m A }
35let WriteCalls =
36      \(m : Type -> Type) ->
37        { transfer : Word 160 -> Word256 -> m unit
38        , invoke : forall (A B : Type) -> Runtime.Boundary -> Word 160 -> Word256 -> A -> m B
39        , optional :
40            forall (A B : Type) -> Runtime.Boundary -> Word 160 -> Word256 -> A -> m (Optional B)
41        , attempt :
42            forall (E A B : Type) -> Runtime.Boundary -> Word 160 -> Word256 -> A -> m (Outcome E B)
43        }
44-- A declaration is a record of typed method references; field selection
45-- checks the method name and preserves its argument, result and error types.
46let Method =
47      \(Errors Args Result : Type) ->
48        forall (Call : Type -> Type -> Type -> Type)
49        -> (Runtime.Boundary -> Call Errors Args Result)
50        -> Call Errors Args Result
51let native =
52      \{Errors : Solidity.Families -> Type}
53       {H : Solidity.Families -> Type}
54       (types :
55         { Errors : Reflect Solidity.types Errors
56         , Messages : Reflect @1 Solidity.types H
57         })
58       {messagesValid : Solidity.InterfaceValid @H types.Messages} ->
59        (Solidity.interface @H types.Messages @messagesValid).2.tabulateHandlers
60          Solidity.values
61          (Method (Errors Solidity.values))
62          (\A B name position args result ->
63             ((\R consume -> consume (Runtime.Boundary.Native name)) :
64                Method (Errors Solidity.values) (A Solidity.values) (B Solidity.values)))
65let nativeIn =
66      \(owner : Text)
67       {Errors : Solidity.Families -> Type}
68       {H : Solidity.Families -> Type}
69       (types :
70         { Errors : Reflect Solidity.types Errors
71         , Messages : Reflect @1 Solidity.types H
72         })
73       {messagesValid : Solidity.InterfaceValid @H types.Messages} ->
74        (Solidity.interface @H types.Messages @messagesValid).2.tabulateHandlers
75          Solidity.values
76          (Method (Errors Solidity.values))
77          (\A B name position args result ->
78             ((\R consume -> consume (Runtime.Boundary.NativeIn { owner, name })) :
79                Method (Errors Solidity.values) (A Solidity.values) (B Solidity.values)))
80
81let solidity =
82      \{Errors : Solidity.Families -> Type}
83       {H : Solidity.Families -> Type}
84       (types :
85         { Errors : Reflect Solidity.types Errors
86         , Messages : Reflect @1 Solidity.types H
87         })
88       {messagesValid : Solidity.InterfaceValid @H types.Messages} ->
89        (Solidity.interface @H types.Messages @messagesValid).2.tabulateHandlers
90          Solidity.values
91          (Method (Errors Solidity.values))
92          (\A B name position args result ->
93             ((\R consume ->
94                 consume
95                   (Runtime.Boundary.Solidity
96                      { name
97                      , arguments = Solidity.describe args
98                      , result = Solidity.describe result
99                      , errors = Solidity.describe types.Errors
100                      })) :
101                Method (Errors Solidity.values) (A Solidity.values) (B Solidity.values)))
102let AccessBase =
103      \(Events Errors State : Type)
104       (kind : E.Mode)
105       (extra : (Type -> Type) -> Row Type)
106       (m : Type -> Type) ->
107        let mutable =
108              (| context : Context
109              , readState : Storage.Read State m
110              , writeState : Storage.Write State m
111              , readCalls : ReadCalls m
112              , writeCalls : WriteCalls m
113              , guard : Guard m
114              , signals : { emit : Events -> m unit }
115              , ...extra m
116              |)
117        let required =
118              merge
119                { Pure = extra m
120                , View =
121                    (| context : Context
122                    , readState : Storage.Read State m
123                    , readCalls : ReadCalls m
124                    , ...extra m
125                    |)
126                , Write = mutable
127                , Payable = mutable
128                }
129                kind
130        in  { reject : forall (A : Type) -> Errors -> m A, ...required }
131let Access =
132      \(Events Errors State Imm : Type) (kind : E.Mode) (extra : (Type -> Type) -> Row Type) ->
133        AccessBase
134          Events
135          Errors
136          State
137          kind
138          (\m ->
139             merge
140               { Pure = extra m
141               , View = (| immutable : Imm, ...extra m |)
142               , Write = (| immutable : Imm, ...extra m |)
143               , Payable = (| immutable : Imm, ...extra m |)
144               }
145               kind)
146let BaseAction =
147      \(Events Errors State : Type) kind ->
148        E.ActionFor (AccessBase Events Errors State kind) Word256 Bool
149-- An individual operation asks only for the fields it uses. This keeps
150-- unrelated state/configuration types out of inference and admits the action
151-- in any handler whose capability row contains those fields.
152let Capability =
153      \(required : ((Type -> Type) -> Row Type) -> (Type -> Type) -> Type) (A : Type) ->
154        E.ActionFor required Word256 Bool A
155let Action =
156      \(Events Errors State Imm : Type) kind ->
157        E.ActionFor (Access Events Errors State Imm kind) Word256 Bool
158let Handler = \(Events Errors State Imm : Type) -> E.HandlerFor (Action Events Errors State Imm)
159let Constructor =
160      \(Events Errors State Imm A : Type) -> A -> Action Events Errors State unit E.Mode.Write Imm
161-- Boundary witnesses keep the decoded and encoded source type in their
162-- operations. Only the trusted lowerer receives the unrestricted runtime.
163let Description = forall (R : Type) -> (forall (A : Type) -> R) -> R
164let describe : Type -> Description = \A R consume -> consume A
165let ValueBoundary = O.ValueBoundary
166let nativeCodec = O.nativeCodec
167let solidityCodec = O.solidityCodec
168let Encoding =
169      \(A : Type) ->
170        { wire : Runtime.Wire
171        , read : forall (Code : Type) -> Runtime.Ops Code -> Natural -> (A -> Code) -> Code
172        , write : forall (Code : Type) -> Runtime.Ops Code -> A -> Code
173        , problems : List Text
174        }
175-- The encodings state their types: the kernel reads a type it infers back in
176-- normal form, which spells out the validity predicate inside each
177-- `Layout.Selection` of the storage operations of `Runtime.Ops`. Inferred,
178-- they cost the library check 14.2 GB instead of 10.0 GB (`type -e 'let C =
179-- std:EVM/Contract in 0'`, 2026-11-19).
180let solidityEncoding
181    : forall {A : Solidity.Families -> Type}
182      -> Reflect Solidity.types A
183      -> Encoding (A Solidity.values)
184    = \{A} d ->
185        let wire = Solidity.describe d
186        in  ({ wire = Runtime.Wire.Solidity wire
187             , read =
188                 \Code raw offset ->
189                   raw.readSolidity (A Solidity.values) wire (Word/fromNatural 256 offset)
190             , write = \Code raw -> raw.outputSolidity (A Solidity.values) wire
191             , problems = []
192             } :
193               Encoding (A Solidity.values))
194let nativeEncoding
195    : forall {A : Solidity.Families -> Type}
196      -> Reflect Solidity.types A
197      -> Encoding (A Solidity.values)
198    = \{A} d ->
199        ({ wire = Runtime.Wire.Native
200         , read = \Code raw offset -> Codec.decode d Code raw (offset * 8)
201         , write = Codec.encode d
202         , problems = Codec.problems d
203         } :
204           Encoding (A Solidity.values))
205let encoding
206    : forall {A : Type} -> ValueBoundary A -> Encoding A
207    = \{A} boundary ->
208        boundary Encoding (\P abi d -> if abi then solidityEncoding d else nativeEncoding d)
209-- A method's boundary witnesses are independent of its exposure. Native
210-- exposure erases optional ABI roles; Solidity exposure preserves those roles
211-- and the written parameter order. Both paths retain the actual source type.
212let encodingFor
213    : forall {A : Type} -> Bool -> ValueBoundary A -> Encoding A
214    = \{A} abi boundary ->
215        boundary Encoding (\P _ d -> if abi then solidityEncoding d else nativeEncoding d)
216let Signals = { events : Solidity.Description, errors : Solidity.Description, problems : List Text }
217let Names = O.Names
218let EntryKind = < Method | Receive | Fallback >
219-- Inside the route builder, the callable belongs to this label, both public
220-- names, mode and wire witnesses. The raw entry is not a public facet item.
221let Binding =
222      \(A B : Type) ->
223        { label : Text
224        , names : Names
225        , arguments : ValueBoundary A
226        , result : ValueBoundary B
227        , mode : E.Mode
228        }
229let Bound =
230      \(Events Errors State Imm A B : Type) (binding : Binding A B) ->
231        forall (args : A) (route : Binding A B)
232        -> route === binding
233        -> Action Events Errors State Imm binding.mode B
234-- One method with all its public names, a receive action or a fallback.
235let Entry =
236      \(Events Errors State Imm : Type) ->
237        forall (R : Type)
238        -> (forall (A B : Type) (binding : Binding A B)
239            -> Bound Events Errors State Imm A B binding
240            -> R)
241        -> (Action Events Errors State Imm E.Mode.Payable unit -> R)
242        -> (forall (B : Type) -> ValueBoundary B -> Handler Events Errors State Imm Word256 B -> R)
243        -> R
244let methodEntry =
245      \{Events Errors State Imm A B : Type}
246       (binding : Binding A B)
247       (body : A -> Action Events Errors State Imm binding.mode B) ->
248        ((\R method receive fallback -> method A B binding (\args route matches -> body args)) :
249           Entry Events Errors State Imm)
250-- The lowerer invokes the body at the binding supplied by its own entry.
251let handlerAt =
252      \{Events Errors State Imm : Type}
253       (A B : Type)
254       (binding : Binding A B)
255       (bound : Bound Events Errors State Imm A B binding) ->
256        let H = Handler Events Errors State Imm A B
257        let tag
258            : forall (mode : E.Mode) -> (A -> Action Events Errors State Imm mode B) -> H
259            = \mode ->
260                merge { Pure = H.Pure, View = H.View, Write = H.Write, Payable = H.Payable } mode
261        in  tag binding.mode (\args -> bound args binding refl)
262-- Interprets an entry once per public name: a method yields its native name
263-- first, then its Solidity name; receive and fallback yield one item.
264let interpretEntry
265    : forall {Events Errors State Imm : Type}
266      -> Entry Events Errors State Imm
267      -> forall (R : Type)
268      -> (forall (A B : Type)
269          -> EntryKind
270          -> Text
271          -> Encoding A
272          -> Encoding B
273          -> Handler Events Errors State Imm A B
274          -> R)
275      -> List R
276    = \{Events} {Errors} {State} {Imm} entry R consume ->
277        entry
278          (List R)
279          (\A B binding bound ->
280             let handler = handlerAt @Events @Errors @State @Imm A B binding bound
281             let on =
282                   \(abi : Bool) (name : Optional Text) ->
283                     Optional/elim
284                       (\(_ : Optional Text) -> List R)
285                       ([] : List R)
286                       (\(name : Text) ->
287                          [ consume
288                              A
289                              B
290                              EntryKind.Method
291                              name
292                              (encodingFor abi binding.arguments)
293                              (encodingFor abi binding.result)
294                              handler
295                          ])
296                       name
297             in  on False binding.names.native # on True binding.names.solidity)
298          (\action ->
299             let input
300                 : Encoding unit
301                 = { wire = Runtime.Wire.Solidity (Solidity.describe {})
302                   , problems = []
303                   , read = \Code raw offset next -> next {=}
304                   , write = \Code raw value -> raw.evm.ret []
305                   }
306             in  [ consume
307                     unit
308                     unit
309                     EntryKind.Receive
310                     ""
311                     input
312                     input
313                     ((Handler Events Errors State Imm unit unit).Payable (\_ -> action))
314                 ])
315          (\B result handler ->
316             let input
317                 : Encoding Word256
318                 = { wire = Runtime.Wire.Solidity (Solidity.describe Word256)
319                   , problems = []
320                   , read = \Code raw offset next -> next raw.evm.cdsize
321                   , write = \Code raw value -> raw.evm.ret [ { size = 32, word = value } ]
322                   }
323             in  [ consume Word256 B EntryKind.Fallback "" input (encodingFor True result) handler
324                 ])
325let qualify = \(owner name : Text) -> if Text/equal owner "" then name else owner ++ "." ++ name
326let kindOf =
327      \{Events Errors State Imm Args Result : Type}
328       (handler : Handler Events Errors State Imm Args Result) ->
329        merge
330          { Pure = \_ -> E.Mode.Pure
331          , View = \_ -> E.Mode.View
332          , Write = \_ -> E.Mode.Write
333          , Payable = \_ -> E.Mode.Payable
334          }
335          handler
336let isPayable =
337      \{Events Errors State Imm Args Result : Type}
338       (handler : Handler Events Errors State Imm Args Result) ->
339        merge
340          { Pure = \_ -> False, View = \_ -> False, Write = \_ -> False, Payable = \_ -> True }
341          handler
342
343-- Runs a handler on its arguments. `abi` selects the encoding of its events
344-- and errors; it may be known only at run time, in a body that both
345-- protocols enter. The caller checks the call value of a handler that is
346-- not payable, before it decodes the arguments.
347let run =
348      \{Events Errors State Imm Args Result : Type}
349       (abi : Bool)
350       (owner : Text)
351       (signals : Signals)
352       (selection : Layout.Selection State)
353       (immutable : Imm)
354       (Code : Type)
355       (raw : Runtime.Ops Code)
356       (handler : Handler Events Errors State Imm Args Result)
357       (args : Args) ->
358        let b = Base.cps (raw.evm // { words = S.nativeWords })
359        let m = Base.Cps Code
360        let c = E.control b
361        let context =
362              { caller = Word/fromNatural 160 (Word/toNatural b.frame.caller)
363              , address = Word/fromNatural 160 (Word/toNatural b.frame.address)
364              , value = b.frame.callvalue
365              , timestamp = b.frame.timestamp
366              }
367        let readCalls
368            : ReadCalls m
369            = { invoke = \A B name to value -> raw.callValue A B name to (None Word256) value
370              , optional =
371                  \A B name to value next ->
372                    raw.optionalCallValue
373                      A
374                      B
375                      name
376                      to
377                      (None Word256)
378                      value
379                      (next (None B))
380                      (\result -> next (Some result))
381              , attempt =
382                  \E A B name to value next ->
383                    raw.tryCallValue
384                      E
385                      A
386                      B
387                      name
388                      to
389                      (None Word256)
390                      value
391                      (\error -> next ((Outcome E B).Err error))
392                      (\result -> next ((Outcome E B).Ok result))
393              }
394        let writeCalls
395            : WriteCalls m
396            = { transfer =
397                  \to amount ->
398                    b.monad.bind
399                      (b.call
400                         { to = Word/fromNatural 256 (Word/toNatural to)
401                         , value = amount
402                         , input = []
403                         })
404                      (\ok -> b.branch ok (b.monad.pure {=}) b.bubble)
405              , invoke = \A B name to amount value -> raw.callValue A B name to (Some amount) value
406              , optional =
407                  \A B name to amount value next ->
408                    raw.optionalCallValue
409                      A
410                      B
411                      name
412                      to
413                      (Some amount)
414                      value
415                      (next (None B))
416                      (\result -> next (Some result))
417              , attempt =
418                  \E A B name to amount value next ->
419                    raw.tryCallValue
420                      E
421                      A
422                      B
423                      name
424                      to
425                      (Some amount)
426                      value
427                      (\error -> next ((Outcome E B).Err error))
428                      (\result -> next ((Outcome E B).Ok result))
429              }
430        let guard
431            : Guard m
432            = { run =
433                  \A key action ->
434                    b.monad.bind
435                      (b.tload key)
436                      (\held ->
437                         b.branch
438                           (Word/isZero held)
439                           (b.monad.bind
440                              (b.tstore key (Word/fromNatural 256 1))
441                              (\_ ->
442                                 b.monad.bind
443                                   action
444                                   (\result ->
445                                      b.monad.bind
446                                        (b.tstore key (Word/fromNatural 256 0))
447                                        (\_ -> b.monad.pure result))))
448                           (b.revert []))
449              }
450        let reject
451            : forall (A : Type) -> Errors -> m A
452            = \A value _ ->
453                if abi
454                then raw.rejectSolidity Errors signals.errors value
455                else raw.rejectValue Errors owner value
456        -- The protocol is a run-time flag in a body that both protocols
457        -- enter: a log continues, so the branch on it joins the rest.
458        let signals
459            : { emit : Events -> m unit }
460            = { emit =
461                  \value ->
462                    b.branch
463                      abi
464                      (\(next : unit -> Code) ->
465                         raw.emitSolidity Events signals.events value (next {=}))
466                      (\(next : unit -> Code) -> raw.emitValue Events owner value (next {=}))
467              }
468        let read
469            : Storage.Read State m
470            = { get = \A path -> raw.getState State A selection path
471              , length = \A path -> raw.stateLength State A selection path
472              }
473        let write
474            : Storage.Write State m
475            = { set = \A path value next -> raw.setState State A selection path value (next {=})
476              , append =
477                  \A path values next -> raw.appendState State A selection path values (next {=})
478              }
479        in  merge
480              { Pure = \body -> body args @(\_ -> (||)) m c { reject }
481              , View =
482                  \body ->
483                    body
484                      args
485                      @(\_ -> (||))
486                      m
487                      c
488                      { context
489                      , immutable
490                      , readState = read
491                      , readCalls
492                      , reject
493                      }
494              , Write =
495                  \body ->
496                    body
497                      args
498                      @(\_ -> (||))
499                      m
500                      c
501                      { context
502                      , immutable
503                      , readState = read
504                      , writeState = write
505                      , readCalls
506                      , writeCalls
507                      , guard
508                      , reject
509                      , signals
510                      }
511              , Payable =
512                  \body ->
513                    body
514                      args
515                      @(\_ -> (||))
516                      m
517                      c
518                      { context
519                      , immutable
520                      , readState = read
521                      , writeState = write
522                      , readCalls
523                      , writeCalls
524                      , guard
525                      , reject
526                      , signals
527                      }
528              }
529              handler
530
531let modeName =
532      \(mode : E.Mode) ->
533        merge { Pure = "pure", View = "view", Write = "nonpayable", Payable = "payable" } mode
534
535let signature = \name -> "omegyu.native.v1:" ++ name
536let prefix : Natural = 0x4f4d4701
537-- The text whose Keccak-256 hash selects a route of the method `name`: its
538-- native signature, qualified by its owner, or its Solidity signature.
539let routeSignature
540    : Text -> Text -> Runtime.Wire -> Text
541    = \owner name wire ->
542        merge
543          { Native = signature (qualify owner name)
544          , Solidity = \(d : Solidity.Description) -> Solidity.signature name d
545          }
546          wire
547let Main = forall (Code : Type) -> Runtime.Ops Code -> Code
548let Message =
549      { name : Text
550      , role : EntryKind
551      , mode : Text
552      , arguments : Description
553      , result : Description
554      , argumentsWire : Runtime.Wire
555      , resultWire : Runtime.Wire
556      , signature : Text
557      -- ^ The text whose hash keys the route (`routeSignature`); empty for
558      -- receive and fallback, which have no key.
559      }
560let SignalSet =
561      { owner : Text
562      , events : Description
563      , errors : Description
564      , declarations : Signals
565      , native : Bool
566      , solidity : Bool
567      }
568let Lowered =
569      { runtime : Main
570      , initial : Main
571      , messages : List Message
572      , arguments : Description
573      , argumentsWire : Runtime.Wire
574      , signals : List SignalSet
575      , storage : List { name : Text, layout : Layout.Description }
576      , problems : List Text
577      }
578let isSolidity = \(wire : Runtime.Wire) -> merge { Native = False, Solidity = \_ -> True } wire
579-- The input of a method's body: the protocol of the route that entered it,
580-- which selects the encodings of its result, events and errors, and the
581-- decoded arguments.
582let Input = \(A : Type) -> { solidity : Bool, args : A }
583-- A case of the dispatch: its key, whether its handler is payable, and its
584-- code, given whether that code checks the call value.
585let Arm = \(Code : Type) -> { key : Word256, payable : Bool, code : Bool -> Code }
586-- The cases of the dispatch: native methods by header, Solidity methods by
587-- selector, and the receive and fallback entries (at most one each, which
588-- the compiler checks).
589let Arms =
590      \(Code : Type) ->
591        { native : List (Arm Code)
592        , solidity : List (Arm Code)
593        , receive : List (Arm Code)
594        , fallback : List (Arm Code)
595        }
596-- The code, after a revert with empty data when the check is on and the
597-- call sends value.
598let valueChecked =
599      \(Code : Type) (o : S.Ops Word256 Bool Code) (check : Bool) (code : Code) ->
600        if check then o.branch (Word/isZero o.callvalue) code (o.revert []) else code
601-- The key of a route: the eight-byte native header (the prefix, then the
602-- selector) or the four-byte Solidity selector of its signature.
603let routeKey
604    : forall (Code : Type) -> S.Ops Word256 Bool Code -> Runtime.Wire -> Text -> Word256
605    = \Code o wire text ->
606        let selector = Word/shr 224 (o.keccakText text)
607        in  merge
608              { Native = Word/or (Word/shl 32 (Word/fromNatural 256 prefix)) selector
609              , Solidity = \(_ : Solidity.Description) -> selector
610              }
611              wire
612-- Adds the cases of an entry of a component to the dispatch, then goes on
613-- with `next`. A method with two routes has one body, a join point that
614-- each route enters after decoding with its own codec, with its protocol
615-- as a flag: the body's leaves branch on it. A method with one route
616-- enters its body with a literal flag, whose branches fold. Its arguments
617-- are joined after decoding, so that a union argument, which the decoder
618-- passes on from one place per alternative, does not copy the body.
619let entryArms =
620      \{Events Errors State Imm : Type}
621       (Code : Type)
622       (raw : Runtime.Ops Code)
623       (owner : Text)
624       (signals : Signals)
625       (selection : Layout.Selection State)
626       (immutables : Immutable.Plan Imm)
627       (offset : Natural)
628       (entry : Entry Events Errors State Imm)
629       (next : Arms Code -> Code)
630       (arms : Arms Code) ->
631        let o = raw.evm // { words = S.nativeWords }
632        -- Reading the immutables fails only on code that the constructor
633        -- did not write; it then reverts.
634        let withImmutables =
635              \(body : Imm -> Code) -> immutables.read Code o.immutable offset body (o.revert [])
636        in  entry
637              Code
638              (\A B binding bound ->
639                 let names = binding.names
640                 let args = binding.arguments
641                 let result = binding.result
642                 let handler = handlerAt @Events @Errors @State @Imm A B binding bound
643                 let payable = isPayable handler
644                 let body =
645                       \(x : Input A) ->
646                         withImmutables
647                           (\(immutable : Imm) ->
648                              run
649                                x.solidity
650                                owner
651                                signals
652                                selection
653                                immutable
654                                Code
655                                raw
656                                handler
657                                x.args
658                                (\(r : B) ->
659                                   if x.solidity
660                                   then (encodingFor True result).write Code raw r
661                                   else (encodingFor False result).write Code raw r))
662                 let decoded =
663                       \(solidity : Bool) ->
664                         (encodingFor solidity args).read Code raw (if solidity then 4 else 8)
665                 let withRoutes =
666                       \(enter : Bool -> Code) ->
667                         let on =
668                               \(solidity : Bool) (name : Optional Text) ->
669                                 std:Optional.fold
670                                   (\(name : Text) ->
671                                      let wire = (encodingFor solidity args).wire
672                                      in  [ { key =
673                                                routeKey
674                                                  Code
675                                                  o
676                                                  wire
677                                                  (routeSignature owner name wire)
678                                            , payable
679                                            , code =
680                                                \(check : Bool) ->
681                                                  valueChecked
682                                                    Code
683                                                    o
684                                                    (check && std:Bool.not payable)
685                                                    (enter solidity)
686                                            }
687                                          ])
688                                   ([] : List (Arm Code))
689                                   name
690                         in  arms
691                             // { native = on False names.native # arms.native
692                                , solidity = on True names.solidity # arms.solidity
693                                }
694                 in  if std:Optional.isSome names.native && std:Optional.isSome names.solidity
695                     then o.join
696                            (Input A)
697                            body
698                            (\(enter : Input A -> Code) ->
699                               next
700                                 (withRoutes
701                                    (\(solidity : Bool) ->
702                                       decoded
703                                         solidity
704                                         (\(a : A) -> enter { solidity, args = a }))))
705                     else next
706                            (withRoutes
707                               (\(solidity : Bool) ->
708                                  o.join
709                                    A
710                                    (\(a : A) -> body { solidity, args = a })
711                                    (decoded solidity))))
712              (\action ->
713                 next
714                   (arms
715                    // { receive =
716                           [ { key = Word/fromNatural 256 0
717                             , payable = True
718                             , code =
719                                 \(_ : Bool) ->
720                                   withImmutables
721                                     (\(immutable : Imm) ->
722                                        run
723                                          True
724                                          owner
725                                          signals
726                                          selection
727                                          immutable
728                                          Code
729                                          raw
730                                          ((Handler Events Errors State Imm unit unit).Payable
731                                             (\_ -> action))
732                                          {=}
733                                          (\(_ : unit) -> o.ret []))
734                             }
735                           ]
736                           # arms.receive
737                       }))
738              (\B result handler ->
739                 let payable = isPayable handler
740                 in  next
741                       (arms
742                        // { fallback =
743                               [ { key = Word/fromNatural 256 0
744                                 , payable
745                                 , code =
746                                     \(check : Bool) ->
747                                       valueChecked
748                                         Code
749                                         o
750                                         (check && std:Bool.not payable)
751                                         (withImmutables
752                                            (\(immutable : Imm) ->
753                                               run
754                                                 True
755                                                 owner
756                                                 signals
757                                                 selection
758                                                 immutable
759                                                 Code
760                                                 raw
761                                                 handler
762                                                 o.cdsize
763                                                 (\(r : B) ->
764                                                    (encodingFor True result).write Code raw r)))
765                                 }
766                               ]
767                               # arms.fallback
768                           }))
769-- The dispatch: one switch on the native header, whose default is the
770-- Solidity part: short call data (receive when there is none, the
771-- fallback otherwise), then one switch on the selector, whose default is
772-- the fallback, staged once. With Solidity methods, one test of the native
773-- prefix in the first four bytes comes first, so that a Solidity call
774-- never takes the native switch: no Solidity selector is the prefix (the
775-- compiler checks it). A native prefix with an unknown selector reaches
776-- the fallback through the Solidity switch either way.
777--
778-- A handler that is not payable reverts with empty data when the call
779-- sends value, before decoding, which reverts with empty data too: one
780-- check before a switch serves every case it reaches when none of them is
781-- payable, and each case checks for itself otherwise.
782let dispatch =
783      \(Code : Type) (o : S.Ops Word256 Bool Code) (arms : Arms Code) ->
784        let nonpayable =
785              \(list : List (Arm Code)) ->
786                L.all (\(arm : Arm Code) -> std:Bool.not arm.payable) list
787        let solidityChecked =
788              nonpayable arms.solidity && nonpayable arms.fallback && L.null arms.receive
789        let allChecked = solidityChecked && nonpayable arms.native
790        -- Equal entry bodies can share their decoder and all the work after it.
791        let cases =
792              \(check : Bool) (list : List (Arm Code)) ->
793                L.map
794                  (\(arm : Arm Code) ->
795                     { key = arm.key
796                     , code = o.share ([] : List Word256) (\_ -> arm.code check)
797                     })
798                  list
799        let header = o.cdload (Word/fromNatural 256 0)
800        let fallback =
801              std:Optional.fold
802                (\(arm : Arm Code) -> arm.code (std:Bool.not solidityChecked))
803                (o.revert [])
804                (L.head arms.fallback)
805        in  o.join
806              unit
807              (\(_ : unit) -> fallback)
808              (\(other : unit -> Code) ->
809                 let short =
810                       std:Optional.fold
811                         (\(arm : Arm Code) ->
812                            o.branch (Word/isZero o.cdsize) (arm.code False) (other {=}))
813                         (other {=})
814                         (L.head arms.receive)
815                 let solidity =
816                       valueChecked
817                         Code
818                         o
819                         (solidityChecked && std:Bool.not allChecked)
820                         (o.branch
821                            (Word/lt o.cdsize (Word/fromNatural 256 4))
822                            short
823                            (o.switch
824                               (Word/shr 224 header)
825                               (cases (std:Bool.not solidityChecked) arms.solidity)
826                               (other {=})))
827                 in  valueChecked
828                       Code
829                       o
830                       allChecked
831                       (if L.null arms.native
832                        then solidity
833                        else if L.null arms.solidity
834                        then o.switch
835                               (Word/shr 192 header)
836                               (cases (std:Bool.not allChecked) arms.native)
837                               solidity
838                        else o.join
839                               unit
840                               (\(_ : unit) -> solidity)
841                               (\(foreign : unit -> Code) ->
842                                  o.branch
843                                    (Word/equal (Word/shr 224 header) (Word/fromNatural 256 prefix))
844                                    (o.switch
845                                       (Word/shr 192 header)
846                                       (cases (std:Bool.not allChecked) arms.native)
847                                       (foreign {=}))
848                                    (foreign {=}))))
849
850-- The reader never returns a callable for decoded method arguments. Metadata
851-- sees only the mode; executable observations lower a complete dispatch arm.
852let BoundaryInfo = { wire : Runtime.Wire, problems : List Text }
853let EntryView =
854      \(State Imm : Type) ->
855        { inspect :
856            forall (R : Type)
857            -> (forall (A B : Type)
858                -> EntryKind
859                -> Text
860                -> BoundaryInfo
861                -> BoundaryInfo
862                -> E.Mode
863                -> R)
864            -> List R
865        , arms :
866            forall (Code : Type)
867            -> Runtime.Ops Code
868            -> Text
869            -> Signals
870            -> Layout.Selection State
871            -> Immutable.Plan Imm
872            -> Natural
873            -> (Arms Code -> Code)
874            -> Arms Code
875            -> Code
876        }
877let observeEntry
878    : forall (Events Errors State Imm : Type)
879      -> Entry Events Errors State Imm
880      -> EntryView State Imm
881    = \Events Errors State Imm entry ->
882        { inspect =
883            \R inspect ->
884              interpretEntry
885                @Events
886                @Errors
887                @State
888                @Imm
889                entry
890                R
891                (\A B role name args result handler ->
892                   inspect
893                     A
894                     B
895                     role
896                     name
897                     { wire = args.wire, problems = args.problems }
898                     { wire = result.wire, problems = result.problems }
899                     (kindOf handler))
900        , arms =
901            \Code raw owner signals selection immutables offset ->
902              entryArms
903                @Events
904                @Errors
905                @State
906                @Imm
907                Code
908                raw
909                owner
910                signals
911                selection
912                immutables
913                offset
914                entry
915        }
916let Scope = { events : Type, errors : Type, state : Type, imm : Type }
917let scope = \(events errors state imm : Type) -> ({ events, errors, state, imm } : Scope)
918let Raw = \(s : Scope) -> Entry s.events s.errors s.state s.imm
919let chosen
920    : std:Observation.Reader @1 @Scope Raw
921    = (\(s : Scope) -> EntryView s.state s.imm, \s -> observeEntry s.events s.errors s.state s.imm)
922let Packed =
923      \(Events Errors State Imm : Type) ->
924        std:Observation.Package @1 @Scope @Raw chosen (scope Events Errors State Imm)
925let packEntry =
926      \(Events Errors State Imm : Type) ->
927        std:Observation.pack @1 @Scope @Raw chosen (scope Events Errors State Imm)
928let viewEntry =
929      \(Events Errors State Imm : Type) ->
930        std:Observation.view @1 @Scope @Raw chosen (scope Events Errors State Imm)
931let Facet =
932      \(Events Errors State Imm : Type) ->
933        { entries : List (Packed Events Errors State Imm), problems : List Text }
934-- Each component keeps its own source types, selected layout and constructor.
935-- The dependent package permits generic inspection without a fixed result
936-- universe. Runtime actions still expose only their restricted capabilities.
937let Component =
938      exists (Events Errors State Imm Args : Type) *
939        { name : Text
940        , signals : Signals
941        , placement : Layout.Selection State
942        , boundary : ValueBoundary Args
943        , immutables : Immutable.Plan Imm
944        , constructor : Constructor Events Errors State Imm Args
945        , facet : Facet Events Errors State Imm
946        }
947let makeComponent =
948      \(Events Errors State Imm Args : Type)
949       (name : Text)
950       (signals : Signals)
951       (placement : Layout.Selection State)
952       (boundary : ValueBoundary Args)
953       (immutables : Immutable.Plan Imm)
954       (constructor : Constructor Events Errors State Imm Args)
955       (facet : Facet Events Errors State Imm) ->
956        ((Events,
957         (Errors,
958         (State,
959         (Imm, (Args, { name, signals, placement, boundary, immutables, constructor, facet }))))) :
960           Component)
961let useComponent =
962      \{l : Level}
963       (component : Component)
964       (R : Type l)
965       (consume :
966         forall (Events Errors State Imm Args : Type)
967         -> Text
968         -> Signals
969         -> Layout.Selection State
970         -> ValueBoundary Args
971         -> Immutable.Plan Imm
972         -> Constructor Events Errors State Imm Args
973         -> Facet Events Errors State Imm
974         -> R) ->
975        let body = component.2.2.2.2.2
976        in  consume
977              component.1
978              component.2.1
979              component.2.2.1
980              component.2.2.2.1
981              component.2.2.2.2.1
982              body.name
983              body.signals
984              body.placement
985              body.boundary
986              body.immutables
987              body.constructor
988              body.facet
989let ownerOf =
990      \(component : Component) ->
991        useComponent
992          component
993          Owners.Owner
994          (\Events
995            Errors
996            State
997            Imm
998            Args
999            name
1000            signals
1001            placement
1002            boundary
1003            immutables
1004            constructor
1005            facet ->
1006             Owners.owner name placement)
1007let ownersOf = \(components : List Component) -> L.map ownerOf components
1008-- Evidence describes the exact component list consumed by the lowerer.
1009let Contract = exists (components : List Component) * Owners.Evidence (ownersOf components)
1010let PlacementValid =
1011      \{State : Type} (placement : Layout.Selection State) ->
1012        Certificate.Valid (Owners.certificate [ Owners.owner "" placement ])
1013let ownership = \(contract : Contract) -> Owners.explicit (ownersOf contract.1) contract.2
1014let empty : Contract = ([], { separated = {=}, fits = {=}, names = refl })
1015-- This equality preserves complete components, including constructors,
1016-- methods, codecs and selected layouts. It is a structural composition law,
1017-- not a claim about gas or the correctness of EVM code generation.
1018let regroup
1019    : forall (left middle right : Contract)
1020      -> left.1 # middle.1 # right.1 === left.1 # (middle.1 # right.1)
1021    = \left middle right ->
1022        List/elim
1023          (\parts -> parts # middle.1 # right.1 === parts # (middle.1 # right.1))
1024          refl
1025          (\component rest proof -> Eq.cong (\tail -> [ component ] # tail) proof)
1026          left.1
1027
1028-- Constructor input composition is a source-level product interpretation.
1029-- Its native encoding follows the same ordinary structural codec as any
1030-- other product; there is no compiler-only aggregate argument representation.
1031let pairBoundary =
1032      \{A B : Type} (left : ValueBoundary A) (right : ValueBoundary B) ->
1033        left
1034          (\A -> ValueBoundary (A * B))
1035          (\P _ first ->
1036             right
1037               (\B -> ValueBoundary (P Solidity.values * B))
1038               (\Q _ second ->
1039                  nativeCodec
1040                    ({ formers = first.formers
1041                     , fold =
1042                         \Result algebra ->
1043                           algebra.pair P Q (first.fold Result algebra) (second.fold Result algebra)
1044                     } :
1045                       Reflect Solidity.types (\F -> P F * Q F))))
1046let ownersAppended
1047    : forall (left right : List Component)
1048      -> ownersOf (left # right) === ownersOf left # ownersOf right
1049    = \left right ->
1050        List/elim
1051          (\left -> ownersOf (left # right) === ownersOf left # ownersOf right)
1052          refl
1053          (\component rest proof -> Eq.cong (\tail -> [ ownerOf component ] # tail) proof)
1054          left
1055let joinedOwners = \(left right : Contract) -> ownersOf left.1 # ownersOf right.1
1056let joinWith =
1057      \(left right : Contract) (proof : Owners.Evidence (joinedOwners left right)) ->
1058        ((left.1 # right.1,
1059         Eq.subst Owners.Evidence (Eq.sym (ownersAppended left.1 right.1)) proof) :
1060           Contract)
1061let join =
1062      \(left right : Contract)
1063       {valid : Certificate.Valid (Owners.certificate (joinedOwners left right))} ->
1064        joinWith left right (Owners.select (joinedOwners left right) @valid).2
1065let renamedComponents =
1066      \(name : Text) (contract : Contract) ->
1067        L.map
1068          (\(component : Component) ->
1069             useComponent
1070               component
1071               Component
1072               (\Events
1073                 Errors
1074                 State
1075                 Imm
1076                 Args
1077                 previous
1078                 signals
1079                 placement
1080                 boundary
1081                 immutables
1082                 constructor
1083                 facet ->
1084                  makeComponent
1085                    Events
1086                    Errors
1087                    State
1088                    Imm
1089                    Args
1090                    (if Text/equal previous "" then name else qualify name previous)
1091                    signals
1092                    placement
1093                    boundary
1094                    immutables
1095                    constructor
1096                    facet))
1097          contract.1
1098let named =
1099      \(name : Text)
1100       (contract : Contract)
1101       {valid :
1102         Certificate.Valid (Owners.certificate (ownersOf (renamedComponents name contract)))} ->
1103        let components = renamedComponents name contract
1104        let plan : Owners.Plan = Owners.select (ownersOf components) @valid
1105        in  ((components, plan.2) : Contract)
1106
1107-- Instantiation separates a reusable component's storage graph from its new
1108-- reservation. A bundle contains requests, not an unchecked Contract. Joining
1109-- bundles does not allocate: the complete flattened bundle is planned once.
1110let Instance = { component : Component, reservation : Allocate.Request }
1111let Bundle = List Instance
1112let componentLayout =
1113      \(component : Component) ->
1114        useComponent
1115          component
1116          Layout.Description
1117          (\Events
1118            Errors
1119            State
1120            Imm
1121            Args
1122            name
1123            signals
1124            placement
1125            boundary
1126            immutables
1127            constructor
1128            facet ->
1129             Layout.describe placement)
1130let instanceSize = \(component : Component) -> Layout.reservationSize (componentLayout component)
1131let instantiate =
1132      \(name : Text) (definition : Contract) ->
1133        (L.map
1134           (\(component : Component) ->
1135              { component, reservation = Allocate.Request.Automatic (instanceSize component) })
1136           (renamedComponents name definition) :
1137           Bundle)
1138-- A manual root applies to a whole definition, including composed ones.
1139-- Its components receive consecutive minimum reservations from that root.
1140-- Use fixed instead to retain explicitly selected reservation sizes and gaps.
1141let instanceAt =
1142      \(name : Text) (root : Natural) (definition : Contract) ->
1143        List/elim
1144          (\(_ : List Component) -> Natural -> Bundle)
1145          (\_ -> [])
1146          (\component rest next start ->
1147             let size = instanceSize component
1148             in  [ { component, reservation = Allocate.Request.Fixed { start, size } } ]
1149                 # next (start + size))
1150          (renamedComponents name definition)
1151          root
1152let fixed =
1153      \(name : Text) (definition : Contract) ->
1154        (L.map
1155           (\(component : Component) ->
1156              { component, reservation = Allocate.Request.Fixed (componentLayout component).space })
1157           (renamedComponents name definition) :
1158           Bundle)
1159let candidate = Allocate.candidate (\(instance : Instance) -> instance.reservation) 0
1160-- Inspect exactly the proposed graphs and reservations that assembly checks.
1161let placements =
1162      \(bundle : Bundle) ->
1163        L.map
1164          (\(placed : Allocate.Placed Instance) ->
1165             useComponent
1166               placed.value.component
1167               { name : Text, layout : Layout.Description }
1168               (\Events
1169                 Errors
1170                 State
1171                 Imm
1172                 Args
1173                 name
1174                 signals
1175                 placement
1176                 boundary
1177                 immutables
1178                 constructor
1179                 facet ->
1180                  { name, layout = Layout.relocate placed.region (Layout.describe placement) }))
1181          (candidate bundle)
1182let realization =
1183      \(placed : Allocate.Placed Instance) ->
1184        useComponent
1185          placed.value.component
1186          (Certificate.Certificate @0 Component)
1187          (\Events
1188            Errors
1189            State
1190            Imm
1191            Args
1192            name
1193            signals
1194            placement
1195            boundary
1196            immutables
1197            constructor
1198            facet ->
1199             let source = Layout.source placement
1200             let description = Layout.relocate placed.region (Layout.describe placement)
1201             in  Certificate.label
1202                   "storage layout for ${name}"
1203                   (Certificate.make
1204                      (Layout.problems source description)
1205                      ([] : List Text)
1206                      (\valid ->
1207                         makeComponent
1208                           Events
1209                           Errors
1210                           State
1211                           Imm
1212                           Args
1213                           name
1214                           signals
1215                           (Layout.select source description @valid)
1216                           boundary
1217                           immutables
1218                           constructor
1219                           facet)))
1220let realize =
1221      List/elim
1222        (\(_ : List (Allocate.Placed Instance)) -> Certificate.Certificate @0 (List Component))
1223        (Certificate.known ([] : List Component))
1224        (\placed rest after ->
1225           Certificate.map
1226             (\(parts : Component * List Component) -> [ parts.1 ] # parts.2)
1227             (Certificate.both (realization placed) after))
1228let AssemblyLayoutsValid = \(bundle : Bundle) -> Certificate.Valid (realize (candidate bundle))
1229let realized =
1230      \(bundle : Bundle) {valid : AssemblyLayoutsValid bundle} ->
1231        Certificate.prove (realize (candidate bundle)) @valid
1232let AssemblyOwnersValid =
1233      \(bundle : Bundle) (layouts : AssemblyLayoutsValid bundle) ->
1234        Certificate.Valid (Owners.certificate (ownersOf (realized bundle @layouts)))
1235-- Both obligations are ordinary source evidence. Explicit proofs can be
1236-- supplied when inference cannot discharge a valid generic choice.
1237let assemble =
1238      \(bundle : Bundle)
1239       {layouts : AssemblyLayoutsValid bundle}
1240       {owners : AssemblyOwnersValid bundle layouts} ->
1241        let components = realized bundle @layouts
1242        in  ((components, (Owners.select (ownersOf components) @owners).2) : Contract)
1243let regroupBundles
1244    : forall (left middle right : Bundle) -> left # middle # right === left # (middle # right)
1245    = \left middle right ->
1246        List/elim
1247          (\parts -> parts # middle # right === parts # (middle # right))
1248          refl
1249          (\instance rest proof -> Eq.cong (\tail -> [ instance ] # tail) proof)
1250          left
1251let regroupPlacements =
1252      \(left middle right : Bundle) -> Eq.cong placements (regroupBundles left middle right)
1253
1254-- This interpreter assembles constructor inputs once, after flattening.
1255-- Both parenthesizations of a join therefore obtain the same input type,
1256-- codec and initializer sequence.
1257let Initialization =
1258      exists (Args : Type) *
1259        { boundary : ValueBoundary Args
1260        , run :
1261            forall (Code : Type)
1262            -> Runtime.Ops Code
1263            -> Bool
1264            -> Args
1265            -> (List Word256 -> Code)
1266            -> Code
1267        }
1268let componentInitializer =
1269      \(component : Component) ->
1270        useComponent
1271          component
1272          Initialization
1273          (\Events
1274            Errors
1275            State
1276            Imm
1277            Args
1278            owner
1279            signals
1280            placement
1281            boundary
1282            immutables
1283            constructor
1284            facet ->
1285             ((Args,
1286              { boundary
1287              , run =
1288                  \Code raw abi args next ->
1289                    raw.withState
1290                      State
1291                      placement
1292                      (\(selection : Layout.Selection State) ->
1293                         run
1294                           abi
1295                           owner
1296                           signals
1297                           selection
1298                           {=}
1299                           Code
1300                           raw
1301                           ((Handler Events Errors State unit Args Imm).Write constructor)
1302                           args
1303                           (\value -> immutables.write Code value next (raw.evm.revert [])))
1304              }) :
1305                Initialization))
1306let combineInitializers =
1307      \(first second : Initialization) ->
1308        ((first.1 * second.1,
1309         { boundary = pairBoundary first.2.boundary second.2.boundary
1310         , run =
1311             \Code raw abi args next ->
1312               first.2.run
1313                 Code
1314                 raw
1315                 abi
1316                 args.1
1317                 (\a -> second.2.run Code raw abi args.2 (\b -> next (a # b)))
1318         }) :
1319           Initialization)
1320let initializers =
1321      List/elim
1322        (\(_ : List Component) -> Initialization)
1323        (({}, { boundary = nativeCodec {}, run = \Code raw abi args next -> next [] }) :
1324           Initialization)
1325        (\component rest after ->
1326           let first = componentInitializer component
1327           in  if L.null rest then first else combineInitializers first after)
1328
1329let lower =
1330      \(declaration : Contract) ->
1331        let components = declaration.1
1332        let Located = { component : Component, offset : Natural }
1333        let located =
1334              List/elim
1335                (\(_ : List Component) -> Natural -> List Located)
1336                (\offset -> [])
1337                (\component rest after offset ->
1338                   let width =
1339                         useComponent
1340                           component
1341                           Natural
1342                           (\Events
1343                             Errors
1344                             State
1345                             Imm
1346                             Args
1347                             name
1348                             signals
1349                             placement
1350                             boundary
1351                             immutables
1352                             constructor
1353                             facet ->
1354                              immutables.width)
1355                   in  [ { component, offset } ] # after (offset + width))
1356                components
1357                0
1358        let initialization = initializers components
1359        let Args = initialization.1
1360        let args = encoding initialization.2.boundary
1361        let messages =
1362              L.concatMap
1363                (\(component : Component) ->
1364                   useComponent
1365                     component
1366                     (List Message)
1367                     (\Events
1368                       Errors
1369                       State
1370                       Imm
1371                       LocalArgs
1372                       owner
1373                       signals
1374                       placement
1375                       boundary
1376                       immutables
1377                       constructor
1378                       facet ->
1379                        L.concatMap
1380                          (\entry ->
1381                             (viewEntry Events Errors State Imm entry).inspect
1382                               Message
1383                               (\P R role name parameters result mode ->
1384                                  { role
1385                                  , name =
1386                                      if isSolidity parameters.wire
1387                                      then name
1388                                      else qualify owner name
1389                                  , mode = modeName mode
1390                                  , arguments = describe P
1391                                  , result = describe R
1392                                  , argumentsWire = parameters.wire
1393                                  , resultWire = result.wire
1394                                  , signature =
1395                                      merge
1396                                        { Method = routeSignature owner name parameters.wire
1397                                        , Receive = ""
1398                                        , Fallback = ""
1399                                        }
1400                                        role
1401                                  }))
1402                          facet.entries))
1403                components
1404        let uses =
1405              \{Events Errors State Imm : Type}
1406               (abi : Bool)
1407               (facet : Facet Events Errors State Imm) ->
1408                L.any
1409                  (\entry ->
1410                     L.any
1411                       (\(used : Bool) -> used)
1412                       ((viewEntry Events Errors State Imm entry).inspect
1413                          Bool
1414                          (\P R role name parameters result mode ->
1415                             isSolidity parameters.wire == abi)))
1416                  facet.entries
1417        in  ({ arguments = describe Args
1418             , argumentsWire = args.wire
1419             , storage = Owners.describe (ownership declaration)
1420             , messages
1421             , signals =
1422                 L.map
1423                   (\(component : Component) ->
1424                      useComponent
1425                        component
1426                        SignalSet
1427                        (\Events
1428                          Errors
1429                          State
1430                          Imm
1431                          LocalArgs
1432                          owner
1433                          signals
1434                          placement
1435                          boundary
1436                          immutables
1437                          constructor
1438                          facet ->
1439                           { owner
1440                           , events = describe Events
1441                           , errors = describe Errors
1442                           , declarations = signals
1443                           , native = uses False facet || isSolidity args.wire == False
1444                           , solidity = uses True facet || isSolidity args.wire
1445                           }))
1446                   components
1447             , problems =
1448                 args.problems
1449                 # L.concatMap
1450                     (\(component : Component) ->
1451                        useComponent
1452                          component
1453                          (List Text)
1454                          (\Events
1455                            Errors
1456                            State
1457                            Imm
1458                            LocalArgs
1459                            owner
1460                            signals
1461                            placement
1462                            boundary
1463                            immutables
1464                            constructor
1465                            facet ->
1466                             signals.problems
1467                             # facet.problems
1468                             # L.concatMap
1469                                 (\entry ->
1470                                    L.concatMap
1471                                      (\(problems : List Text) -> problems)
1472                                      ((viewEntry Events Errors State Imm entry).inspect
1473                                         (List Text)
1474                                         (\P R role name parameters result mode ->
1475                                            L.map
1476                                              (\why -> name ++ " arguments: " ++ why)
1477                                              parameters.problems
1478                                            # L.map
1479                                                (\why -> name ++ " result: " ++ why)
1480                                                result.problems)))
1481                                 facet.entries))
1482                     components
1483             , runtime =
1484                 \Code raw ->
1485                   let o = raw.evm // { words = S.nativeWords }
1486                   -- Every case of every component is added before the
1487                   -- dispatch, inside the join points of their bodies.
1488                   in  L.fold
1489                         (\(at : Located) (rest : Arms Code -> Code) (arms : Arms Code) ->
1490                            useComponent
1491                              at.component
1492                              Code
1493                              (\Events
1494                                Errors
1495                                State
1496                                Imm
1497                                LocalArgs
1498                                owner
1499                                signals
1500                                placement
1501                                boundary
1502                                immutables
1503                                constructor
1504                                facet ->
1505                                 raw.withState
1506                                   State
1507                                   placement
1508                                   (\(selection : Layout.Selection State) ->
1509                                      L.fold
1510                                        (\entry (later : Arms Code -> Code) ->
1511                                           (viewEntry Events Errors State Imm entry).arms
1512                                             Code
1513                                             raw
1514                                             owner
1515                                             signals
1516                                             selection
1517                                             immutables
1518                                             at.offset
1519                                             later)
1520                                        rest
1521                                        facet.entries
1522                                        arms)))
1523                         (dispatch Code o)
1524                         located
1525                         { native = ([] : List (Arm Code))
1526                         , solidity = ([] : List (Arm Code))
1527                         , receive = ([] : List (Arm Code))
1528                         , fallback = ([] : List (Arm Code))
1529                         }
1530             , initial =
1531                 \Code raw ->
1532                   let o = raw.evm // { words = S.nativeWords }
1533                   -- The constructors are not payable.
1534                   in  valueChecked
1535                         Code
1536                         o
1537                         (std:Bool.not (L.null components))
1538                         (o.join
1539                            Args
1540                            (\(value : Args) ->
1541                               initialization.2.run
1542                                 Code
1543                                 raw
1544                                 (isSolidity args.wire)
1545                                 value
1546                                 (\words ->
1547                                    raw.evm.ret (L.map (\word -> { size = 32, word }) words)))
1548                            (args.read Code raw 0))
1549             } :
1550               Lowered)
1551
1552let make =
1553      \{Events Errors Imm : Type} (signals : Signals) (immutables : Immutable.Plan Imm) ->
1554        let describeBoundary
1555            : forall {A : Type} -> ValueBoundary A -> Solidity.Description
1556            = \{A} boundary ->
1557                boundary
1558                  (\_ -> Solidity.Description)
1559                  (\P abi description -> Solidity.describe description)
1560        let Key = O.Key
1561        let Operation = O.Operation
1562        let Table = O.Table
1563        let Family = O.Family
1564        let Routes = O.Routes
1565        let Protocol = O.Protocol
1566        let Body =
1567              \(State : Type) (k : Key) ->
1568                k.arguments -> Action Events Errors State Imm k.mode k.result
1569        -- Apply the arguments before obtaining a local action. Neither a bound
1570        -- member nor a projection of it is an unbound method body.
1571        let Local =
1572              \(State : Type) (k : Key) ->
1573                k.arguments -> { call : Action Events Errors State Imm k.mode k.result }
1574        let Definition =
1575              \(State : Type) (k : Key) -> { operation : Operation k, body : Body State k }
1576        let define =
1577              \{State A B : Type}
1578               {mode : E.Mode}
1579               {routes : Routes}
1580               (op : Operation { arguments = A, result = B, mode, routes })
1581               (body : A -> Action Events Errors State Imm mode B) ->
1582                ({ operation = op, body } :
1583                   Definition State { arguments = A, result = B, mode, routes })
1584        let Remote =
1585              \(p : Protocol) (k : Key) ->
1586                if O.exposed k.routes p then Method Errors k.arguments k.result else {}
1587        let remote
1588            : forall (p : Protocol) (k : Key) -> Text -> Operation k -> Remote p k
1589            = \p k label op ->
1590                let name = std:Optional.fold (\(n : Text) -> n) label (O.nameOn label k.routes p)
1591                let boundary =
1592                      merge
1593                        { Native = Runtime.Boundary.Native name
1594                        , Solidity =
1595                            Runtime.Boundary.Solidity
1596                              { name
1597                              , arguments = describeBoundary op.arguments
1598                              , result = describeBoundary op.result
1599                              , errors = signals.errors
1600                              }
1601                        }
1602                        p
1603                in  Bool/elim
1604                      (\(shown : Bool) -> if shown then Method Errors k.arguments k.result else {})
1605                      (\Call consume -> consume boundary)
1606                      {=}
1607                      (O.exposed k.routes p)
1608        let operations = O.operations
1609        let bindOperations =
1610              \{H : Family} (walk : Table.Walk H) (specs : H operations) ->
1611                let references =
1612                      \(p : Protocol) ->
1613                        walk.map operations { member = Remote p } (remote p) "" specs
1614                let implement =
1615                      \{State : Type} (bodies : H { member = Body State }) ->
1616                        let facet =
1617                              walk.zipFold
1618                                operations
1619                                { member = Body State }
1620                                (Facet Events Errors State Imm)
1621                                (\k name op body rest ->
1622                                   { entries =
1623                                       [ packEntry
1624                                           Events
1625                                           Errors
1626                                           State
1627                                           Imm
1628                                           (methodEntry
1629                                              @Events
1630                                              @Errors
1631                                              @State
1632                                              @Imm
1633                                              @k.arguments
1634                                              @k.result
1635                                              { label = name
1636                                              , names = O.namesOf name k.routes
1637                                              , arguments = op.arguments
1638                                              , result = op.result
1639                                              , mode = k.mode
1640                                              }
1641                                              body)
1642                                       ]
1643                                       # rest.entries
1644                                   , problems =
1645                                       if O.usesField k.routes
1646                                       then O.nameProblems name # rest.problems
1647                                       else rest.problems
1648                                   })
1649                                ""
1650                                specs
1651                                bodies
1652                                { entries = [], problems = [] }
1653                        in  { facet
1654                            , local =
1655                                walk.map
1656                                  { member = Body State }
1657                                  { member = Local State }
1658                                  (\k _ f args -> { call = f args })
1659                                  ""
1660                                  bodies
1661                            }
1662                in  { implement
1663                    , native = references Protocol.Native
1664                    , solidity = references Protocol.Solidity
1665                    }
1666        let use =
1667              \(schema : O.Schema) ->
1668                bindOperations
1669                  @schema.1
1670                  (Table.select @Operation @schema.1 schema.2.1.structure @schema.2.2)
1671                  schema.2.1.value
1672        let methods =
1673              \{State : Type}
1674               {H : Family}
1675               (selected :
1676                 { structure : Reflect @1 { member = Definition State } H
1677                 , value : H { member = Definition State }
1678                 })
1679               {valid : Table.Valid @(Definition State) @H selected.structure} ->
1680                let walk = Table.select @(Definition State) @H selected.structure @valid
1681                let map = walk.map { member = Definition State }
1682                let api =
1683                      bindOperations
1684                        @H
1685                        walk
1686                        (map operations (\k _ d -> d.operation) "" selected.value)
1687                in  api.implement
1688                      @State
1689                      (map { member = Body State } (\k _ d -> d.body) "" selected.value)
1690                    // { native = api.native, solidity = api.solidity }
1691        -- Native entries of a handler record typed by a validated interface,
1692        -- in its reverse canonical label order, each named by its label.
1693        let handlersFacet
1694            : forall {State : Type}
1695                     {H : Solidity.Families -> Type}
1696                     (interface : Solidity.Interface H)
1697              -> interface.1 Solidity.values (Handler Events Errors State Imm)
1698              -> Facet Events Errors State Imm
1699            = \{State} {H} interface handlers ->
1700                let entries =
1701                      interface.2.foldHandlers
1702                        Solidity.values
1703                        (Handler Events Errors State Imm)
1704                        (List (Packed Events Errors State Imm))
1705                        (\A B name position args result handler rest ->
1706                           let bind =
1707                                 \(mode : E.Mode) ->
1708                                   methodEntry
1709                                     @Events
1710                                     @Errors
1711                                     @State
1712                                     @Imm
1713                                     @(A Solidity.values)
1714                                     @(B Solidity.values)
1715                                     { label = name
1716                                     , names = { native = Some name, solidity = None Text }
1717                                     , arguments = solidityCodec @A args
1718                                     , result = solidityCodec @B result
1719                                     , mode
1720                                     }
1721                           in  rest
1722                               # [ packEntry
1723                                     Events
1724                                     Errors
1725                                     State
1726                                     Imm
1727                                     (merge
1728                                        { Pure = bind E.Mode.Pure
1729                                        , View = bind E.Mode.View
1730                                        , Write = bind E.Mode.Write
1731                                        , Payable = bind E.Mode.Payable
1732                                        }
1733                                        handler)
1734                                 ])
1735                        handlers
1736                        []
1737                in  { entries, problems = [] }
1738        let receive =
1739              \{State : Type} (action : Action Events Errors State Imm E.Mode.Payable unit) ->
1740                ({ entries =
1741                     [ packEntry
1742                         Events
1743                         Errors
1744                         State
1745                         Imm
1746                         (\R method receive fallback -> receive action)
1747                     ]
1748                 , problems = []
1749                 } :
1750                   Facet Events Errors State Imm)
1751        let fallback =
1752              \{State : Type}
1753               {B : Solidity.Families -> Type}
1754               (types : { Result : Reflect Solidity.types B })
1755               (handler : Handler Events Errors State Imm Word256 (B Solidity.values)) ->
1756                ({ entries =
1757                     [ packEntry
1758                         Events
1759                         Errors
1760                         State
1761                         Imm
1762                         (\R method receive fallback ->
1763                            fallback (B Solidity.values) (solidityCodec types.Result) handler)
1764                     ]
1765                 , problems = []
1766                 } :
1767                   Facet Events Errors State Imm)
1768        let composeWithBounds =
1769              \{State A : Type}
1770               (placement : Layout.Selection State)
1771               (types : { Args : ValueBoundary A })
1772               (bounded : std:Region.Fits (std:Natural.pow2 256) (Layout.describe placement).space)
1773               (body :
1774                 { constructor : Constructor Events Errors State Imm A
1775                 , facets : List (Facet Events Errors State Imm)
1776                 }) ->
1777                let component =
1778                      makeComponent
1779                        Events
1780                        Errors
1781                        State
1782                        Imm
1783                        A
1784                        ""
1785                        signals
1786                        placement
1787                        types.Args
1788                        immutables
1789                        body.constructor
1790                        { entries =
1791                            L.concatMap
1792                              (\(facet : Facet Events Errors State Imm) -> facet.entries)
1793                              body.facets
1794                        , problems =
1795                            L.concatMap
1796                              (\(facet : Facet Events Errors State Imm) -> facet.problems)
1797                              body.facets
1798                        }
1799                in  (([ component ],
1800                     { separated = ({=}, {=}), fits = (bounded, {=}), names = refl }) :
1801                       Contract)
1802        let composeWithLayout =
1803              \{State A : Type}
1804               (placement : Layout.Selection State)
1805               (types : { Args : ValueBoundary A })
1806               {owned : PlacementValid placement}
1807               (body :
1808                 { constructor : Constructor Events Errors State Imm A
1809                 , facets : List (Facet Events Errors State Imm)
1810                 }) ->
1811                let plan : Owners.Plan = Owners.select [ Owners.owner "" placement ] @owned
1812                in  composeWithBounds placement types plan.2.fits.1 body
1813
1814        -- Annotated by measurement: with an inferred type, the library check
1815        -- allocates 10.9 GB instead of 10.0 GB (2026-11-19).
1816        let compose
1817            : forall {State A : Type}
1818                     (types : { State : Codec.Of State, Args : ValueBoundary A })
1819                     {valid : Layout.Derived types.State}
1820                     {owned : PlacementValid (Layout.derive types.State @valid)}
1821                     (body :
1822                       { constructor : Constructor Events Errors State Imm A
1823                       , facets : List (Facet Events Errors State Imm)
1824                       })
1825              -> Contract
1826            = \{State} {A} types {valid} {owned} body ->
1827                composeWithLayout (Layout.derive types.State) { Args = types.Args } @owned body
1828        -- A native contract from a record of handlers typed by a validated
1829        -- interface. Unannotated by measurement: its type annotation added
1830        -- 0.9 GB to the library check and 1.25 GB to each `C.contract` user
1831        -- (2026-11-19).
1832        let handlersContract =
1833              \{State A : Type}
1834               {H : Solidity.Families -> Type}
1835               (state : Codec.Of State)
1836               (arguments : ValueBoundary A)
1837               (interface : Solidity.Interface H)
1838               {valid : Layout.Derived state}
1839               {owned : PlacementValid (Layout.derive state @valid)}
1840               (body :
1841                 { constructor : Constructor Events Errors State Imm A
1842                 , handlers : interface.1 Solidity.values (Handler Events Errors State Imm)
1843                 }) ->
1844                compose
1845                  @State
1846                  @A
1847                  { State = state, Args = arguments }
1848                  @valid
1849                  @owned
1850                  { constructor = body.constructor
1851                  , facets = [ handlersFacet @State @H interface body.handlers ]
1852                  }
1853        -- A native contract from a record of handlers typed by `Messages`:
1854        -- one entry per handler, named natively by its label.
1855        let contract =
1856              \{State : Type}
1857               {A H : Solidity.Families -> Type}
1858               (types :
1859                 { State : Codec.Of State
1860                 , Args : Reflect Solidity.types A
1861                 , Messages : Reflect @1 Solidity.types H
1862                 })
1863               {messagesValid : Solidity.InterfaceValid @H types.Messages} ->
1864                handlersContract
1865                  @State
1866                  @(A Solidity.values)
1867                  @H
1868                  types.State
1869                  (nativeCodec types.Args)
1870                  (Solidity.interface @H types.Messages @messagesValid)
1871
1872        let pure = \{State Args Result : Type} -> (Handler Events Errors State Imm Args Result).Pure
1873        let view = \{State Args Result : Type} -> (Handler Events Errors State Imm Args Result).View
1874        let write =
1875              \{State Args Result : Type} -> (Handler Events Errors State Imm Args Result).Write
1876        let payable =
1877              \{State Args Result : Type} -> (Handler Events Errors State Imm Args Result).Payable
1878        let monad =
1879              \{State : Type} mode -> E.monadFor (Access Events Errors State Imm mode) Word256 Bool
1880        let constructorMonad =
1881              \{State : Type} ->
1882                E.monadFor (Access Events Errors State unit E.Mode.Write) Word256 Bool
1883        let get
1884            : forall {State A : Type}
1885              -> Storage.Path State A
1886              -> BaseAction Events Errors State E.Mode.View A
1887            = \{State} {A} path m c access -> access.readState.get A path
1888        let set
1889            : forall {State A : Type}
1890              -> Storage.Path State A
1891              -> A
1892              -> BaseAction Events Errors State E.Mode.Write unit
1893            = \{State} {A} path value m c access -> access.writeState.set A path value
1894        let length
1895            : forall {State A : Type}
1896              -> Storage.Path State (List A)
1897              -> BaseAction Events Errors State E.Mode.View Word256
1898            = \{State} {A} path m c access -> access.readState.length A path
1899        let append
1900            : forall {State A : Type}
1901              -> Storage.Path State (List A)
1902              -> List A
1903              -> BaseAction Events Errors State E.Mode.Write unit
1904            = \{State} {A} path values m c access -> access.writeState.append A path values
1905        let storage =
1906              \{T : {} -> Type} (shape : Reflect @1 {=} T) ->
1907                let State = T {=}
1908                let Cell =
1909                      \(A : Type) ->
1910                        { read : BaseAction Events Errors State E.Mode.View A
1911                        , write : A -> BaseAction Events Errors State E.Mode.Write unit
1912                        }
1913                let cell =
1914                      \(A : Type) (path : Storage.Path State A) ->
1915                        { read = get @State @A path, write = set @State @A path }
1916                in  std:EVM/State/Bindings.scope
1917                      @T
1918                      shape
1919                      Cell
1920                      cell
1921                      (\(A Element : Type) ->
1922                         { whole : Cell (List A)
1923                         , at : Word256 -> Element
1924                         , length : BaseAction Events Errors State E.Mode.View Word256
1925                         , append : List A -> BaseAction Events Errors State E.Mode.Write unit
1926                         })
1927                      (\A Element path at ->
1928                         { whole = cell (List A) path
1929                         , at
1930                         , length = length @State @A path
1931                         , append = append @State @A path
1932                         })
1933        let context
1934            : Capability (\extra m -> { context : Context, ...extra m }) Context
1935            = \m c access -> c.monad.pure access.context
1936        let caller
1937            : Capability (\extra m -> { context : Context, ...extra m }) (Word 160)
1938            = \m c access -> c.monad.pure access.context.caller
1939        let address
1940            : Capability (\extra m -> { context : Context, ...extra m }) (Word 160)
1941            = \m c access -> c.monad.pure access.context.address
1942        let value
1943            : Capability (\extra m -> { context : Context, ...extra m }) Word256
1944            = \m c access -> c.monad.pure access.context.value
1945        let timestamp
1946            : Capability (\extra m -> { context : Context, ...extra m }) Word256
1947            = \m c access -> c.monad.pure access.context.timestamp
1948        let promotePure
1949            : forall {State A : Type}
1950              -> BaseAction Events Errors State E.Mode.Pure A
1951              -> BaseAction Events Errors State E.Mode.View A
1952            = \action -> action
1953        let promoteView
1954            : forall {State A : Type}
1955              -> BaseAction Events Errors State E.Mode.View A
1956              -> BaseAction Events Errors State E.Mode.Write A
1957            = \action -> action
1958
1959        let immutable
1960            : Capability (\extra m -> { immutable : Imm, ...extra m }) Imm
1961            = \m c access -> c.monad.pure access.immutable
1962
1963        let staticCall
1964            : forall {RemoteErrors A B : Type}
1965              -> Method RemoteErrors A B
1966              -> Word 160
1967              -> A
1968              -> Capability (\extra m -> { readCalls : ReadCalls m, ...extra m }) B
1969            = \{RemoteErrors} {A} {B} method to value m c access ->
1970                method
1971                  (\(e a b : Type) -> a -> m b)
1972                  (\name -> access.readCalls.invoke A B name to)
1973                  value
1974        let callValue
1975            : forall {RemoteErrors A B : Type}
1976              -> Method RemoteErrors A B
1977              -> Word 160
1978              -> Word256
1979              -> A
1980              -> Capability (\extra m -> { writeCalls : WriteCalls m, ...extra m }) B
1981            = \{RemoteErrors} {A} {B} method to amount value m c access ->
1982                method
1983                  (\(e a b : Type) -> a -> m b)
1984                  (\name -> access.writeCalls.invoke A B name to amount)
1985                  value
1986        let call
1987            : forall {RemoteErrors A B : Type}
1988              -> Method RemoteErrors A B
1989              -> Word 160
1990              -> A
1991              -> Capability (\extra m -> { writeCalls : WriteCalls m, ...extra m }) B
1992            = \method to -> callValue method to (Word/fromNatural 256 0)
1993        let staticCallOptional
1994            : forall {RemoteErrors A B : Type}
1995              -> Method RemoteErrors A B
1996              -> Word 160
1997              -> A
1998              -> Capability (\extra m -> { readCalls : ReadCalls m, ...extra m }) (Optional B)
1999            = \{RemoteErrors} {A} {B} method to value m c access ->
2000                method
2001                  (\(e a b : Type) -> a -> m (Optional b))
2002                  (\name -> access.readCalls.optional A B name to)
2003                  value
2004        let callValueOptional
2005            : forall {RemoteErrors A B : Type}
2006              -> Method RemoteErrors A B
2007              -> Word 160
2008              -> Word256
2009              -> A
2010              -> Capability (\extra m -> { writeCalls : WriteCalls m, ...extra m }) (Optional B)
2011            = \{RemoteErrors} {A} {B} method to amount value m c access ->
2012                method
2013                  (\(e a b : Type) -> a -> m (Optional b))
2014                  (\name -> access.writeCalls.optional A B name to amount)
2015                  value
2016        let callOptional
2017            : forall {RemoteErrors A B : Type}
2018              -> Method RemoteErrors A B
2019              -> Word 160
2020              -> A
2021              -> Capability (\extra m -> { writeCalls : WriteCalls m, ...extra m }) (Optional B)
2022            = \method to -> callValueOptional method to (Word/fromNatural 256 0)
2023
2024        let tryStaticCall
2025            : forall {RemoteErrors A B : Type}
2026              -> Method RemoteErrors A B
2027              -> Word 160
2028              -> A
2029              -> Capability
2030                   (\extra m -> { readCalls : ReadCalls m, ...extra m })
2031                   (Outcome RemoteErrors B)
2032            = \{RemoteErrors} {A} {B} method to value m c access ->
2033                method
2034                  (\(e a b : Type) -> a -> m (Outcome e b))
2035                  (\name -> access.readCalls.attempt RemoteErrors A B name to)
2036                  value
2037        let tryCallValue
2038            : forall {RemoteErrors A B : Type}
2039              -> Method RemoteErrors A B
2040              -> Word 160
2041              -> Word256
2042              -> A
2043              -> Capability
2044                   (\extra m -> { writeCalls : WriteCalls m, ...extra m })
2045                   (Outcome RemoteErrors B)
2046            = \{RemoteErrors} {A} {B} method to amount value m c access ->
2047                method
2048                  (\(e a b : Type) -> a -> m (Outcome e b))
2049                  (\name -> access.writeCalls.attempt RemoteErrors A B name to amount)
2050                  value
2051        let tryCall
2052            : forall {RemoteErrors A B : Type}
2053              -> Method RemoteErrors A B
2054              -> Word 160
2055              -> A
2056              -> Capability
2057                   (\extra m -> { writeCalls : WriteCalls m, ...extra m })
2058                   (Outcome RemoteErrors B)
2059            = \method to -> tryCallValue method to (Word/fromNatural 256 0)
2060
2061        let pay
2062            : Word 160
2063              -> Word256
2064              -> Capability (\extra m -> { writeCalls : WriteCalls m, ...extra m }) unit
2065            = \to amount m c access -> access.writeCalls.transfer to amount
2066        let withLock
2067            : forall {State A : Type}
2068              -> Word256
2069              -> Action Events Errors State Imm E.Mode.Write A
2070              -> Action Events Errors State Imm E.Mode.Write A
2071            = \{State} {A} key action {extra} m c access ->
2072                access.guard.run A key (action @extra m c access)
2073        let nonReentrant
2074            : forall {State A : Type}
2075              -> Action Events Errors State Imm E.Mode.Write A
2076              -> Action Events Errors State Imm E.Mode.Write A
2077            = \action -> withLock (Word/not (Word/fromNatural 256 0)) action
2078
2079        let emit
2080            : Events
2081              -> Capability (\extra m -> { signals : { emit : Events -> m unit }, ...extra m }) unit
2082            = \value m c access -> access.signals.emit value
2083        let abort
2084            : forall {A : Type} -> Capability (\extra m -> { ...extra m }) A
2085            = \m control access -> control.revert []
2086        let reject
2087            : forall {A : Type}
2088              -> Errors
2089              -> Capability
2090                   (\extra m -> { reject : forall (T : Type) -> Errors -> m T, ...extra m })
2091                   A
2092            = \{A} value m c access -> access.reject A value
2093
2094        let require
2095            : Bool
2096              -> Errors
2097              -> Capability
2098                   (\extra m -> { reject : forall (T : Type) -> Errors -> m T, ...extra m })
2099                   unit
2100            = \condition problem m control access ->
2101                if condition then control.monad.pure {=} else access.reject unit problem
2102        -- Turn an absent checked value into the caller's own typed error.
2103        let orReject
2104            : forall {A : Type}
2105              -> Errors
2106              -> Optional A
2107              -> Capability
2108                   (\extra m -> { reject : forall (T : Type) -> Errors -> m T, ...extra m })
2109                   A
2110            = \{A} problem result m control access ->
2111                std:Optional.fold (control.monad.pure @A) (access.reject A problem) result
2112
2113        in  { Contract
2114            , ownership
2115            , empty
2116            , regroup
2117            , join
2118            , joinWith
2119            , named
2120            , Bundle
2121            , instantiate
2122            , instanceAt
2123            , fixed
2124            , placements
2125            , assemble
2126            , AssemblyLayoutsValid
2127            , AssemblyOwnersValid
2128            , regroupBundles
2129            , regroupPlacements
2130            , Value = Solidity.Value
2131            , Events
2132            , Errors
2133            , Method
2134            , native
2135            , nativeIn
2136            , solidity
2137            , staticCall
2138            , call
2139            , callValue
2140            , pay
2141            , withLock
2142            , nonReentrant
2143            , staticCallOptional
2144            , callOptional
2145            , callValueOptional
2146            , tryStaticCall
2147            , tryCall
2148            , tryCallValue
2149            , contract
2150            , compose
2151            , composeWithLayout
2152            , composeWithBounds
2153            , PlacementValid
2154            , writing = O.writing
2155            , reading = O.reading
2156            , computing = O.computing
2157            , receiving = O.receiving
2158            , on = O.on
2159            , define
2160            , methods
2161            , use
2162            , Name = O.Name
2163            , nameProblems = O.nameProblems
2164            , Routes
2165            , Protocol
2166            , receive
2167            , fallback
2168            , nativeCodec
2169            , solidityCodec
2170            , Facet = \(State : Type) -> Facet Events Errors State Imm
2171            , Action = \(State : Type) mode A -> Action Events Errors State Imm mode A
2172            , Handler = \(State Args Result : Type) -> Handler Events Errors State Imm Args Result
2173            , Constructor = \(State Args : Type) -> Constructor Events Errors State Imm Args
2174            , Context
2175            , pure
2176            , view
2177            , write
2178            , payable
2179            , monad
2180            , constructorMonad
2181            , Mode = E.Mode
2182            , get
2183            , set
2184            , append
2185            , length
2186            , immutable
2187            , context
2188            , caller
2189            , address
2190            , value
2191            , timestamp
2192            , promotePure
2193            , promoteView
2194            , root = Storage.root
2195            , field = Storage.field
2196            , storage
2197            , item = Storage.item
2198            , key = Storage.key
2199            , emit
2200            , reject
2201            , require
2202            , orReject
2203            , abort
2204            }
2205
2206let configured =
2207      \{Events Errors : Type} (signals : Signals) ->
2208        let withImmutables =
2209              \{Imm : Type}
2210               (types : { Imm : Immutable.Of Imm })
2211               {valid : Immutable.Valid types.Imm} ->
2212                make @Events @Errors @Imm signals (Immutable.derive types.Imm @valid)
2213        in  withImmutables { Imm = {} } // { withImmutables }
2214
2215let withSignals =
2216      \{Events Errors : Solidity.Families -> Type}
2217       (types :
2218         { Events : Reflect Solidity.types Events
2219         , Errors : Reflect Solidity.types Errors
2220         }) ->
2221        configured
2222          @(Events Solidity.values)
2223          @(Errors Solidity.values)
2224          { events = Solidity.describe types.Events
2225          , errors = Solidity.describe types.Errors
2226          , problems = Codec.problems types.Events # Codec.problems types.Errors
2227          }
2228let withSoliditySignals =
2229      \{Events Errors : Solidity.Families -> Type}
2230       (types :
2231         { Events : Reflect Solidity.types Events
2232         , Errors : Reflect Solidity.types Errors
2233         }) ->
2234        configured
2235          @(Events Solidity.values)
2236          @(Errors Solidity.values)
2237          { events = Solidity.describe types.Events
2238          , errors = Solidity.describe types.Errors
2239          , problems = []
2240          }
2241in  withSignals { Events = <>, Errors = <> } // { withSignals, withSoliditySignals, lower }
Your result
Complete file: lib/EVM/Contract.omg · with imports