Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,47 @@ tx_receipt = contract.update_storage(args=["new_value"]).transact(
assert tx_execution_succeeded(tx_receipt)
```

### Fee Profiling

Generate a frontend-ready fee profile from the deploys and write transactions
executed during a gltest session:

```bash
gltest --fee-profile artifacts/fee-profile.json
gltest --fee-profile artifacts/fee-profile.json --fee-profile-headroom 1.5
```

`--fee-profile` writes JSON that can be passed verbatim as `suggestions` to
`createTransactionKit` from `@genlayer/transaction-kit`. The optional
`--fee-profile-headroom` multiplier defaults to `1.25`. Each value is the
maximum observed consumed fee across the session multiplied by headroom, rounded
up, and emitted as a decimal string.

```json
{
"version": 1,
"network": "localnet",
"measuredAt": "2026-06-10T12:00:00Z",
"deploy": {
"executionBudgetPerRound": "625000",
"totalMessageFees": "0"
},
"methods": {
"create_bet": {
"executionBudgetPerRound": "312500",
"totalMessageFees": "12500"
}
}
}
```

Fee profiling is currently measurable on Studio-based networks whose receipts
include consumed fee data. Testnet receipts do not expose consumed fees yet, and
direct/sim mode does not go through these receipt paths. Time-unit allocations
are not measurable from backend receipts, so `leaderTimeunitsAllocation` and
`validatorTimeunitsAllocation` are intentionally omitted; downstream presets or
network defaults should supply them.

### Assertions

```python
Expand Down
4 changes: 4 additions & 0 deletions gltest/contracts/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from genlayer_py.types import SimConfig
from typing import List, Any, Optional, Dict, Callable, Literal
from gltest_cli.config.general import get_general_config
from gltest.fees import maybe_record_fee_observation
from .contract_functions import ContractFunction
from .stats_collector import StatsCollector, SimulationConfig

Expand Down Expand Up @@ -146,6 +147,9 @@ def transact_method(
interval=actual_wait_interval,
retries=actual_wait_retries,
)
maybe_record_fee_observation(
kind="method", method_name=method_name, receipt=receipt
)
if wait_triggered_transactions:
triggered_transactions = receipt.get("triggered_transactions", [])
for triggered_transaction in triggered_transactions:
Expand Down
2 changes: 2 additions & 0 deletions gltest/contracts/contract_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from gltest.assertions import tx_execution_failed
from gltest.exceptions import DeploymentError
from gltest_cli.config.general import get_general_config
from gltest.fees import maybe_record_fee_observation
from gltest.utils import extract_contract_address
from gltest.types import TransactionContext

Expand Down Expand Up @@ -229,6 +230,7 @@ def deploy_contract_tx(
interval=actual_wait_interval,
retries=actual_wait_retries,
)
maybe_record_fee_observation(kind="deploy", receipt=tx_receipt)
if wait_triggered_transactions:
triggered_transactions = tx_receipt.get("triggered_transactions", [])
for triggered_transaction in triggered_transactions:
Expand Down
15 changes: 15 additions & 0 deletions gltest/fees/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from .profile import (
FeeProfileCollector,
fee_profile_enabled,
get_fee_profile_collector,
maybe_record_fee_observation,
reset_fee_profile_collector,
)

__all__ = [
"FeeProfileCollector",
"fee_profile_enabled",
"get_fee_profile_collector",
"maybe_record_fee_observation",
"reset_fee_profile_collector",
]
126 changes: 126 additions & 0 deletions gltest/fees/profile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import json
import math
from datetime import datetime, timezone
from decimal import Decimal
from pathlib import Path
from typing import Any, Dict, Optional

from gltest.logging import logger
from gltest_cli.config.general import get_general_config

FEE_KEYS = ("executionBudgetPerRound", "totalMessageFees")
CONSUMED_KEY_MAPPING = {
"executionBudgetPerRound": "executionConsumed",
"totalMessageFees": "messageFeesConsumed",
}


class FeeProfileCollector:
def __init__(self):
self._deploy: Dict[str, int] = {}
self._methods: Dict[str, Dict[str, int]] = {}
self._warned_malformed = False

def record_deploy(self, receipt: Dict[str, Any]) -> None:
observation = self._extract_observation(receipt)
if observation is not None:
self._record_max(self._deploy, observation)

def record_method(self, method_name: str, receipt: Dict[str, Any]) -> None:
observation = self._extract_observation(receipt)
if observation is not None:
method_values = self._methods.setdefault(method_name, {})
self._record_max(method_values, observation)

def build_profile(self, network: str, headroom: float) -> Dict[str, Any]:
profile: Dict[str, Any] = {
"version": 1,
"network": network,
"measuredAt": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
}
if self._deploy:
profile["deploy"] = self._apply_headroom(self._deploy, headroom)
profile["methods"] = {
method_name: self._apply_headroom(values, headroom)
for method_name, values in sorted(self._methods.items())
}
return profile

def write(self, path: Path, network: str, headroom: float) -> Dict[str, Any]:
profile = self.build_profile(network=network, headroom=headroom)
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(profile, indent=2) + "\n", encoding="utf-8")
return profile

def has_observations(self) -> bool:
return bool(self._deploy or self._methods)

def _extract_observation(
self, receipt: Optional[Dict[str, Any]]
) -> Optional[Dict[str, int]]:
try:
if not receipt:
return None
fees = receipt.get("fees")
if not fees:
return None
consumed = fees.get("consumed")
if not consumed:
return None
return {
output_key: int(consumed[consumed_key])
for output_key, consumed_key in CONSUMED_KEY_MAPPING.items()
}
except Exception as e:
if not self._warned_malformed:
logger.warning("Failed to record fee profile observation: %s", e)
self._warned_malformed = True
return None

@staticmethod
def _record_max(current: Dict[str, int], observation: Dict[str, int]) -> None:
for key in FEE_KEYS:
current[key] = max(current.get(key, 0), observation[key])

@staticmethod
def _apply_headroom(values: Dict[str, int], headroom: float) -> Dict[str, str]:
multiplier = Decimal(str(headroom))
# The backend only reports consumed fee amounts, not consumed time-unit
# allocations, so leader/validator allocation suggestions are omitted.
return {
key: str(math.ceil(Decimal(value) * multiplier))
for key, value in values.items()
}


_fee_profile_collector = FeeProfileCollector()


def get_fee_profile_collector() -> FeeProfileCollector:
return _fee_profile_collector


def reset_fee_profile_collector() -> FeeProfileCollector:
global _fee_profile_collector
_fee_profile_collector = FeeProfileCollector()
return _fee_profile_collector


def fee_profile_enabled() -> bool:
return get_general_config().get_fee_profile_path() is not None


def maybe_record_fee_observation(
kind: str, receipt: Dict[str, Any], method_name: Optional[str] = None
) -> None:
try:
if not fee_profile_enabled():
return
collector = get_fee_profile_collector()
if kind == "deploy":
collector.record_deploy(receipt)
elif method_name is not None:
collector.record_method(method_name, receipt)
except Exception as e:
logger.warning("Failed to record fee profile observation: %s", e)
2 changes: 1 addition & 1 deletion gltest_cli/config/constants.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from genlayer_py.chains.localnet import SIMULATOR_JSON_RPC_URL
from pathlib import Path


GLTEST_CONFIG_FILE = "gltest.config.yaml"
DEFAULT_NETWORK = "localnet"
PRECONFIGURED_NETWORKS = ["localnet", "studionet", "testnet_asimov", "testnet_bradbury"]
Expand All @@ -16,3 +15,4 @@
DEFAULT_WAIT_INTERVAL = 3000
DEFAULT_WAIT_RETRIES = 50
DEFAULT_LEADER_ONLY = False
DEFAULT_FEE_PROFILE_HEADROOM = 1.25
52 changes: 52 additions & 0 deletions gltest_cli/config/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
DEFAULT_LEADER_ONLY,
CHAINS,
)
from gltest.fees import get_fee_profile_collector, reset_fee_profile_collector


def pytest_addoption(parser):
Expand Down Expand Up @@ -75,6 +76,18 @@ def pytest_addoption(parser):
default=None,
help=f"Chain type (possible values: {', '.join(CHAINS)})",
)
group.addoption(
"--fee-profile",
action="store",
default=None,
help="Path to write a JSON fee profile for observed deploys and writes",
)
group.addoption(
"--fee-profile-headroom",
action="store",
default=None,
help="Multiplier applied to observed fee maxima in --fee-profile output",
)


def pytest_configure(config):
Expand Down Expand Up @@ -112,6 +125,8 @@ def pytest_configure(config):
network = config.getoption("--network")
leader_only = config.getoption("--leader-only")
chain_type = config.getoption("--chain-type")
fee_profile = config.getoption("--fee-profile")
fee_profile_headroom = config.getoption("--fee-profile-headroom")

plugin_config = PluginConfig()
plugin_config.contracts_dir = (
Expand All @@ -130,6 +145,14 @@ def pytest_configure(config):
plugin_config.network_name = network
plugin_config.leader_only = leader_only
plugin_config.chain_type = chain_type
plugin_config.fee_profile_path = (
Path(fee_profile) if fee_profile is not None else None
)
if fee_profile_headroom is not None:
parsed_headroom = float(fee_profile_headroom)
if parsed_headroom <= 0:
raise ValueError("--fee-profile-headroom must be greater than 0")
plugin_config.fee_profile_headroom = parsed_headroom

general_config.plugin_config = plugin_config
except Exception as e:
Expand All @@ -139,6 +162,7 @@ def pytest_configure(config):

def pytest_sessionstart(session):
try:
reset_fee_profile_collector()
general_config = get_general_config()
artifacts_dir = general_config.get_artifacts_dir()
if artifacts_dir and artifacts_dir.exists():
Expand Down Expand Up @@ -167,6 +191,10 @@ def pytest_sessionstart(session):
logger.info(
f" Default wait retries: {general_config.get_default_wait_retries()}"
)
if general_config.get_fee_profile_path() is not None:
logger.info(
f" Fee profile output: {general_config.get_fee_profile_path()}"
)

if (
general_config.get_leader_only()
Expand All @@ -182,6 +210,30 @@ def pytest_sessionstart(session):
pytest.exit("gltest session start error")


def pytest_sessionfinish(session, exitstatus):
try:
general_config = get_general_config()
fee_profile_path = general_config.get_fee_profile_path()
if fee_profile_path is None:
return

collector = get_fee_profile_collector()
profile = collector.write(
path=fee_profile_path,
network=general_config.get_network_name(),
headroom=general_config.get_fee_profile_headroom(),
)
logger.info(f"Wrote fee profile to {fee_profile_path}")
if not collector.has_observations():
logger.warning(
"Fee profile is empty; this backend may not expose consumed fee data on receipts yet"
)
elif "deploy" not in profile and not profile["methods"]:
logger.warning("Fee profile contains no deploy or method observations")
except Exception as e:
logger.error(f"Failed to write fee profile: {e}")


def pytest_runtest_setup(item):
_pytest_context.current_item = item

Expand Down
11 changes: 11 additions & 0 deletions gltest_cli/config/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
DEFAULT_WAIT_INTERVAL,
DEFAULT_WAIT_RETRIES,
DEFAULT_LEADER_ONLY,
DEFAULT_FEE_PROFILE_HEADROOM,
CHAINS,
)

Expand All @@ -22,6 +23,8 @@ class PluginConfig:
network_name: Optional[str] = None
leader_only: bool = False
chain_type: Optional[str] = None
fee_profile_path: Optional[Path] = None
fee_profile_headroom: Optional[float] = None


@dataclass
Expand Down Expand Up @@ -228,6 +231,14 @@ def get_leader_only(self) -> bool:
return network_config.leader_only
return DEFAULT_LEADER_ONLY

def get_fee_profile_path(self) -> Optional[Path]:
return self.plugin_config.fee_profile_path

def get_fee_profile_headroom(self) -> float:
if self.plugin_config.fee_profile_headroom is not None:
return self.plugin_config.fee_profile_headroom
return DEFAULT_FEE_PROFILE_HEADROOM

def check_local_rpc(self) -> bool:
return self.get_chain_type() == "localnet"

Expand Down
1 change: 1 addition & 0 deletions tests/gltest/fees/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Loading
Loading