Package genlayer.std#

gl#

Blockchain specific functionality, that won’t work without GenVM and reexports form genlayer.py provided for convenience

gl.calldata

Proxy to module genlayer.py.calldata

gl.advanced

Proxy to module gl..advanced

gl.wasi

Proxy to module gl.._wasi

gl.eth

Proxy to module genlayer.py.eth

class gl.Contract[source]#

Bases: object

Class that indicates main user contract

classmethod __get_schema__() str[source]#
Return type:

str

abstract __handle_undefined_method__(method_name: str, args: list[Any], kwargs: dict[str, Any])[source]#

Method that is called for no-method calls, must be either @gl.public.write or @gl.public.write.payable

__on_errored_message__()[source]#

Method that is called when emitted message with non-zero value failed. This method is not abstract to just receive value. It must be @gl.public.write.payable

abstract __receive__()[source]#

Method that is called for no-method transfers, must be @gl.public.write.payable

property address: Address#
Returns:

Address of this contract

property balance: u256#

Current balance of this contract

class gl.ContractAt[source]#

Bases: GenVMContractProxy

Provides a way to call view methods and send transactions to GenVM contracts

__init__(addr: Address)[source]#
address: Address#

Address to which this proxy points

property balance: u256#
emit(**data: Unpack[TransactionDataKwArgs])[source]#

Namespace with write message

Returns:

object supporting .name(*args, **kwargs) that emits a message and returns None

emit_transfer(**data: Unpack[TransactionDataKwArgs])[source]#

Method to emit a message that transfers native tokens

view()[source]#

Namespace with all view methods

Returns:

object supporting .name(*args, **kwargs) that calls a contract and returns its result (Any) or rises its Rollback

Note

supports name.lazy(*args, **kwargs) call version

class gl.Event[source]#

Bases: object

class TransferOccurredEvent(gl.Event):
        def __init__(self, from: Address, to: Address, /): ...

class TransferOccurredEvent(gl.Event):
        def __init__(self, from: Address, to: Address, /, **blob): ...
__init__()[source]#
emit() None#
indexed: tuple[str, ...]#

tuple of indexed arguments name in sorted order

name: str#

Event name. If not overridden it will be set to __name__

signature: str#

Event signature (built-in/main topic). Consists of name and indexed fields in parenthesis, sorted

Example: TransferOccurredEvent(from,to)

class gl.Lazy[source]#

Bases: Generic

Base class to support lazy evaluation

__init__(_eval: Callable[[], T])[source]#
get() T[source]#

Performs evaluation if necessary (only ones) and stores the result

Returns:

result of evaluating

Raises:

iff evaluation raised, this outcome is also cached, so subsequent calls will raise same exception

Return type:

T

class gl.MessageRawType[source]#

Bases: TypedDict

__optional_keys__ = frozenset({})#
__required_keys__ = frozenset({'chain_id', 'contract_address', 'datetime', 'entry_data', 'entry_kind', 'entry_stage_data', 'is_init', 'origin_address', 'sender_address', 'stack', 'value'})#
__total__ = True#
chain_id: u256#

Current chain ID

contract_address: Address#

Address of current Intelligent Contract

datetime: str#

Transaction datetime. For #get-schema it can be some predefined datetime

entry_data: bytes#
entry_kind: int#
entry_stage_data: Encodable#
is_init: bool#

True iff it is a deployment

origin_address: Address#

Entire transaction initiator

sender_address: Address#

Address of this call initiator

stack: list[Address]#

Stack of view method calls, excluding last (contract_address)

value: u256#
class gl.MessageType[source]#

Bases: NamedTuple

MessageType(contract_address, sender_address, origin_address, value, chain_id)

__getnewargs__()#

Return self as a plain tuple. Used by copy and pickle.

static __new__(_cls, contract_address: Address, sender_address: Address, origin_address: Address, value: u256, chain_id: u256)#

Create new instance of MessageType(contract_address, sender_address, origin_address, value, chain_id)

__repr__()#

Return a nicely formatted representation string

chain_id: u256#

Current chain ID

contract_address: Address#

Address of current Intelligent Contract

origin_address: Address#

Entire transaction initiator

sender_address: Address#

Address of this call initiator

value: u256#

Alias for field number 3

gl.contract_interface(_contr: GenVMContractDeclaration) Callable[[Address], GenVMContractProxy][source]#

This decorator produces an “interface” for other GenVM contracts. It has no semantical value, but can be used for auto completion and type checks

@gl.contract_interface
class MyContract:
  class View:
    def view_meth(self, i: int) -> int: ...

  class Write:
    def write_meth(self, i: int) -> None: ...
Return type:

Callable[[Address], GenVMContractProxy]

gl.deploy_contract(*, code: bytes, args: Sequence[Any] = [], kwargs: Mapping[str, Any] = {}, **data: Unpack[DeploymentTransactionDataKwArgs]) Address | None[source]#

Function for deploying new genvm contracts

Parameters:
  • code (bytes) – code (i.e. contents of a python file) of the contract

  • args (Sequence[Any]) – arguments to be encoded into calldata

  • kwargs (Mapping[str, Any]) – keyword arguments to be encoded into calldata

Returns:

address of new contract iff non-zero salt_nonce was provided

Return type:

Address | None

Note

Refer to consensus documentation for exact specification of

  • salt_nonce requirements and it’s effect on address

  • order of transactions

gl.eq_principle_prompt_comparative(fn: Callable[[], T], principle: str) T[source]#

Comparative equivalence principle that utilizes NLP for verifying that results are equivalent

Parameters:
  • fn (Callable[[], T]) – function that does all the job

  • principle (str) – principle with which equivalence will be evaluated in the validator (via performing NLP)

Return type:

T

See gl.advanced..run_nondet() for description of data transformations

Note

As leader results are encoded as calldata, format() is used for string representation. However, operating on strings by yourself is more safe in general

Note

supports .lazy() version, which will return Lazy

gl.eq_principle_prompt_non_comparative(fn: Callable[[], str], *, task: str, criteria: str) str[source]#

Non-comparative equivalence principle that must cover most common use cases

Both leader and validator finish their execution via NLP, that is used to perform task on input. Leader just executes this task, but the validator checks if task was performed with integrity. This principle is useful when task is subjective

See run_nondet() for description of data transformations

Note

supports .lazy() version, which will return Lazy

Return type:

str

gl.eq_principle_strict_eq(fn: Callable[[], T]) T[source]#

Comparative equivalence principle that checks for strict equality

Parameters:

fn (Callable[[], T]) – functions to perform an action

Return type:

T

See gl.advanced..run_nondet() for description of data transformations

Note

supports .lazy() version, which will return Lazy

gl.eth_contract(contr: ContractDeclaration) Callable[[Address], ContractProxy]#
Return type:

Callable[[Address], ContractProxy]

gl.exec_prompt(prompt: str, **config: Unpack[ExecPromptKwArgs]) str | dict[source]#

API to execute a prompt (perform NLP)

Parameters:
  • prompt (str) – prompt itself

  • **config (ExecPromptKwArgs) – configuration

Return type:

str

Note

supports .lazy() version, which will return Lazy

gl.get_webpage(url: str, **config: Unpack[GetWebpageKwArgs]) str | Image[source]#

API to get a webpage after rendering it

Parameters:
  • url (str) – url of website

  • **config (GetWebpageKwArgs) – configuration

Return type:

str

Note

supports .lazy() version, which will return Lazy

gl.message: MessageType = Ellipsis#

Represents fields from a transaction message that was sent

gl.message_raw: MessageRawType = Ellipsis#

Raw message as parsed json

gl.private(f)[source]#

Decorator that marks method as private. As all methods are private by default it does nothing.

class gl.public[source]#

Bases: object

static view(f)[source]#

Decorator that marks a contract method as a public view

write = <genlayer.std.annotations._write object>#

Decorator that marks a contract method as a public write. Has .payable

@gl.public.write
def foo(self) -> None: ...

@gl.public.write.payable
def bar(self) -> None: ...

@gl.public.write.min_gas(leader=100, validator=20).payable
def bar(self) -> None: ...
Return type:

T

gl.calldata#

This module is responsible for working with genvm calldata

Calldata natively supports following types:

  1. Primitive types:

    1. python built-in: bool, None, int, str, bytes

    2. Address() type

  2. Composite types:

    1. list (and any other collections.abc.Sequence)

    2. dict with str keys (and any other collections.abc.Mapping with str keys)

For full calldata specification see genvm repo

class gl.calldata.CalldataEncodable[source]#

Bases: object

Abstract class to support calldata encoding for custom types

Can be used to simplify code

abstract __to_calldata__() Encodable[source]#

Override this method to return calldata-compatible type

Warning

returning self may lead to an infinite loop or an exception

Return type:

Encodable

exception gl.calldata.DecodingError[source]#

Bases: ValueError

gl.calldata.decode(mem0: Buffer, *, memview2bytes: Callable[[memoryview], Any] = bytes) Decoded[source]#

Decodes calldata encoded bytes into python DSL

Out of composite types it will contain only dict and list

Return type:

Decoded

gl.calldata.encode(x: EncodableWithDefault, *, default: Callable[[EncodableWithDefault], Encodable] | None = None) bytes[source]#

Encodes python object into calldata bytes

Parameters:

default (Callable[[EncodableWithDefault], Encodable] | None) – function to be applied to each object recursively, it must return object encodable to calldata

Return type:

bytes

Warning

All composite types in the end are coerced to dict and list, so custom type information is not be preserved. Such types include:

  1. CalldataEncodable

  2. dataclasses

gl.calldata.to_str(d: Encodable) str[source]#

Transforms calldata DSL into human readable json-like format, should be used for debug purposes only

Return type:

str

gl.advanced#

This module provides some “advanced” features that can be used for optimizations

Warning

If you are using something “advanced” you must know what you do

exception gl.advanced.ContractError[source]#

Bases: Exception

Represents “Contract error” result of a contract that is passed to validator function of gl..run_nondet()

Validating leader output and sandbox invocation are only places where contract can “handle” contract error

__eq__(other)#

Return self==value.

__hash__ = None#
__init__(data: str) None#
__repr__()#

Return repr(self).

data: str#
class gl.advanced.ContractReturn[source]#

Bases: object

Represents a normal “Return” result of a contract that is passed to validator function of gl..run_nondet()

__eq__(other)#

Return self==value.

__hash__ = None#
__init__(data: Decoded) None#
__repr__()#

Return repr(self).

data: Decoded#
gl.advanced.emit_raw_event(name: str, indexed_fields_names: Sequence[str], blob: Encodable) None[source]#
gl.advanced.run_nondet(leader_fn: Callable[[], T], validator_fn: Callable[[ContractReturn | Rollback | ContractError], bool]) Lazy[source]#

Most generic user-friendly api to execute a non-deterministic block

Parameters:
Return type:

Lazy

Uses cloudpickle to pass a “function” to sub VM

Note

If validator_fn produces an error and leader_fn produces an error, executor itself will set result of this block to “agree” and fail entire contract with leader’s error. This is done because not all errors can be caught in code itself (i.e. exit). If this behavior is not desired, just fast return False for leader error result.

Warning

All sub-vm returns go through genlayer.py.calldata encoding

gl.advanced.sandbox(fn: Callable[[], T], *, allow_write_ops: bool = False) Lazy[source]#

Runs function in the sandbox

Return type:

Lazy

gl.advanced.validator_handle_rollbacks_and_errors_default(fn: Callable[[], Decoded], leaders_result: ContractReturn | Rollback | ContractError) tuple[Decoded, Decoded][source]#

Default function to handle rollbacks and contract errors

Errors and rollbacks are always checked for strict equality, which means that it’s user responsibility to dump least possible text in there

Returns:

ContractReturn data fields as (validator, leader)` iff both results are not errors/rollbacks

Return type:

tuple[Decoded, Decoded]

gl.eth#

This module is responsible for interactions with ghost/external contracts

class gl.eth.ContractDeclaration[source]#

Bases: Protocol, Generic

Interface for declaring interfaces of external contracts

View: type[TView]#
Write: type[TWrite]#
__init__(*args, **kwargs)#
class gl.eth.ContractProxy[source]#

Bases: Generic

__init__(address: Address, view_impl: Callable[[ContractProxy], TView], balance_impl: Callable[[ContractProxy], u256], send_impl: Callable[[ContractProxy, TransactionDataKwArgs], TWrite], transfer_impl: Callable[[ContractProxy, TransactionDataKwArgs], None])[source]#
address#
property balance: u256#
emit(**data: Unpack[TransactionDataKwArgs]) TWrite[source]#
Return type:

TWrite

emit_transfer(**data: Unpack[TransactionDataKwArgs]) None[source]#
view() TView[source]#
Return type:

TView

class gl.eth.InplaceTuple[source]#

Bases: object

This class indicates that tuple should be encoded/decoded in-place. Which means that even if it is dynamically sized, it is ignored. It is useful for encoding/decoding arguments and returns

tuple[InplaceTuple, str, u256]
class gl.eth.MethodEncoder[source]#

Bases: object

__init__(name: str, params: tuple[Any, ...], ret: type)[source]#
decode_ret(data: Buffer) Any[source]#
Return type:

Any

encode_call(args: tuple[Any, ...]) bytes[source]#
Return type:

bytes

gl.eth.decode(expected: Type, encoded: Buffer) T[source]#
Return type:

T

gl.eth.encode(params: Type, args: T) bytes[source]#
Return type:

bytes

gl.eth.selector_of(name: str, params: Type[tuple[Unpack[T]]]) bytes[source]#
Return type:

bytes

gl.eth.signature_of(name: str, params: Type[tuple[Unpack[T]]]) str[source]#

calculates signature that is used for making method selector

Return type:

str

gl.eth.type_name_of(t: type) str[source]#
Return type:

str

gl.wasi#

gl.wasi.get_balance(address: bytes) int[source]#
Return type:

int

gl.wasi.get_self_balance() int[source]#
Return type:

int

gl.wasi.gl_call(data: bytes) _Fd[source]#
Return type:

_Fd

gl.wasi.storage_read(slot: bytes, off: int, buf: Buffer) bytes[source]#
Return type:

bytes

gl.wasi.storage_write(slot: bytes, off: int, what: Buffer) bytes[source]#
Return type:

bytes