Package genlayer#
Top level#
GenLayer Python Standard Library
The recommended import pattern is:
import genlayer as gl
This provides access to:
Type aliases:
gl.u8,gl.u16, …,gl.u256,gl.Address, etc.Contract declaration via
gl.contract.ContractContract interaction via
gl.contract.interface,gl.contract.deploy,gl.contract.get_atMessage context via
gl.message.contract_address,gl.message.sender_address, etc.VM operations via
gl.vmNon-deterministic operations via
gl.nondetEquivalence principles via
gl.eq_principleEVM interaction via
gl.evmMethod decorators via
gl.publicandgl.private
- class genlayer.Lazy[source]#
Bases:
GenericBase class to support lazy evaluation
- __annotations__ = {'_eval': typing.Optional[typing.Callable[[], T]], '_exc': Exception | None, '_res': typing.Optional[T]}#
- classmethod __class_getitem__()#
Parameterizes a generic class.
At least, parameterizing a generic class is the main thing this method does. For example, for some generic class Foo, this is called when we do Foo[int] - there, with cls=Foo and params=int.
However, note that this method is also called when defining generic classes in the first place with class Foo[T]: ….
- classmethod __init_subclass__()#
Function to initialize subclasses.
- __module__ = 'genlayer.types'#
- __orig_bases__ = (typing.Generic[T],)#
- __parameters__ = (T,)#
- __slots__ = ('_eval', '_exc', '_res')#
- __type_params__ = (T,)#
- class genlayer.SizedArray[source]#
-
- __abstractmethods__ = frozenset({})#
- __annotations__ = {}#
- classmethod __class_getitem__()#
Parameterizes a generic class.
At least, parameterizing a generic class is the main thing this method does. For example, for some generic class Foo, this is called when we do Foo[int] - there, with cls=Foo and params=int.
However, note that this method is also called when defining generic classes in the first place with class Foo[T]: ….
- __dict__ = mappingproxy({'__module__': 'genlayer.types', '__type_params__': (T, S), '__len__': <function SizedArray.__len__>, '__getitem__': <function SizedArray.__getitem__>, '__iter__': <function SizedArray.__iter__>, '__orig_bases__': (<class 'typing.Protocol'>, typing.Generic[T, S]), '__dict__': <attribute '__dict__' of 'SizedArray' objects>, '__weakref__': <attribute '__weakref__' of 'SizedArray' objects>, '__doc__': None, '__parameters__': (T, S), '_is_protocol': True, '__subclasshook__': <classmethod(<function _proto_hook>)>, '__init__': <function _no_init_or_replace_init>, '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>, '__annotations__': {}, '__protocol_attrs__': {'__len__', '__iter__', '__getitem__'}, '_is_runtime_protocol': True, '__non_callable_proto_members__': set()})#
- __getitem__(index: SupportsIndex, /) T[source]#
- Return type:
T
- __init__(*args, **kwargs)#
- classmethod __init_subclass__(*args, **kwargs)#
Function to initialize subclasses.
- __module__ = 'genlayer.types'#
- __non_callable_proto_members__ = {}#
- __orig_bases__ = (<class 'typing.Protocol'>, typing.Generic[T, S])#
- __parameters__ = (T, S)#
- __protocol_attrs__ = {'__getitem__', '__iter__', '__len__'}#
- __slots__ = ()#
- classmethod __subclasshook__(other)#
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
- __type_params__ = (T, S)#
- __weakref__#
list of weak references to the object
- genlayer.private(f: T, /) T[source]#
Decorator that marks method as private. As all methods are private by default it does nothing.
- Return type:
T
- class genlayer.public[source]#
Bases:
object- __dict__ = mappingproxy({'__module__': 'genlayer._internal.annotations', 'view': <staticmethod(<function public.view>)>, 'write': <genlayer._internal.annotations._write object>, '__dict__': <attribute '__dict__' of 'public' objects>, '__weakref__': <attribute '__weakref__' of 'public' objects>, '__doc__': None, '__annotations__': {}})#
- __module__ = 'genlayer._internal.annotations'#
- __weakref__#
list of weak references to the object
- static view(f: T, /) T[source]#
Decorator that marks a contract method as a public view
- Return type:
T
- write = <genlayer._internal.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
Integer aliases#
It also has aliases for signed and unsigned integer types (such as u256) and a bigint alias that can be used in storage unlike regular int
contract#
Contract interaction and declaration module.
This module provides functionality for:
- Declaring main contracts with the Contract base class
- Creating type-safe interfaces with @interface
- Deploying contracts with deploy
- Getting contract proxies with get_at
- class genlayer.contract.Contract[source]#
Bases:
IAccountClass for declaring main GenVM contract.
This class must be inherited by user contracts to be deployable on GenVM. It provides essential contract functionality including balance access, address information, and storage proxying.
Only one
Contractsubclass is allowed per module. The class automatically generates storage management code and registers itself as the main contract.- Example:
>>> import genlayer as gl >>> >>> class MyContract(gl.contract.Contract): >>> def __init__(self, initial_value: int): >>> self.value = initial_value >>> >>> @gl.public.view >>> def get_value(self) -> int: >>> return self.value >>> >>> @gl.public.write >>> def set_value(self, new_value: int): >>> self.value = new_value
Warning
Only one Contract subclass is allowed per Python module. Attempting to define multiple Contract subclasses will raise a TypeError.
- class genlayer.contract.GenVMContractDeclaration[source]#
-
Protocol for defining contract interface declarations.
This protocol is used with the @gl.contract.interface decorator to create type-safe interfaces for interacting with specific contract types.
- Parameters:
TView – Type containing view method declarations
TWrite – Type containing write method declarations
- Example:
>>> @gl.contract.interface >>> class MyContract: >>> class View: >>> def get_balance(self, user: Address) -> u256: ... >>> def get_name(self) -> str: ... >>> >>> class Write: >>> def transfer(self, to: Address, amount: u256) -> None: ... >>> def mint(self, to: Address, amount: u256) -> None: ...
- View: type[TView]#
Class containing declarations for all view (read-only) methods.
All methods should be annotated with their expected return types.
- Write: type[TWrite]#
Class containing declarations for all write (state-modifying) methods.
All methods must have return type annotations of either None or be omitted.
- __init__(*args, **kwargs)#
- type genlayer.contract.ON = Literal['decided', 'finalized']#
When the transaction message should be applied:
'decided'or'finalized'
- class genlayer.contract.Proxy[source]#
Bases:
IAccount,Protocol,GenericGeneric proxy interface for interacting with deployed GenVM contracts.
This protocol defines the interface for contract proxies that provide type-safe access to view methods and write operations on deployed contracts.
- Parameters:
TView – Type representing available view methods
TSend – Type representing available write methods
- emit(*, value: u256 = 0, on: ON = 'finalized', use_balance: bool = False, fee_params: InternalMessageParams | None = None) TSend[source]#
Get a namespace for emitting write transactions.
- Parameters:
value (Annotated[int, StaticIntMeta(size=32, signed=False)]) – Amount of native tokens to transfer with the transaction
on (ON) – When the transaction message should be emitted to consensus
use_balance (bool) – Fund the message fee from this contract’s balance instead of the sender’s prefunded pool. Requires the
can_use_balance_for_message_feespermission andfee_params.fee_params (InternalMessageParams | None) – Fee parameters GenVM meters the balance-funded fee from; required when
use_balanceis set, ignored otherwise
- Returns:
Object providing access to write methods
- Return type:
TSend
Warning
Emitting transactions, especially with value transfers on
decidedmay lead to undesired results. Prefer to usefinalized(default)
- emit_transfer(value: u256, *, on: ON = 'finalized', use_balance: bool = False, fee_params: InternalMessageParams | None = None) None[source]#
Emit a simple value transfer without calling any method. Receiver may catch it with
Contract.__receive__()method, so users may need to supply non-zero gas- Parameters:
value (Annotated[int, StaticIntMeta(size=32, signed=False)]) – Amount of native tokens to transfer
on (ON) – When transaction message should be emitted to consensus
use_balance (bool) – Fund the message fee from this contract’s balance; see
emit()fee_params (InternalMessageParams | None) – Fee parameters for the balance-funded fee; required when
use_balanceis set
- Raises:
ValueError – If value is zero
- view(*, state: StorageView = StorageView.LATEST_DECIDED, catch_vm_error: Literal[False] = False) TView[source]#
- view(*, state: StorageView = StorageView.LATEST_DECIDED, catch_vm_error: Literal[True]) _CaughtViewMethods
- view(*, state: StorageView = StorageView.LATEST_DECIDED, catch_vm_error: bool) TView | '_CaughtViewMethods'
Get a namespace for calling view methods.
- Parameters:
state (StorageView) – Storage state to query against
catch_vm_error (bool) – return the callee’s VM error instead of re-raising it. A fatal one is never caught.
- Returns:
Object providing access to view methods
- Return type:
TView | _CaughtViewMethods
- class genlayer.contract.StorageView[source]#
Bases:
IntEnum- DEFAULT = 0#
- LATEST_DECIDED = 2#
- LATEST_FINALIZED = 1#
- __new__(value)#
- genlayer.contract.deploy(*, code: bytes, args: Sequence[Encodable] = [], kwargs: Mapping[str, Encodable] = {}, salt_nonce: Literal[0] = 0, value: Annotated[int, StaticIntMeta(size=32, signed=False)] = 0, on: ON = 'finalized', use_balance: bool = False, fee_params: InternalMessageParams | None = None) None[source]#
- genlayer.contract.deploy(*, code: bytes, args: Sequence[Encodable] = [], kwargs: Mapping[str, Encodable] = {}, salt_nonce: Annotated[int, StaticIntMeta(size=32, signed=False)], value: Annotated[int, StaticIntMeta(size=32, signed=False)] = 0, on: ON = 'finalized', use_balance: bool = False, fee_params: InternalMessageParams | None = None) Address
Deploy a new GenVM contract to the blockchain.
This function deploys a new contract using the provided
codeand constructor arguments. The deployment address can be deterministic (with a salt) or non-deterministic.- Parameters:
code (bytes) – Source code of the contract to deploy. It can be regular Python code. See Runners for more information
args (Sequence[Encodable]) – Positional arguments for the contract constructor
kwargs (Mapping[str, Encodable]) – Keyword arguments for the contract constructor
salt_nonce (Annotated[int, StaticIntMeta(size=32, signed=False)] | Literal[0]) – Salt for deterministic deployment. Use 0 for non-deterministic.
value (Annotated[int, StaticIntMeta(size=32, signed=False)]) – Amount of native tokens to send to the contract during deployment
on (ON) – When to execute the deployment (‘decided’ or ‘finalized’)
use_balance (bool) – Fund the deploy message fee from this contract’s balance; see
Proxy.emit()fee_params (InternalMessageParams | None) – Fee parameters for the balance-funded fee; required when
use_balanceis set
- Returns:
Contract address if salt_nonce != 0, None otherwise
- Return type:
Address | None
- Example:
>>> # Non-deterministic deployment >>> deploy( >>> code=contract_source_str.encode('utf-8'), >>> args=[initial_supply], >>> kwargs={"name": "MyToken", "symbol": "MTK"} >>> ) >>> >>> # Deterministic deployment >>> address = deploy( >>> code=contract_source_zip_as_bytes, >>> args=[initial_supply], >>> salt_nonce=12345, >>> value=1000 # Send 1000 native tokens >>> ) >>> print(f'Contract deployed at: {address}')
Note
- For deterministic deployments (salt_nonce != 0), the contract address
is computed using CREATE2 and is returned immediately
- For non-deterministic deployments (salt_nonce == 0), the address is
assigned by the consensus and not returned. Considering asynchronous nature of GenLayer consensus the address should not be predicted
The contract’s constructor will be called with the provided
argsandkwargs- Refer to consensus documentation for CREATE2 address derivation process and
details about transaction ordering
- genlayer.contract.get_at(address: Address, /) Proxy[source]#
Create a proxy object for interacting with a deployed GenVM contract.
This function returns a contract proxy that provides runtime access to the methods of a deployed contract without requiring type annotations describing its interface.
- Parameters:
address (Address) – Address of the deployed contract
- Returns:
ContractProxy object for interacting with the contract
- Return type:
- Example:
>>> addr = Address('0x1234567890abcdef...') >>> contract = get_at(addr) >>> result = contract.view().some_view_method(arg1, arg2) >>> contract.emit(value=100).some_write_method(arg1)
- genlayer.contract.interface(_declaration: GenVMContractDeclaration, /) Callable[[Address], Proxy][source]#
Decorator for creating type-safe contract interfaces.
This decorator creates a factory function that returns strongly-typed contract proxies, enabling IDE autocompletion and static type checking for contract interactions.
- Parameters:
_contr – Contract declaration class with View and Write nested classes
- Returns:
Factory function that creates typed contract proxies
- Return type:
- Example:
>>> @gl.contract.interface >>> class ERC20Contract: >>> class View: >>> def balance_of(self, owner: Address) -> u256: ... >>> def total_supply(self) -> u256: ... >>> >>> class Write: >>> def transfer(self, to: Address, amount: u256) -> None: ... >>> def approve(self, spender: Address, amount: u256) -> None: ... >>> >>> # Usage: >>> token = ERC20Contract(token_address) >>> balance = token.view().balance_of(user_address) # Fully typed! >>> token.emit().transfer(recipient, amount)
Note
This decorator provides no runtime functionality - it’s purely for type safety and developer experience. The actual contract interaction uses the same runtime mechanisms as get_at.
message#
- class genlayer.message.MessageRawType[source]#
Bases:
TypedDict- entry_kind: int#
- One of:
0forMAIN1forSANDBOX2forCONSENSUS_STAGE
See Startup Process for more details.
- genlayer.message.chain_id: Annotated[int, StaticIntMeta(size=32, signed=False)] = Ellipsis#
Current chain ID
- genlayer.message.entry_kind: int = Ellipsis#
One of:
0forMAIN1forSANDBOX2forCONSENSUS_STAGE
See Startup Process for more details.
- genlayer.message.entry_stage_data: Decoded = Ellipsis#
Decoded stage data (leader non-deterministic blocks outputs or
None)
- genlayer.message.raw: MessageRawType = Ellipsis#
The raw message dictionary as received from the VM
- genlayer.message.signer_address: Address = Ellipsis#
Externally-owned account that signed the transaction
chain#
- class genlayer.chain.Account[source]#
Bases:
IAccountClass for on-chain accounts.
- __init__(address: Address, /)[source]#
Get account at given address.
Can be used to emit transfer messages to any address, even if there is no contract deployed at it.
- Parameters:
address (Address) – target account address
- Returns:
account instance for the given address
- __non_callable_proto_members__ = {'address', 'balance'}#
- class genlayer.chain.Event[source]#
Bases:
objectclass TransferOccurredEvent(gl.chain.Event): def __init__(self, sender: Address, to: Address, /): ... class TransferOccurredEvent(gl.chain.Event): def __init__(self, sender: Address, to: Address, /, **blob): ...
- class genlayer.chain.IAccount[source]#
Bases:
ProtocolProtocol defining the interface for on-chain accounts. Be that a contract or an EoA.
- __init__(*args, **kwargs)#
- __non_callable_proto_members__ = {'address', 'balance'}#
- final class genlayer.chain.InternalMessageParams[source]#
Bases:
DataclassMixinFee parameters for a balance-funded internal message (
use_balance). GenVM meters the fee from these params (against the emitting contract’s balance) and that metered amount becomes the child transaction’sdeclaredBudget.Field names and layout mirror the executor’s calldata encoding exactly.
- Parameters:
leader_time_units_allocation – time units allocated to the leader per round
validator_time_units_allocation – time units allocated to each validator per round
execution_budget_per_round – gas budget granted to the child execution per round
rotations – per-round rotation allocations; must be non-empty (
appeal_roundsislen(rotations) - 1)max_price_gen_per_time_unit – per-time-unit GEN price cap; must be non-zero
storage_fee_max_gas_price – max gas price for the storage-fee component; must be non-zero
receipt_fee_max_gas_price – max gas price for the receipt-fee component; must be non-zero
- __delattr__(name)#
Implement delattr(self, name).
- __eq__(other)#
Return self==value.
- __final__ = True#
- __hash__()#
Return hash(self).
- __init__(leader_time_units_allocation: u256, validator_time_units_allocation: u256, execution_budget_per_round: u256, rotations: list[u256], max_price_gen_per_time_unit: u256, storage_fee_max_gas_price: u256, receipt_fee_max_gas_price: u256) None#
- __repr__()#
Return repr(self).
- __setattr__(name, value)#
Implement setattr(self, name, value).
vm#
Virtual Machine execution and sandbox module.
This module provides:
- Sandbox execution with spawn_sandbox and spawn_runner
- Non-deterministic execution with run_nondet_default and run_nondet
- Result types: Return, VMError, UserError, Result
- Event emission with Event
- type genlayer.vm.Result = Return | VMError | UserError#
Union type representing all possible outcomes from a VM operation.
- class genlayer.vm.Return[source]#
Bases:
GenericRepresents a successful return value from a VM operation.
- calldata: T#
Decoded return value from the VM execution
- class genlayer.vm.RunnerID#
Id of a runner:
name:hash,custom:<hash>,chain:<address>, orcontractfor this contract’s own onealias of
str
- class genlayer.vm.RunnerIDOps[source]#
Bases:
object- CONTRACT = 'contract'#
- type genlayer.vm.SandboxChangesOnError = Literal['inherit']#
Defines what happens to storage changes and emissions on non-return result of a sandbox
- exception genlayer.vm.UserError[source]#
Bases:
ExceptionRepresents an error that a user contract raised during execution in the VM.
- class genlayer.vm.VMError[source]#
Bases:
objectRepresents an error that occurred within the VM during execution.
It indicates user-caused error, such as OOM.
- genlayer.vm.get_timestamp() datetime[source]#
Returns the current timestamp as a timezone-aware
datetime.In deterministic mode it is the transaction timestamp; in non-deterministic mode it is the real wall-clock time.
- Return type:
- genlayer.vm.map_file(runner: RunnerID, path_in_runner: str, path_in_vfs: str) None[source]#
Maps a file from a runner into the VM filesystem at runtime.
Behaves the same as the
MapFilerunner action: ifpath_in_runnerends with/the whole directory subtree is mapped, otherwise a single file.Mapping into
/vm/is forbidden.
- genlayer.vm.register_runner(code: Buffer) RunnerID[source]#
Registers a runner archive at runtime and returns its
custom:<hash>id.The returned id can be referenced from
Depends/Withactions of other runners. Requires deterministic mode.
- genlayer.vm.run_nondet(leader_fn: Callable[[], T], validator_fn: Callable[[Result], bool], /, *, custom_runners: list[RunnerID] | None = None, catch_vm_error: Literal[False] = False) T[source]#
- genlayer.vm.run_nondet(leader_fn: Callable[[], T], validator_fn: Callable[[Result], bool], /, *, custom_runners: list[RunnerID] | None = None, catch_vm_error: Literal[True]) T | VMError
- genlayer.vm.run_nondet(leader_fn: Callable[[], T], validator_fn: Callable[[Result], bool], /, *, custom_runners: list[RunnerID] | None = None, catch_vm_error: bool) T | VMError
Executes a non-deterministic block with leader-validator consensus.
This is the most generic API for non-deterministic execution. The leader function runs as is, and each validator checks the result.
- Parameters:
leader_fn (Callable[[], T]) – Function executed by the leader node (must be serializable)
validator_fn (Callable[[Result], bool]) – Function that validates the leader’s result and returns bool
custom_runners (list[RunnerID] | None) –
custom:<hash>ids visible to the block;Nonegrants this VM’s entire set, a list grants exactly that subset of itcatch_vm_error (bool) – return the block’s VM error instead of re-raising it; a fatal one is never caught
- Returns:
The result from the leader (iff validation passes, otherwise VM will be terminated)
- Return type:
T | VMError
Warning
This function does not use extra sandbox for catching validator errors. Validator error will result in a
Disagreeerror in executor (same as if this function returnedFalse). Userun_nondet_default()instead if you want to catch and inspectvalidator_fnerrors, or use sandbox inside of it.Note
All sub-vm returns go through
genlayer.calldataencoding.- Example:
>>> def leader(): ... return os.urandom(1)[0] % 3 >>> def validator(result): ... return unpack_result(result) == 1 # agree in 33% of cases >>> value = gl.vm.run_nondet(leader, validator)
Note
supports
.lazy()version, which will returnLazy
- genlayer.vm.run_nondet_default(leader_fn: typing.Callable[[], T], validator_fn: typing.Callable[[Result[T]], bool], /, *, compare_user_errors: typing.Callable[[UserError, UserError], bool] = <function <lambda>>, compare_vm_errors: typing.Callable[[VMError, VMError], bool] = <function <lambda>>, custom_runners: list[RunnerID] | None = None, catch_vm_error: ~typing.Literal[False] = False) T[source]#
- genlayer.vm.run_nondet_default(leader_fn: typing.Callable[[], T], validator_fn: typing.Callable[[Result[T]], bool], /, *, compare_user_errors: typing.Callable[[UserError, UserError], bool] = <function <lambda>>, compare_vm_errors: typing.Callable[[VMError, VMError], bool] = <function <lambda>>, custom_runners: list[RunnerID] | None = None, catch_vm_error: ~typing.Literal[True]) T | VMError
- genlayer.vm.run_nondet_default(leader_fn: typing.Callable[[], T], validator_fn: typing.Callable[[Result[T]], bool], /, *, compare_user_errors: typing.Callable[[UserError, UserError], bool] = <function <lambda>>, compare_vm_errors: typing.Callable[[VMError, VMError], bool] = <function <lambda>>, custom_runners: list[RunnerID] | None = None, catch_vm_error: bool) T | VMError
Executes a non-deterministic block with comprehensive error handling.
This is the recommended API for custom non-deterministic execution. It provides safer error handling compared to
run_nondet()by running the validator in a sandbox and handling validator errors with provided functions with sensible defaults.- Parameters:
leader_fn (Callable[[], T]) – Function executed by the leader node
validator_fn (Callable[[Result], bool]) – Function that validates the leader’s result and runs in a sandbox
compare_user_errors (Callable[[UserError, UserError], bool]) – Function to compare UserError instances for equality
compare_vm_errors (Callable[[VMError, VMError], bool]) – Function to compare VMError instances for equality; the default compares only the public code (the part before the first `` # `` detail suffix), ignoring implementation-specific diagnostics
custom_runners (list[RunnerID] | None) –
custom:<hash>ids visible to the block;Nonegrants this VM’s entire set, a list grants exactly that subset of itcatch_vm_error (bool) – return the block’s VM error instead of re-raising it; a fatal one is never caught
- Returns:
The result from the leader if validation passes
- Return type:
T | VMError
Error handling: - If leader and validator both succeed: returns leader result - If leader fails and validator agrees: propagates leader error - If results don’t match: consensus fails
- Example:
>>> def leader() -> list[int]: ... return fetch_external_data() >>> def validator(result): ... if not isinstance(result, Return): ... return False ... my_data = leader() ... return ( ... numpy.linalg.norm(np.array(result.calldata) - np.array(my_data)) < 0.1 ... ) >>> value = run_nondet_default(leader, validator)
Note
supports
.lazy()version, which will returnLazy
- genlayer.vm.spawn_runner(runner: RunnerID, data: Buffer, /, *, allow_write_storage: bool = False, allow_send_messages: bool = False, custom_runners: list[RunnerID] | None = None, changes_on_error: SandboxChangesOnError = 'inherit') Return[Decoded] | VMError | UserError[source]#
Runs another runner in an isolated sub-VM, handing it
dataverbatim.This is the general form of
spawn_sandbox(): the child is whateverrunnernames, so it need not be Python, anddatais its entry payload rather than a pickled callable. Determinism of the spawned VM matches the determinism of the current VM.Each
allow_*flag grants the corresponding permission, but only if the current VM holds it as well.- Parameters:
runner (RunnerID) – runner id to execute: a
custom:<hash>/name:hash/chain:id, orcontractfor this contract’s own runnerdata (Buffer) – entry payload, passed to the child untouched
allow_write_storage (bool) – Whether to allow storage writes in the child
allow_send_messages (bool) – Whether to allow sending messages in the child
custom_runners (list[RunnerID] | None) –
custom:<hash>ids visible to the child;Nonegrants this VM’s entire set, a list grants exactly that subset of itchanges_on_error (SandboxChangesOnError) – see
SandboxChangesOnError
- Return type:
Both sides have to agree on what
datameans. Usegenlayer.calldatafor it unless the runner documents otherwise:- Example:
>>> answer = spawn_runner(rid, calldata.encode(30)) >>> calldata.decode(unpack_result(answer))
Note
supports
.lazy()version, which will returnLazy
- genlayer.vm.spawn_sandbox(fn: Callable[[], T], *, allow_write_storage: bool = False, allow_send_messages: bool = False, custom_runners: list[RunnerID] | None = None, changes_on_error: SandboxChangesOnError = 'inherit') Return | VMError | UserError[source]#
Runs a function of this contract in an isolated sandbox environment.
The function is executed in a separate VM instance with controlled permissions. This provides isolation and security for potentially unsafe operations. Determinism of spawned VM matches the determinism of the current VM.
Each
allow_*flag grants the corresponding permission to the sandbox, but only if the current VM holds it as well.To run a different runner – one that may not even be Python – use
spawn_runner(), which this is a thin wrapper over.- Parameters:
fn (Callable[[], T]) – Function to execute in the sandbox (must be serializable with cloudpickle)
allow_write_storage (bool) – Whether to allow storage writes in the sandbox
allow_send_messages (bool) – Whether to allow sending messages in the sandbox
custom_runners (list[RunnerID] | None) –
custom:<hash>ids visible to the sandbox;Nonegrants this VM’s entire set, a list grants exactly that subset of itchanges_on_error (SandboxChangesOnError) – see
SandboxChangesOnError
- Return type:
- Example:
>>> result = spawn_sandbox(lambda: risky_computation()) >>> safe_value = unpack_result(result)
Note
supports
.lazy()version, which will returnLazy
- genlayer.vm.unpack_result(res: Result, /) T[source]#
Extracts the successful result from a VM operation result.
- Parameters:
res (Result) – The result from a VM operation
- Returns:
The actual return value if successful
- Raises:
- Return type:
T
- Example:
>>> result = gl.vm.spawn_sandbox(lambda: 42) >>> value = unpack_result(result) # Returns 42 or re-raises on error
evm#
EVM (Ethereum Virtual Machine) contract interaction module.
This module provides functionality for interacting with EVM-compatible contracts:
- contract_interface: Decorator for creating type-safe EVM contract interfaces
- ABI encoding/decoding utilities
- Fixed-size byte types (bytes1 through bytes32)
- class genlayer.evm.Address[source]#
Bases:
objectRepresents GenLayer Address
- ZERO: ClassVar[Address] = Address("0x0000000000000000000000000000000000000000")#
The zero address (0x0000000000000000000000000000000000000000)
- __init__(val: str | Buffer | Address)[source]#
- Parameters:
val (str | Buffer | Address) – either a hex encoded address (that starts with ‘0x’), or base64 encoded address, or buffer of 20 bytes
Warning
checksum validation is not performed
- property as_b64: str#
>>> Address('0x5b38da6a701c568545dcfcb03fcb875f56beddc4').as_b64 'WzjaanAcVoVF3PywP8uHX1a+3cQ='
- Returns:
base64 representation of an address (most compact string)
- property as_bytes: bytes#
>>> Address('0x5b38da6a701c568545dcfcb03fcb875f56beddc4').as_bytes b'[8\xdajp\x1cV\x85E\xdc\xfc\xb0?\xcb\x87_V\xbe\xdd\xc4'
- Returns:
raw bytes of an address (most compact representation)
- property as_hex: str#
>>> Address('0x5b38da6a701c568545dcfcb03fcb875f56beddc4').as_hex '0x5B38Da6a701c568545dCfcB03FcB875f56beddC4'
- Returns:
checksum string representation
- property as_int: Annotated[int, StaticIntMeta(size=20, signed=False)]#
>>> Address('0x5b38da6a701c568545dcfcb03fcb875f56beddc4').as_int 520786028573371803640530888255888666801131675076 >>> hex(Address('0x5b38da6a701c568545dcfcb03fcb875f56beddc4').as_int) '0x5b38da6a701c568545dcfcb03fcb875f56beddc4'
- Returns:
int representation of an address (unsigned big endian)
- class genlayer.evm.ContractDeclaration[source]#
-
Interface for declaring interfaces of external contracts
- __init__(*args, **kwargs)#
- class genlayer.evm.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]#
- exception genlayer.evm.DecodingError[source]#
Bases:
ValueError
- class genlayer.evm.InplaceTuple[source]#
Bases:
objectThis 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 genlayer.evm.bytes1#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes10#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes11#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes12#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes13#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes14#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes15#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes16#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes17#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes18#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes19#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes2#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes20#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes21#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes22#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes23#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes24#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes25#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes26#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes27#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes28#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes29#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes3#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes30#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes31#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes32#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes4#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes5#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes6#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes7#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes8#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- class genlayer.evm.bytes9#
Fixed-size byte array. These types are used for encoding/decoding fixed-size byte arrays in EVM contracts
alias of
bytes
- genlayer.evm.contract_generator(generate_view: _EthGenerator, generate_send: _EthGenerator, balance_getter: Callable[[ContractProxy], u256], transfer: Callable[[ContractProxy, TransactionDataKwArgs], None], /)[source]#
nondet#
Non-deterministic operations module.
This module provides APIs for operations that may produce different results
across different nodes, such as:
- exec_prompt: Execute LLM prompts
- web: Web interaction functionality
- Image: Image dataclass for multimodal prompts
- class genlayer.nondet.Image[source]#
Bases:
objectImage(raw: bytes, pil: ‘PIL.Image.Image’)
- __eq__(other)#
Return self==value.
- __hash__ = None#
- __repr__()#
Return repr(self).
- pil: PIL.Image.Image#
- type genlayer.nondet.JSONValue = None | bool | int | float | str | list[JSONValue] | dict[str, JSONValue]#
- genlayer.nondet.exec_prompt(prompt: str, *, images: collections.abc.Sequence[bytes | Image] | None = None) str[source]#
- genlayer.nondet.exec_prompt(prompt: str, *, response_format: Literal['text'], images: collections.abc.Sequence[bytes | Image] | None = None) str
- genlayer.nondet.exec_prompt(prompt: str, *, response_format: Literal['json'], images: collections.abc.Sequence[bytes | Image] | None = None) JSONValue
API to execute a prompt (perform NLP)
- Parameters:
prompt (
str) – prompt itself**config (
ExecPromptKwArgs) – configuration
- Return type:
strorJSONValue
Note
supports
.lazy()version, which will returnLazy
nondet.web#
- class genlayer.nondet.web.Response[source]#
Bases:
objectResponse(status: int, headers: dict[str, bytes], body: bytes | None)
- __eq__(other)#
Return self==value.
- __hash__ = None#
- __repr__()#
Return repr(self).
- genlayer.nondet.web.delete(url: str, /, *, body: str | bytes | None = None, headers: Mapping[str, str | bytes] | None = None, sign: bool = False) Response[source]#
Note
supports
.lazy()version, which will returnLazy- Return type:
- genlayer.nondet.web.get(url: str, /, *, headers: Mapping[str, str | bytes] | None = None, sign: bool = False) Response[source]#
Note
supports
.lazy()version, which will returnLazy- Return type:
- genlayer.nondet.web.head(url: str, /, *, body: str | bytes | None = None, headers: Mapping[str, str | bytes] | None = None, sign: bool = False) Response[source]#
Note
supports
.lazy()version, which will returnLazy- Return type:
- genlayer.nondet.web.options(url: str, /, *, body: str | bytes | None = None, headers: Mapping[str, str | bytes] | None = None, sign: bool = False) Response[source]#
Note
supports
.lazy()version, which will returnLazy- Return type:
- genlayer.nondet.web.patch(url: str, /, *, body: str | bytes | None = None, headers: Mapping[str, str | bytes] | None = None, sign: bool = False) Response[source]#
Note
supports
.lazy()version, which will returnLazy- Return type:
- genlayer.nondet.web.post(url: str, /, *, body: str | bytes | None = None, headers: Mapping[str, str | bytes] | None = None, sign: bool = False) Response[source]#
Note
supports
.lazy()version, which will returnLazy- Return type:
- genlayer.nondet.web.put(url: str, /, *, body: str | bytes | None = None, headers: Mapping[str, str | bytes] | None = None, sign: bool = False) Response[source]#
Note
supports
.lazy()version, which will returnLazy- Return type:
- genlayer.nondet.web.render(url: str, /, *, wait_after_loaded: str | None = None, mode: Literal['text', 'html'] = 'text') str[source]#
- genlayer.nondet.web.render(url: str, /, *, wait_after_loaded: str | None = None, mode: Literal['screenshot']) Image
API to get a webpage after rendering it in a browser-like environment
- Parameters:
- Return type:
Note
supports
.lazy()version, which will returnLazy
- genlayer.nondet.web.request(url: str, /, *, method: Literal['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH'], body: str | bytes | None = None, headers: Mapping[str, str | bytes] | None = None, sign: bool = False) Response[source]#
Note
supports
.lazy()version, which will returnLazy- Return type:
eq_principle#
Equivalence principle module for consensus validation.
This module provides different equivalence principles for validating
non-deterministic operations across leader and validator nodes:
- strict_eq: Strict equality comparison
- prompt_comparative: NLP-based comparative validation
- prompt_non_comparative: NLP-based non-comparative validation
- genlayer.eq_principle.prompt_comparative(fn: Callable[[], T], principle: str, /) T[source]#
Comparative equivalence principle that utilizes NLP for verifying that results are equivalent
For validator: in case of non-
Returnresult infn, agreement will be decided bygenlayer.vm.run_nondet_default(), which executed validator wrapper function in a sandbox VM. If on the other hand leader reported an error, while our function execution is successful, the validator votesFalse.- Parameters:
- Return type:
T
See
genlayer.vm.run_nondet_default()for description of data transformationsNote
As leader results are encoded as calldata,
format()is used for string representation. However, operating on strings by yourself is more safe in generalWarning
See
genlayer.vm.run_nondet_default()for description of data transformationsNote
supports
.lazy()version, which will returnLazy
- genlayer.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
taskoninput. Leader just executes this task, but the validator checks if task was performed with integrity. This principle is useful when task is subjective. For instance, when you want to check if some text is a good summary of the input text.For validator: in case of non-
Returnresult infn, agreement will be decided bygenlayer.vm.run_nondet_default(), which executed validator wrapper function in a sandbox VM. If on the other hand leader reported an error, while our function execution is successful, the validator votesFalse.Note
supports
.lazy()version, which will returnLazy- Return type:
- genlayer.eq_principle.strict_eq(fn: Callable[[], T], /) T[source]#
Comparative equivalence principle that checks for strict equality
This function checks that VM result is of the same type and has the same value inside. It is the most performant equivalence principle, but it is also the most strict one.
- Parameters:
fn (Callable[[], T]) – function that provides result that will be validated
- Return type:
T
Warning
See
genlayer.vm.run_nondet_default()for description of data transformationsNote
supports
.lazy()version, which will returnLazy
calldata#
GenVM calldata encoding and decoding module.
This module provides:
encode: Encode Python objects to calldata bytesdecode: Decode calldata bytes to Python objectsto_str: Human-readable string representationCalldataEncodable: ABC for custom encodingType aliases:
Encodable,Decoded,EncodableWithDefault
Calldata natively supports following types:
Primitive types:
Composite types:
list(and any othercollections.abc.Sequence)dictwithstrkeys (and any othercollections.abc.Mappingwithstrkeys)
For full calldata specification see genvm repo
- class genlayer.calldata.CalldataEncodable[source]#
Bases:
objectAbstract class to support calldata encoding for custom types
Can be used to simplify code
- type genlayer.calldata.Decoded = None | int | Address | bool | str | bytes | list[Decoded] | dict[str, Decoded]#
Type that represents what type is coerced to after
decode . encode
- exception genlayer.calldata.DecodingError[source]#
Bases:
ValueError- __cause__#
exception cause
- __context__#
exception context
- __getattribute__(name, /)#
Return getattr(self, name).
- __init__(*args, **kwargs)#
- classmethod __new__(*args, **kwargs)#
- __reduce__()#
Helper for pickle.
- __repr__()#
Return repr(self).
- __setstate__()#
- __str__()#
Return str(self).
- __suppress_context__#
- __traceback__#
- add_note()#
Exception.add_note(note) – add a note to the exception
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- type genlayer.calldata.Encodable = None | int | str | Address | bool | bytes | Buffer | Raw | Sequence[Encodable] | Mapping[str, Encodable] | CalldataEncodable#
Type that can be encoded into calldata
- type genlayer.calldata.EncodableWithDefault = Encodable | T#
Type that can be encoded into calldata, provided
defaultfunctionT -> Encodable
- class genlayer.calldata.Raw[source]#
Bases:
objectAlready encoded calldata, spliced into the output verbatim
Deliberately not a dataclass: the default
encodeparameter transform expands any dataclass instance into a map, which is the one thing this wrapper must not becomeWarning
nothing checks that
datais well formed; a malformed blob produces calldata that fails to decode- data#
- genlayer.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
dictandlist- Return type:
- genlayer.calldata.encode(x: EncodableWithDefault, /, *, default: Callable[[EncodableWithDefault], Encodable] = encode_default_parameter) bytes[source]#
Encodes python object into calldata bytes
- Parameters:
default (Callable[[EncodableWithDefault], Encodable]) – function to be applied to each object recursively, it must return object encodable to calldata
- Return type:
storage#
Persistent storage module for GenLayer contracts.
This module provides:
- DynArray: Dynamic-length arrays
- Array: Fixed-size arrays
- TreeMap: Tree-based key-value storage
- allow: Decorator for storage-enabled classes
- inmem_allocate: In-memory allocation utility
- Root: Root storage class
- class genlayer.storage.Array[source]#
Bases:
Sequence,SizedArray,GenericConstantly sized array that can be persisted on the blockchain
- __contains__(value)#
- __getitem__(idx: SupportsIndex) T[source]#
- __getitem__(idx: slice) Array
Get element by index or a view over a sub-range by slice.
- Parameters:
idx (SupportsIndex | slice) – integer index or slice (step must be 1)
- Returns:
single element for int index,
Arrayview for slice- Raises:
IndexError – when integer index is out of range
ValueError – when slice step is not 1
- Return type:
T | Array
- __non_callable_proto_members__ = {}#
- __setitem__(idx: int, val: T) None[source]#
Set element at the given index.
- Parameters:
idx (int) – integer index (supports negative indexing)
val (T) – value to set
- Raises:
IndexError – when index is out of range
If the value’s storage encoding requires several writes and one fails, writes completed before the error remain visible.
- count(value) integer -- return number of occurrences of value#
- index(value[, start[, stop]]) integer -- return first index of value.#
Raises ValueError if the value is not present.
Supporting start and stop arguments is optional, but recommended.
- class genlayer.storage.Comparable[source]#
Bases:
ProtocolProtocol for types that support
<comparison.- __init__(*args, **kwargs)#
- __non_callable_proto_members__ = {}#
- class genlayer.storage.DynArray[source]#
Bases:
MutableSequence,GenericRepresents exponentially growing array (
listin python terms) that can be persisted on the blockchain- __contains__(value)#
- __delitem__(idx: int) None[source]#
- __delitem__(idx: slice) None
Delete element by index or range by slice.
- Parameters:
- Raises:
IndexError – when integer index is out of range
Elements are shifted before the length is reduced. If shifting fails, the original length and any shifts already completed remain visible.
- __getitem__(idx: int) T[source]#
- __getitem__(idx: slice) list[T]
Get element by index or sublist by slice.
- Parameters:
- Returns:
single element for int index, list of elements for slice
- Raises:
IndexError – when integer index is out of range
- Return type:
T | list[T]
- __iadd__(values)#
- __setitem__(idx: SupportsIndex, val: T) None[source]#
- __setitem__(idx: slice, val: collections.abc.Iterable[T]) None
Set element by index or replace a range by slice.
- Parameters:
idx (SupportsIndex | slice) – integer index or slice
val (T | Iterable) – value or sequence of values to assign
- Raises:
IndexError – when integer index is out of range
If assigning an element or one of several slice elements fails, earlier writes made by this operation remain visible. A failed extending slice assignment changes the length only after all new elements are written.
- append(value: T, /) None[source]#
Append value to the end of the array.
- Parameters:
value (T) – value to append
The length is increased before the value is written. If writing the value fails, the new element remains visible with whatever data its storage previously contained, or its zero-initialized value.
- append_new_get() T[source]#
Grow the array by one and return a reference to the new (uninitialized) element.
- Returns:
reference to the newly appended element
- Return type:
T
The new element is not initialized by this method. It exposes the value already present at its storage location, which is zero-initialized if the location has never been written.
- assign(arr: Sequence, /) Self[source]#
Same as
self[:] = arrbut more efficientException safety
On error list becomes empty
- Return type:
- clear() None[source]#
Remove all elements from the array.
Payload bytes remain in storage; later growth can expose them again.
- count(value) integer -- return number of occurrences of value#
- extend(values)#
S.extend(iterable) – extend sequence by appending elements from the iterable
- index(value[, start[, stop]]) integer -- return first index of value.#
Raises ValueError if the value is not present.
Supporting start and stop arguments is optional, but recommended.
- insert(index: SupportsIndex, value: T, /) None[source]#
Insert value before the given index.
- Parameters:
index (SupportsIndex) – position to insert at
value (T) – value to insert
Like
list.insert(), negative indices are normalized and indices outside the array are clamped to either end. The length is increased before elements are shifted, so a failed write leaves the increased length and any completed shifts visible.
- pop(index: SupportsIndex = -1, /) T[source]#
Remove and return an element.
- Parameters:
index (SupportsIndex) – element to remove (default last)
- Raises:
IndexError – when the array is empty or index is out of range
- Return type:
T
Storage-backed compound values are returned as views, not detached Python objects. Removing a non-last element shifts another element into the returned view’s location; reusing the removed last slot can likewise change a previously returned view.
- remove(value)#
S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.
- reverse()#
S.reverse() – reverse IN PLACE
- class genlayer.storage.Indirection[source]#
Bases:
GenericThis class provides ability to save data at its own slot. Occupies 1 byte to prevent collision.
- class genlayer.storage.Manager[source]#
Bases:
objectAbstract interface for storage backends.
- abstractmethod do_read(slot_id: bytes, off: int, len: int, /) bytes[source]#
Read raw bytes from storage.
- abstractmethod do_write(slot_id: bytes, off: int, what: Buffer, /)[source]#
Write raw bytes to storage.
- class genlayer.storage.Pickled[source]#
Bases:
GenericStorage wrapper that persists arbitrary Python objects via pickle serialization.
- __gl_allow_storage__ = True#
- load() T[source]#
Deserialize and return the stored value.
- Returns:
the unpickled object
- Return type:
T
- store(val: T, /) None[source]#
Serialize and persist the given value.
- Parameters:
val (T) – object to pickle and store
Serialization completes before storage is changed. If serialization fails, the previous value remains intact. A later storage-write failure may leave the byte payload only partially updated.
- class genlayer.storage.Root[source]#
Bases:
objectThis ABI is known and used by:
genvm
node
- MANAGER: ClassVar[Manager] = <genlayer.storage.core.InmemManager object>#
Manager instance for the storage.
It is set to an actual storage manager in the runtime, but can be overridden for testing purposes.
- __gl_allow_storage__ = True#
- __gl_storage_patched__ = True#
- __init__(*args, **kwargs)#
- property code#
contract code
- property code_slot#
Slot id the contract code is stored at, as a raw 32-byte value. If zero (the default), the code is read from the default
codeslot; otherwise it is read from the pointed-to slot (seechain:runner ids).
- property contract_instance#
Storage-backed field; failed compound assignment can leave it partially updated.
- static get() Root[source]#
Return the root storage instance.
- Returns:
singleton root object
- Return type:
- get_contract_instance(typ: Type, /) T[source]#
Return the contract instance deserialized as the given type.
- Parameters:
typ (Type) – storage-allowed type to deserialize into
- Returns:
contract instance
- Return type:
T
- get_permission(perm: Permissions, /) bool[source]#
Check whether a permission bit is set in the root
permissionsbitfield.- Parameters:
perm (Permissions) – permission to query
- Returns:
Trueiff the corresponding bit is set- Return type:
- get_vacant_slot() Slot[source]#
This slot can be used to store data without worrying about overwriting contract data. Useful for bootstrapping contract storage
- Return type:
- lock_default()[source]#
Lock the default set of slots (root, code, locked_slots, upgraders) to prevent modification after deployment.
Slots are appended in that order. If an append fails and the exception is caught, earlier appends and the failed append’s length change remain.
- property locked_slots#
Slot ids that can not be modified after deployment. Use
Slot.as_int()for conversion of Slot tointBy default it will be populated bycode,frozen_slots
- property major#
Major version of the GenVM contract expects
- property permissions#
Permission bitfield read by the executor at execution start. Bit
ncorresponds to thePermissionsmember whose value isn. Useget_permission()/set_permission()to access it.
- set_permission(perm: Permissions, value: bool, /) None[source]#
Set or clear a permission bit in the root
permissionsbitfield.- Parameters:
perm (Permissions) – permission to modify
value (bool) – whether to grant the permission
This method performs one fixed-size storage-field write.
- slot() Slot[source]#
Return the storage slot backing this root.
- Returns:
underlying storage slot
- Return type:
- property upgraders#
Storage-backed field; failed compound assignment can leave it partially updated.
- final class genlayer.storage.Slot[source]#
Bases:
objectHandle to a named region of storage, identified by a 32-byte address.
- __final__ = True#
- cast(t: Type, offset: int, /) T[source]#
Unsafely casts a storage slot to the given type. Use with caution.
- Return type:
T
- indirect(off: int, /) Slot[source]#
Derive a child slot by hashing this slot’s address with the given offset.
- class genlayer.storage.TreeMap[source]#
Bases:
MutableMapping,GenericRepresents a mapping from keys to values that can be persisted on the blockchain
- Tparam K:
must implement
genlayer.storage.tree_map.Comparableprotocol (“<” is needed) and be storage-allowed- Tparam V:
must be storage-allowed
- __delitem__(k: K)[source]#
Remove the entry with the given key.
- Parameters:
k (K) – key to remove
- Raises:
KeyError – when key is not found
Key comparisons finish before mutation starts. A later storage error can leave the tree only partially updated; storage errors must not be caught.
- __eq__(other)#
Return self==value.
- __getitem__(k: K) V[source]#
Return value for the given key.
- Parameters:
k (K) – key to look up
- Returns:
value associated with the key
- Raises:
KeyError – when key is not found
- Return type:
V
- __gl_allow_storage__ = True#
- __hash__ = None#
- __setitem__(k: K, v: V)[source]#
Set value for the given key, inserting if absent.
- Parameters:
k (K) – key
v (V) – value to associate with the key
Overwriting an entry has the value encoder’s exception safety. During an insertion, an encoding or storage error can leave an allocated node linked and partially initialized; such errors must not be caught.
- assign(arr: Mapping, /) Self[source]#
Clear the map and populate it from the given mapping.
The old map is cleared first. If iteration or insertion fails, entries inserted before the error remain visible.
- clear()[source]#
Remove all entries from the map.
The root is cleared before the backing arrays. If a storage write fails, the map may already appear empty while unreachable backing data remains.
- compute_if_absent(k: K, supplier: Callable[[], V], /) V[source]#
- Returns:
Value associated with k if it is present, otherwise get’s new value from the supplier, stores it at k and returns
- Return type:
V
The supplier is called before storage is mutated. If encoding or storing the supplied value fails, insertion can remain partially applied.
- get(k: K, /) V | None[source]#
- get(k: K, /, default: V | G) V | G
- Returns:
Value associated with k or default if there is no such value
- get_or_insert_default(k: K, /) V[source]#
Return value for key, inserting a default-initialized entry if absent.
- Parameters:
k (K) – key to look up or insert
- Returns:
value associated with the key
- Return type:
V
If insertion fails during a storage write, it can remain partially applied.
- items() ItemsView[source]#
Return a view of all (key, value) pairs in sorted order.
- Returns:
items view
- Return type:
- keys() a set-like object providing a view on D's keys#
- pop(k[, d]) v, remove specified key and return the corresponding value.#
If key is not found, d is returned if given, otherwise KeyError is raised.
- popitem() (k, v), remove and return some (key, value) pair#
as a 2-tuple; but raise KeyError if D is empty.
- setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D#
- update([E, ]**F) None. Update D from mapping/iterable E and F.#
If E present and has a .keys() method, does: for k in E.keys(): D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
- values() an object providing a view on D's values#
- class genlayer.storage.VLA[source]#
Bases:
PseudoSequence,GenericVariable Length Array. Can be used in pair with
Indirectionto save length at the same place as data. Can also be used in C language way. Occupies at least 4 bytes (for length)- __getitem__(idx: int) T[source]#
Get element at the given index.
- Parameters:
idx (int) – non-negative index
- Returns:
element at the index
- Raises:
IndexError – when index is out of range
- Return type:
T
- __init__(*args, **kwargs)#
- __setitem__(idx: int, val: T)[source]#
Set element at the given index.
- Parameters:
idx (int) – non-negative index
val (T) – value to set
- Raises:
IndexError – when index is out of range
If encoding requires several writes and one fails, writes completed before the error remain visible.
- append(val: T, /)[source]#
Append a value to the end of the array.
- Parameters:
val (T) – value to append
The value is written before the length is increased. If writing fails, the old length remains visible, although bytes beyond it may have changed.
- assign(val: Iterable, /)[source]#
Replace contents with elements from
val, truncating first.- Parameters:
val (Iterable) – sequence of values (or raw bytes for
VLA[u8])
For an iterable, the old contents are hidden first and successfully appended elements remain visible on error. For raw bytes, the new length is written before the payload, so an error may expose old or partial data.
- extend(val: Iterable, /)[source]#
Append all elements from
val.- Parameters:
val (Iterable) – sequence of values (or raw bytes for
VLA[u8])
Completed elements remain appended if iteration or a later write fails. For raw bytes, the payload is written before the length is increased.
- set_length(length: int, /)[source]#
Set the array length.
Growing the array exposes bytes already present after the old end, or zeroes for storage that has never been written. Elements are not initialized by this method.
- truncate(to: int = 0, /)[source]#
Truncate the array to the given length.
- Parameters:
to (int) – new length (default 0)
- Raises:
IndexError – when
toexceeds current length
Only the length is changed; truncated element bytes are retained and can be exposed again by
set_length().
- genlayer.storage.allow(cls: T) T[source]#
Marks class as allowed to be used within storage. Without this annotation, storage builder will raise an exception when trying to generate description for the class. This behavior is required to prevent accidental usage of classes that are not designed to be used in storage, because storage-generated class is modified and starts to behave differently from regular python class)
- Return type:
T
- genlayer.storage.inmem_allocate(t: Type, /, *init_args, **init_kwargs) T[source]#
Allocate a storage type in memory (useful for testing).
- Parameters:
t (Type) – storage-allowed type to allocate
init_args – positional arguments forwarded to
__init__init_kwargs – keyword arguments forwarded to
__init__
- Returns:
new in-memory instance of the given type
- Return type:
T
types#
Core type definitions for GenLayer contracts
- class genlayer.types.Address[source]#
Bases:
objectRepresents GenLayer Address
- ZERO: ClassVar[Address] = Address("0x0000000000000000000000000000000000000000")#
The zero address (0x0000000000000000000000000000000000000000)
- __format__(fmt: Literal['s', 'x', 'b64', 'cd', '']) str[source]#
Default object formatter.
Return str(self) if format_spec is empty. Raise TypeError otherwise.
- Return type:
- __init__(val: str | Buffer | Address)[source]#
- Parameters:
val (str | Buffer | Address) – either a hex encoded address (that starts with ‘0x’), or base64 encoded address, or buffer of 20 bytes
Warning
checksum validation is not performed
- property as_b64: str#
>>> Address('0x5b38da6a701c568545dcfcb03fcb875f56beddc4').as_b64 'WzjaanAcVoVF3PywP8uHX1a+3cQ='
- Returns:
base64 representation of an address (most compact string)
- property as_bytes: bytes#
>>> Address('0x5b38da6a701c568545dcfcb03fcb875f56beddc4').as_bytes b'[8\xdajp\x1cV\x85E\xdc\xfc\xb0?\xcb\x87_V\xbe\xdd\xc4'
- Returns:
raw bytes of an address (most compact representation)
- property as_hex: str#
>>> Address('0x5b38da6a701c568545dcfcb03fcb875f56beddc4').as_hex '0x5B38Da6a701c568545dCfcB03FcB875f56beddC4'
- Returns:
checksum string representation
- property as_int: Annotated[int, StaticIntMeta(size=20, signed=False)]#
>>> Address('0x5b38da6a701c568545dcfcb03fcb875f56beddc4').as_int 520786028573371803640530888255888666801131675076 >>> hex(Address('0x5b38da6a701c568545dcfcb03fcb875f56beddc4').as_int) '0x5b38da6a701c568545dcfcb03fcb875f56beddc4'
- Returns:
int representation of an address (unsigned big endian)
- class genlayer.types.KeccakHash[source]#
Bases:
objectThe Keccak hash function, with a hashlib-compatible interface.
- __init__(bitrate_bits: int, capacity_bits: int, output_bits: int)[source]#
Create a new Keccak hash instance.
- block_size#
- copy() KeccakHash[source]#
Return a copy of this hash object.
- Return type:
- digest() bytes[source]#
Return the digest of the data fed so far.
- Returns:
hash digest as bytes
- Return type:
- digest_size#
- hexdigest() str[source]#
Return the hex-encoded digest of the data fed so far.
- Returns:
hash digest as hex string
- Return type:
- static preset(bitrate_bits, capacity_bits, output_bits)[source]#
Returns a factory function for the given bitrate, sponge capacity and output length. The function accepts an optional initial input, ala hashlib.
- sponge#
- class genlayer.types.SizedArray[source]#
-
- __getitem__(index: SupportsIndex, /) T[source]#
- Return type:
T
- __init__(*args, **kwargs)#
- __non_callable_proto_members__ = {}#
- genlayer.types.bigint#
Just an alias for
int, it is introduced to prevent accidental use of low-performance big integers in the storealias of
Annotated[int, ‘bigint’]
- genlayer.types.i104#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=13, signed=True)]
- genlayer.types.i112#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=14, signed=True)]
- genlayer.types.i120#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=15, signed=True)]
- genlayer.types.i128#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=16, signed=True)]
- genlayer.types.i136#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=17, signed=True)]
- genlayer.types.i144#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=18, signed=True)]
- genlayer.types.i152#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=19, signed=True)]
- genlayer.types.i16#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=2, signed=True)]
- genlayer.types.i160#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=20, signed=True)]
- genlayer.types.i168#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=21, signed=True)]
- genlayer.types.i176#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=22, signed=True)]
- genlayer.types.i184#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=23, signed=True)]
- genlayer.types.i192#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=24, signed=True)]
- genlayer.types.i200#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=25, signed=True)]
- genlayer.types.i208#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=26, signed=True)]
- genlayer.types.i216#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=27, signed=True)]
- genlayer.types.i224#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=28, signed=True)]
- genlayer.types.i232#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=29, signed=True)]
- genlayer.types.i24#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=3, signed=True)]
- genlayer.types.i240#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=30, signed=True)]
- genlayer.types.i248#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=31, signed=True)]
- genlayer.types.i256#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=32, signed=True)]
- genlayer.types.i32#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=4, signed=True)]
- genlayer.types.i40#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=5, signed=True)]
- genlayer.types.i48#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=6, signed=True)]
- genlayer.types.i56#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=7, signed=True)]
- genlayer.types.i64#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=8, signed=True)]
- genlayer.types.i72#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=9, signed=True)]
- genlayer.types.i8#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=1, signed=True)]
- genlayer.types.i80#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=10, signed=True)]
- genlayer.types.i88#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=11, signed=True)]
- genlayer.types.i96#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=12, signed=True)]
- genlayer.types.u104#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=13, signed=False)]
- genlayer.types.u112#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=14, signed=False)]
- genlayer.types.u120#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=15, signed=False)]
- genlayer.types.u128#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=16, signed=False)]
- genlayer.types.u136#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=17, signed=False)]
- genlayer.types.u144#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=18, signed=False)]
- genlayer.types.u152#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=19, signed=False)]
- genlayer.types.u16#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=2, signed=False)]
- genlayer.types.u160#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=20, signed=False)]
- genlayer.types.u168#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=21, signed=False)]
- genlayer.types.u176#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=22, signed=False)]
- genlayer.types.u184#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=23, signed=False)]
- genlayer.types.u192#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=24, signed=False)]
- genlayer.types.u200#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=25, signed=False)]
- genlayer.types.u208#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=26, signed=False)]
- genlayer.types.u216#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=27, signed=False)]
- genlayer.types.u224#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=28, signed=False)]
- genlayer.types.u232#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=29, signed=False)]
- genlayer.types.u24#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=3, signed=False)]
- genlayer.types.u240#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=30, signed=False)]
- genlayer.types.u248#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=31, signed=False)]
- genlayer.types.u256#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=32, signed=False)]
- genlayer.types.u32#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=4, signed=False)]
- genlayer.types.u40#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=5, signed=False)]
- genlayer.types.u48#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=6, signed=False)]
- genlayer.types.u56#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=7, signed=False)]
- genlayer.types.u64#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=8, signed=False)]
- genlayer.types.u72#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=9, signed=False)]
- genlayer.types.u8#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=1, signed=False)]
- genlayer.types.u80#
Fixed size integer alias for storage
alias of
Annotated[int, StaticIntMeta(size=10, signed=False)]