From 66a1d03597a35ddfd5d797fc3914b0a559ad2a65 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 25 Apr 2026 11:02:21 +0000 Subject: [PATCH 01/14] Release v1.1.7 [skip ci] --- CHANGELOG.md | 2 ++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ce7579..e509475 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ +## 1.1.7 (2026-04-25) + ## 1.1.6 (2026-04-24) ## 1.1.5 (2026-04-24) diff --git a/package-lock.json b/package-lock.json index cac205c..a30fba9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "genlayer-js", - "version": "1.1.6", + "version": "1.1.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "genlayer-js", - "version": "1.1.6", + "version": "1.1.7", "license": "MIT", "dependencies": { "eslint-plugin-import": "^2.30.0", diff --git a/package.json b/package.json index 49990ab..6cd3532 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "genlayer-js", "type": "module", - "version": "1.1.6", + "version": "1.1.7", "description": "GenLayer JavaScript SDK", "main": "dist/index.js", "types": "dist/index.d.ts", From ae4805e09cf1626e2bfcc0b2e6e1b2639f8431cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Rabenda?= <99408377+rrabenda@users.noreply.github.com> Date: Wed, 6 May 2026 14:52:43 +0200 Subject: [PATCH 02/14] ci: scope down release/sync-docs to dedicated GitHub Apps (#168) Replace the over-privileged shared CI bot with two dedicated, minimally scoped GitHub Apps gated behind protected environments. Mirrors the same change in genlayer-testing-suite#78 and genlayer-cli#297. - publish.yml: rename environment npm -> Publish, switch from tibdex/github-app-token@v1 (archived) to actions/create-github-app-token@v3 with vars.PUBLISH_CI_APP_CLIENT_ID + secrets.PUBLISH_CI_APP_KEY. - sync-docs.yml: bump create-github-app-token to @v3, switch to client-id, gate behind the Sync-docs environment with vars.DOCS_SYNC_APP_CLIENT_ID + secrets.DOCS_SYNC_APP_KEY. Each App should be installed only on the repos it needs (Publish: this repo only; Sync-docs: this repo + genlayer-docs) with Contents: read & write as the only permission. --- .github/workflows/publish.yml | 8 ++++---- .github/workflows/sync-docs.yml | 5 +++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 35096d0..359ba26 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -13,14 +13,14 @@ permissions: jobs: release: runs-on: ubuntu-latest - environment: npm + environment: Publish steps: - name: Get CI Bot Token - uses: tibdex/github-app-token@v1 + uses: actions/create-github-app-token@v3 id: ci_bot_token with: - app_id: ${{ secrets.CI_BOT_APP_ID }} - private_key: ${{ secrets.CI_BOT_SECRET }} + client-id: ${{ vars.PUBLISH_CI_APP_CLIENT_ID }} + private-key: ${{ secrets.PUBLISH_CI_APP_KEY }} - name: Checkout source code uses: actions/checkout@v4 diff --git a/.github/workflows/sync-docs.yml b/.github/workflows/sync-docs.yml index 5e1e4e8..5ff3ec7 100644 --- a/.github/workflows/sync-docs.yml +++ b/.github/workflows/sync-docs.yml @@ -9,6 +9,7 @@ jobs: generate-and-sync: if: github.event_name != 'release' || !contains(github.event.release.tag_name, '-') runs-on: ubuntu-latest + environment: Sync-docs permissions: contents: read steps: @@ -38,9 +39,9 @@ jobs: - name: Generate docs repo token id: app-token - uses: actions/create-github-app-token@v1 + uses: actions/create-github-app-token@v3 with: - app-id: ${{ vars.DOCS_SYNC_APP_ID }} + client-id: ${{ vars.DOCS_SYNC_APP_CLIENT_ID }} private-key: ${{ secrets.DOCS_SYNC_APP_KEY }} repositories: genlayer-docs From a76bec395aaa927720ee0ce364899a64044dd43e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edgars=20Nem=C5=A1e?= Date: Wed, 6 May 2026 21:37:44 +0100 Subject: [PATCH 03/14] fix(ci): add trigger comment to publish workflow (#170) No-op patch release to verify the publish pipeline end-to-end after the env scope-down (#168) and npm trusted publisher update. --- .github/workflows/publish.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 359ba26..ebefed2 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,5 +1,6 @@ name: Release & Publish Package to NPM +# Triggered on push to main or manual dispatch. on: workflow_dispatch: push: From 4303db00c428d57c6d8e5b04a75043ea42d4b0e7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Wed, 6 May 2026 23:13:43 +0000 Subject: [PATCH 04/14] Release v1.1.8 [skip ci] --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e509475..f8643e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ +## 1.1.8 (2026-05-06) + + +### Bug Fixes + +* **ci:** add trigger comment to publish workflow ([#170](https://github.com/genlayerlabs/genlayer-js/issues/170)) ([a76bec3](https://github.com/genlayerlabs/genlayer-js/commit/a76bec395aaa927720ee0ce364899a64044dd43e)), closes [#168](https://github.com/genlayerlabs/genlayer-js/issues/168) + ## 1.1.7 (2026-04-25) ## 1.1.6 (2026-04-24) diff --git a/package-lock.json b/package-lock.json index a30fba9..42fbf8e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "genlayer-js", - "version": "1.1.7", + "version": "1.1.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "genlayer-js", - "version": "1.1.7", + "version": "1.1.8", "license": "MIT", "dependencies": { "eslint-plugin-import": "^2.30.0", diff --git a/package.json b/package.json index 6cd3532..0447029 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "genlayer-js", "type": "module", - "version": "1.1.7", + "version": "1.1.8", "description": "GenLayer JavaScript SDK", "main": "dist/index.js", "types": "dist/index.d.ts", From e3b12fb8ce942471aa2173351892ae37d0927c9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edgars=20Nem=C5=A1e?= Date: Wed, 20 May 2026 22:11:53 +0100 Subject: [PATCH 05/14] feat: branch-per-major release model (#172) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Aligns this repo with genlayer-node + genvm: branches per major (v1 today; v2 / v2-dev when fees lands), no main, deliberate releases via script + skill. What changes: - publish.yml fires on `push: tags v*` instead of `push: main`. The workflow no longer bumps versions — it just sanity-checks that the tag matches package.json, builds, publishes to npm, and creates the GitHub Release. No commits back to the branch. - scripts/release.sh is the new release entry point. Pre-flight checks: on a v branch, clean tree, in sync with origin, latest CI green. Refuses major bumps without --allow-major (those need a new branch in this model). Then runs release-it with an explicit version to bump package.json, prepend CHANGELOG.md, commit, tag, push — but with npm/github plugins disabled so the dev machine doesn't need npm auth and the GH release is cut by CI from the tag. - .claude/skills/release/SKILL.md documents the flow for Claude: when to use it, what to confirm with the user, what to refuse, and the roll-back path (deprecate, never unpublish blind). - CONTRIBUTING.md explains the branch model + points at the skill. - npm run release → ./scripts/release.sh so the convenience script routes through pre-flight checks (the previous `release-it --ci` invocation bypassed every guard). - .github/e2e-track on this branch points at runner track v0.5 (current stable). v2-dev (when it exists) will point at v0.6-dev. Why kill auto-bump: - Twice landed accidental majors when a BREAKING CHANGE footer in a PR body triggered the conventional-commit bump algorithm — once on this repo (0.28.7 → 1.0.0), once on genlayer-testing-suite (yanked v1/v2 tags). The whatBump cap mitigated future jumps but didn't address the underlying issue: shipping a release shouldn't be a side-effect of merging a PR. - The new flow puts a human checkpoint between "code lands" and "users get it" without losing the bump-and-tag automation. Follow-up (separate PRs): - After this lands: switch default branch on github.com from main to v1, then delete origin/main. - Same shape applied to genlayer-py, genlayer-cli, genlayer-testing-suite, genlayer-explorer (per their existing major). - Runner matrix updates: matrix/v0.5.yaml tooling refs switch from tag pins to branch pins (genlayer-js: v1). --- .claude/skills/release/SKILL.md | 99 +++++++++++++++++++++ .github/e2e-track | 2 +- .github/workflows/publish.yml | 68 ++++++++++----- CONTRIBUTING.md | 22 +++++ package.json | 2 +- scripts/release.sh | 148 ++++++++++++++++++++++++++++++++ 6 files changed, 316 insertions(+), 25 deletions(-) create mode 100644 .claude/skills/release/SKILL.md create mode 100755 scripts/release.sh diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md new file mode 100644 index 0000000..dc916d8 --- /dev/null +++ b/.claude/skills/release/SKILL.md @@ -0,0 +1,99 @@ +--- +name: release +description: Cut a release of genlayer-js. Bumps version, updates CHANGELOG, tags, pushes — CI then publishes to npm and creates the GitHub Release. Use when a human asks "release v1.x.y" or "ship a new version". +--- + +# Release skill — genlayer-js + +This repo follows a branch-per-major release model. There is no auto-bump on push. A release happens when a human (or you on their behalf) runs `scripts/release.sh` on the target stable branch. + +## When to use this skill + +User asks anything like: +- "release v1.2.0" +- "ship a patch" +- "cut a new minor" +- "tag the latest fix as a release" + +If they ask "publish to npm directly" — refuse and point at this flow. The repo doesn't have an unprotected npm push path; the tag is the only release entry point. + +## What this repo's release model expects + +- Branches are named after the major they ship: `v1` (current stable), `v2-dev` / `v2` (next major when it exists). +- Tags live within those branches: `v1.1.9`, `v1.2.0`, ... +- A major bump means **cutting a new branch**, not tagging on the current one. The release script refuses major bumps unless `--allow-major` is passed. +- `CHANGELOG.md` is updated in the release commit (release-it via `@release-it/conventional-changelog`). +- `publish.yml` fires on the tag push and does the npm publish + GitHub Release. + +## Steps + +1. **Confirm intent with the user.** + - Which version? If unspecified, ask whether it's patch / minor / explicit. + - Which branch? Default `v1`. If they're shipping a back-port to an older major, the branch is `v`. + +2. **Switch to the target branch + sync.** + ```bash + git checkout v1 + git pull --ff-only origin v1 + ``` + If the working tree isn't clean, stop and surface what's there — never stash and ship. + +3. **Verify the head is shippable.** + - Latest CI run on this commit is green (the release script also checks, but check first so you don't half-run the script): + ```bash + gh run list --branch v1 --commit "$(git rev-parse HEAD)" --limit 1 + ``` + - Inspect the last few commits since the previous tag for surprises: + ```bash + git log "$(git describe --tags --abbrev=0)..HEAD" --oneline + ``` + - If anything looks unexpected (e.g. an in-flight refactor accidentally landed), surface it and wait for the user's call. + +4. **Run the release script.** + ```bash + scripts/release.sh # or patch / minor + ``` + It will: bump `package.json`, prepend `CHANGELOG.md`, commit `Release v [skip ci]`, tag `v`, and push both the branch commit and the tag. It will NOT publish to npm — CI handles that. + +5. **Watch the publish workflow.** + ```bash + gh run watch + ``` + or + ```bash + gh run list --workflow=publish.yml --limit 1 + ``` + If `publish.yml` fails (typical causes: tag/package.json mismatch — caused by hand-editing `package.json` outside the script; `NPM_TOKEN` rotated; npm provenance check), report the failure verbatim and stop. Do not retry blindly. + +6. **Confirm on npm.** + ```bash + npm view genlayer-js dist-tags + ``` + The `latest` tag should show the new version. Report back to the user with the version and the GitHub Release URL. + +## Things to refuse + +- **Major bump on the current branch** without `--allow-major`. The right move for a major is a new branch + new track in the runner matrix (separate workflow). +- **Releasing from `main`** — `main` is retired. If somehow `main` exists locally, the script will refuse; explain why. +- **Hand-editing `package.json` to bump the version** instead of running the script. The script keeps `package.json`, the CHANGELOG entry, the commit message, and the tag in lockstep; doing it by hand drifts them. +- **Publishing a tag where `publish.yml` failed** — fix the underlying issue, re-cut the release (delete the bad tag both locally and on origin, re-run the script). Don't manually `npm publish`. + +## Roll-back + +If a release shipped but is broken: + +1. **Don't unpublish from npm** unless someone with elevated permissions has assessed the impact — npm unpublish has a 72-hour window and a deprecation path that consumers prefer. +2. **Deprecate the bad version**: + ```bash + npm deprecate "genlayer-js@" "broken release; install or later" + ``` +3. **Ship a follow-up patch** via the same flow (`scripts/release.sh patch`). + +## Why no auto-bump? + +The previous flow auto-bumped on every push to `main`, which: +- Twice landed accidental major bumps (`0.28.7 → 1.0.0`, `v1-prerelease → v2-yanked` in testing-suite) because conventional-commit `BREAKING CHANGE` notes are too easy to drop into a PR. +- Tied "shipping a release" to "merging a PR", which conflated two decisions. +- Left no human checkpoint between "code lands" and "users get it". + +Manual + scripted is the trade we made: small overhead per release in exchange for never shipping a surprise. diff --git a/.github/e2e-track b/.github/e2e-track index ba2906d..83b4ac5 100644 --- a/.github/e2e-track +++ b/.github/e2e-track @@ -1 +1 @@ -main +v0.5 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ebefed2..340aa70 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,37 +1,28 @@ -name: Release & Publish Package to NPM +name: Publish Package to NPM -# Triggered on push to main or manual dispatch. +# Tag-driven publish. The release is cut by a human (or Claude via the +# release skill) running scripts/release.sh on the target stable branch +# — that script bumps package.json, writes the CHANGELOG, commits, tags +# vX.Y.Z, and pushes both the branch commit and the tag. This workflow +# fires on the tag push, builds, sanity-checks the tag matches +# package.json, and publishes to npm. It never bumps or tags by itself. on: workflow_dispatch: push: - branches: - - main + tags: + - "v*" permissions: contents: write id-token: write jobs: - release: + publish: runs-on: ubuntu-latest environment: Publish steps: - - name: Get CI Bot Token - uses: actions/create-github-app-token@v3 - id: ci_bot_token - with: - client-id: ${{ vars.PUBLISH_CI_APP_CLIENT_ID }} - private-key: ${{ secrets.PUBLISH_CI_APP_KEY }} - - - name: Checkout source code + - name: Checkout tag uses: actions/checkout@v4 - with: - token: ${{ steps.ci_bot_token.outputs.token }} - - - name: Initialize Git User - run: | - git config --global user.email "github-actions[bot]@genlayer.com" - git config --global user.name "github-actions[bot]" - uses: actions/setup-node@v4 with: @@ -40,7 +31,38 @@ jobs: - run: npm ci - - name: Release - run: npm run release + - name: Verify tag matches package.json version + run: | + TAG_VERSION="${GITHUB_REF_NAME#v}" + PKG_VERSION="$(node -p "require('./package.json').version")" + if [ "$TAG_VERSION" != "$PKG_VERSION" ]; then + echo "Tag ($TAG_VERSION) and package.json ($PKG_VERSION) disagree — refusing to publish." >&2 + echo "Re-cut the release via scripts/release.sh so the tag and the committed version match." >&2 + exit 1 + fi + echo "Tag $GITHUB_REF_NAME matches package.json $PKG_VERSION." + + - run: npm run build + + - name: Publish to npm + run: npm publish --provenance --access public env: - GITHUB_TOKEN: ${{ steps.ci_bot_token.outputs.token }} \ No newline at end of file + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + - name: Create GitHub Release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # Pull the changelog block for this version out of CHANGELOG.md. + # Falls back to a generic body if the section isn't found. + NOTES="$(awk -v ver="$GITHUB_REF_NAME" ' + $0 ~ "^## \\[?" substr(ver, 2) {capture=1; next} + capture && /^## / {exit} + capture {print} + ' CHANGELOG.md)" + if [ -z "$NOTES" ]; then + NOTES="Release $GITHUB_REF_NAME" + fi + gh release create "$GITHUB_REF_NAME" \ + --title "$GITHUB_REF_NAME" \ + --notes "$NOTES" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0f4344f..160a7e2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,6 +28,28 @@ Have ideas for new features or use cases? We're eager to hear them! But first: - Ensure you have the SDK installed to explore existing use cases. - After familiarizing yourself with the SDK, contribute your unique use case and share your ideas in our [Discord channel](https://discord.gg/8Jm4v89VAu). +## Branch model + +This repo uses a branch-per-major release model. There is no `main`. + +- **`v1`** — current stable major. PRs for bug fixes / non-breaking features target this branch. Releases are cut from here (see `scripts/release.sh`). +- **`v-dev`** — when a major bump is in progress (e.g. `v2-dev`), this branch is open for the new major's work. PRs introducing breaking changes target this branch, not `v1`. +- **Older majors** (`v0`, etc.) stay on the repo for back-ports and security patches. Default branch on github.com is whichever major is current stable. + +When you fork or clone, the default branch is `v1` today. If you have a `main` branch from a previous checkout, delete it locally: + +```sh +git checkout v1 +git branch -D main +git remote prune origin +``` + +## Releases + +Releases are deliberate, not automatic. `scripts/release.sh` bumps the version, updates `CHANGELOG.md`, commits, tags, and pushes; CI takes over from the tag push and publishes to npm. See `.claude/skills/release/SKILL.md` for the full flow. + +If you're using Claude Code, ask it to "release a patch" (or "release v1.2.0") and the skill walks through the pre-flight checks before invoking the script. + ### Bug fixing and Feature development #### 1. Set yourself up to start coding diff --git a/package.json b/package.json index 0447029..23c6e3a 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,7 @@ "test:watch": "vitest --watch", "lint": "eslint . --fix --ext .ts", "check:chains": "node scripts/check-chains-drift.mjs", - "release": "release-it --ci", + "release": "./scripts/release.sh", "docs": "node scripts/generate-api-docs.mjs" }, "exports": { diff --git a/scripts/release.sh b/scripts/release.sh new file mode 100755 index 0000000..0e81522 --- /dev/null +++ b/scripts/release.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# Cut a release on the current stable branch. +# +# Bumps package.json, prepends CHANGELOG.md, commits, tags vX.Y.Z, and +# pushes both the branch commit and the tag. publish.yml takes over from +# the tag push (build → npm publish → GitHub Release). +# +# Releases are deliberate. There is no auto-bump on push; only this +# script (or `npm version` invoked equivalently) is supposed to create +# release tags. Run from the major branch you want to ship a release on +# (e.g. v1 for v1.x.y, v0.18 for v0.18.x once that branch exists). +# +# Usage: +# scripts/release.sh # explicit semver — recommended +# scripts/release.sh patch # 1.1.8 → 1.1.9 +# scripts/release.sh minor # 1.1.8 → 1.2.0 +# scripts/release.sh major # 1.1.8 → 2.0.0 (refuses unless --allow-major) +# scripts/release.sh --allow-major +# +# Pre-flight (each check refuses to proceed on failure): +# - On a v branch (refuses on main / feature branches) +# - Working tree clean +# - Local HEAD matches origin/ (no unpushed work, no missed pulls) +# - Latest CI run on HEAD is green (so we don't ship a broken main) +# - Major bumps require --allow-major OR explicit X.0.0 with --allow-major +# since major = new branch in this repo's release model + +set -euo pipefail + +ALLOW_MAJOR=0 +if [ "${1:-}" = "--allow-major" ]; then + ALLOW_MAJOR=1 + shift +fi + +VERSION_ARG="${1:-}" +if [ -z "$VERSION_ARG" ]; then + echo "Usage: $0 [--allow-major] |patch|minor|major" >&2 + exit 2 +fi + +repo_root="$(git rev-parse --show-toplevel)" +cd "$repo_root" + +branch="$(git rev-parse --abbrev-ref HEAD)" +if ! [[ "$branch" =~ ^v[0-9]+(\.[0-9]+)?(-dev)?$ ]]; then + cat >&2 <&2 + exit 1 +fi + +git fetch --tags origin "$branch" +local_sha="$(git rev-parse HEAD)" +remote_sha="$(git rev-parse "origin/$branch")" +if [ "$local_sha" != "$remote_sha" ]; then + cat >&2 </dev/null 2>&1; then + status="$(gh run list --branch "$branch" --commit "$local_sha" --limit 1 --json conclusion --jq '.[0].conclusion' 2>/dev/null || echo "")" + case "$status" in + success) ;; + "" ) + echo "Warning: no CI run found for $local_sha on $branch. Continuing anyway." >&2 + ;; + *) + echo "Latest CI on $branch@$local_sha is '$status' (not success). Refusing to release a red commit." >&2 + exit 1 + ;; + esac +fi + +current_version="$(node -p "require('./package.json').version")" + +# Resolve to a concrete X.Y.Z so the major-bump guard can compare. +case "$VERSION_ARG" in + major|minor|patch) + next_version="$(node -e " + const semver = require('semver'); + const cur = require('./package.json').version; + const inc = '$VERSION_ARG'; + const out = semver.inc(cur, inc); + if (!out) { console.error('semver.inc failed for', cur, inc); process.exit(1); } + console.log(out); + ")" + ;; + *) + next_version="$VERSION_ARG" + ;; +esac + +# Validate semver shape early so we don't half-bump. +if ! node -e "if (!require('semver').valid('$next_version')) process.exit(1)"; then + echo "Not a valid semver: $next_version" >&2 + exit 2 +fi + +cur_major="${current_version%%.*}" +next_major="${next_version%%.*}" +if [ "$next_major" != "$cur_major" ] && [ "$ALLOW_MAJOR" -ne 1 ]; then + cat >&2 < Date: Fri, 22 May 2026 13:43:37 +0100 Subject: [PATCH 06/14] fix: run CI on v1 branch (#173) * fix: run CI on v1 branch * fix: sync testnet consensus abi --- .github/workflows/chains-drift.yml | 4 ++-- .github/workflows/test.yml | 4 ++-- src/chains/testnetAsimov.ts | 25 +++++++++++++++++++++++++ src/chains/testnetBradbury.ts | 25 +++++++++++++++++++++++++ 4 files changed, 54 insertions(+), 4 deletions(-) diff --git a/.github/workflows/chains-drift.yml b/.github/workflows/chains-drift.yml index a97289e..55a1d22 100644 --- a/.github/workflows/chains-drift.yml +++ b/.github/workflows/chains-drift.yml @@ -3,10 +3,10 @@ name: Chains Drift Check on: pull_request: branches: - - main + - v1 push: branches: - - main + - v1 schedule: # Daily at 07:00 UTC. Catches upstream contract deployments even when no # PRs are open against the SDK. diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 696828a..1b215a1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -3,10 +3,10 @@ name: Run Tests on: push: branches: - - main + - v1 pull_request: branches: - - main + - v1 jobs: test: diff --git a/src/chains/testnetAsimov.ts b/src/chains/testnetAsimov.ts index fcdd1bc..b0b089a 100644 --- a/src/chains/testnetAsimov.ts +++ b/src/chains/testnetAsimov.ts @@ -411,6 +411,31 @@ const CONSENSUS_MAIN_CONTRACT = { "name": "NewTransaction", "type": "event" }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "txId", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "firstAnnouncedAt", + "type": "uint256" + } + ], + "name": "NewTransactionAlreadyAnnounced", + "type": "event" + }, { "anonymous": false, "inputs": [ diff --git a/src/chains/testnetBradbury.ts b/src/chains/testnetBradbury.ts index 68ec7cc..f6b0e00 100644 --- a/src/chains/testnetBradbury.ts +++ b/src/chains/testnetBradbury.ts @@ -411,6 +411,31 @@ const CONSENSUS_MAIN_CONTRACT = { "name": "NewTransaction", "type": "event" }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "txId", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "firstAnnouncedAt", + "type": "uint256" + } + ], + "name": "NewTransactionAlreadyAnnounced", + "type": "event" + }, { "anonymous": false, "inputs": [ From 71175f751bf8359d68b066cf5a0b684b5d213da5 Mon Sep 17 00:00:00 2001 From: "ci-core-e2e-runner[bot]" <263344042+ci-core-e2e-runner[bot]@users.noreply.github.com> Date: Tue, 26 May 2026 20:24:15 +0100 Subject: [PATCH 07/14] ci(workflows): sync e2e.yml from genlayer-e2e (#174) Co-authored-by: ci-core-e2e-runner[bot] <263344042+ci-core-e2e-runner[bot]@users.noreply.github.com> --- .github/workflows/e2e.yml | 930 ++++++++++++++++++++++++++++---------- 1 file changed, 685 insertions(+), 245 deletions(-) diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 509f1ea..efc2849 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -1,292 +1,732 @@ -# Reference caller workflow for any component repo (genlayer-node, -# -consensus, -js, -py, -cli, -explorer, -testing-suite). Copy to -# .github/workflows/e2e.yml in the target repo. +# Source-of-truth E2E pipeline workflow. # -# Triggers: -# 1. /run-e2e comment by a member/collaborator → runs against stable -# track by default, optional track selection via `/run-e2e ` -# or `/run-e2e `. -# 2. PR opened / synchronized / reopened / ready_for_review — AUTO-GATE. -# Runs E2E as a required check. Track defaults to `main`. -# 3. PR approved — auto-runs E2E (dedup if a prior run covered the SHA). +# This file is BOTH: +# - The workflow that runs in this repo (genlayer-e2e) for dispatch / +# local testing. +# - The file synced verbatim to every consumer repo as +# .github/workflows/e2e.yml (sync-template.yaml owns the fan-out). # -# Track = which branch of ci-core-e2e-runner to run against. `main` is the -# stable track; `v0.6-dev` etc. are in-flight tracks. Each track ships -# its own matrix/ file, tests, and resolver. +# Consumers don't carry a separate thin caller — keeping the consumer's +# workflow file BYTE-IDENTICAL to this one means: +# - Sidebar tiles stay flat: `acknowledge / register`, `plan / action`, +# `build / discover`, `genlayer-core / shard ... / e2e`, `result` — +# no wrapper-job prefix. A consumer-side thin caller would force +# ` /` on every inner tile (see #386 follow-up where +# deleting e2e-harness.yml restored the flat layout). +# - Behavior changes ship via one sync PR per consumer, instead of +# each consumer hand-editing their wrapper. +# +# Two trigger paths: +# - `issue_comment` — PR comment `/run-e2e [profile] [track] [scope]` +# on the consumer's repo. The acknowledge job's `if:` gates on +# author-association so only members/owners/collaborators can fire +# the pipeline. +# - `workflow_dispatch` — manual / debug in this repo (UI dropdowns). +# Acknowledge is skipped (no PR comment context); plan/build/waves +# run with workflow_dispatch input values. +# +# All internal `uses:` references are cross-repo +# (`genlayerlabs/genlayer-e2e/.github/workflows/X.yml@main`) so the same +# file works whether it lives in this repo or in a synced consumer. +# Feature-branch testing requires sedding `@main` → `@` on the +# inner uses; see feedback_branch_pin_for_testing.md. +# +# Sync-time hack — `on: issue_comment:` injection +# ------------------------------------------------ +# The source-of-truth file in genlayer-e2e does NOT declare an +# `on: issue_comment:` trigger. If it did, this workflow would fire on +# EVERY comment in genlayer-e2e's own PRs (coderabbit, dependabot, …) +# and consume a 3-second skipped "noop" run per comment — visible +# clutter on the Actions list. +# +# `sync-templates.sh` injects the `issue_comment:` trigger block at +# sync time at the `# SYNC_INJECT(issue_comment)` marker below. The +# synced consumer copy gets the trigger; genlayer-e2e's source never +# does. Manual debug here still works via the `workflow_dispatch:` +# trigger which IS declared. +# +# The runtime expressions below (run-name, concurrency, acknowledge's +# `if:`, build/wave `pr-number` / `comment-id` coalesces) all reference +# `github.event_name == 'issue_comment'` and `github.event.comment.*` +# — those evaluate cleanly to false / empty on the workflow_dispatch +# path in genlayer-e2e, so they stay unconditional and work for both +# consumer and source contexts. Only the trigger declaration itself +# is injected. + +name: E2E Pipeline -name: E2E Tests +# Tag every run with a descriptive title: +# issue_comment /run-e2e: PR # /run-e2e +# workflow_dispatch: E2E Test // +# anything else: noop +# +# Manual dispatch is only available on the source repo (genlayer-e2e +# itself, never on a synced consumer), and is intentionally unrestricted +# — there's no per-actor concurrency group, so a developer can fire +# several test runs side-by-side. Putting profile/track/scope in the +# title makes those runs distinguishable at a glance on the Actions +# list (where the bare run_id was previously opaque). +run-name: >- + ${{ (github.event_name == 'issue_comment' + && startsWith(github.event.comment.body, '/run-e2e') + && format('PR #{0} /run-e2e', github.event.issue.number)) + || (github.event_name == 'workflow_dispatch' + && format('E2E Test {0}/{1}/{2}/{3}', inputs.profile, inputs.track, inputs.scope, inputs.stack)) + || format('noop {0}', github.run_id) }} on: issue_comment: types: [created] - pull_request: - types: [opened, synchronize, reopened, ready_for_review] - pull_request_review: - types: [submitted] + workflow_dispatch: + inputs: + profile: + description: Profile name (must be a top-level key in profiles.json) + required: false + default: default + type: choice + options: + - default + - testnet + track: + description: Matrix track (must exist as matrix/.yaml) + required: false + default: v0.5 + type: choice + options: + - v0.5 + scope: + description: > + Wave-plan scope filter. `all` runs every wave (default); + `core` runs only wave-1 (genlayer-node / test-core); + `tooling` runs waves 2-4 (SDKs + explorer + testing-suite + wallet). + Out-of-scope waves cascade-skip with reason "scope". + required: false + default: all + type: choice + options: + - all + - core + - tooling + stack: + description: > + Stack-target filter. `all` exercises every declared stack + (default); `dev-env` runs only the genlayer-dev-env variants; + `studio` runs only the GenLayer Studio variants. Components + whose declared `stack-targets` don't include the chosen + stack cascade-skip with reason "stack". + required: false + default: all # SYNC_INJECT(default_stack) + type: choice + options: + - all + - dev-env + - studio permissions: contents: read id-token: write issues: write checks: write + actions: write pull-requests: write -# Per-PR group so pushes cancel in-flight E2E on the same PR. +# /run-e2e triggers share a per-PR group so a new comment cancels the +# previous in-progress run. Other issue_comment events (and +# workflow_dispatch) get a unique group so they never queue behind a +# hung /run-e2e. concurrency: - group: e2e-${{ github.repository }}-pr-${{ github.event.issue.number || github.event.pull_request.number }} + group: >- + ${{ (github.event_name == 'issue_comment' + && startsWith(github.event.comment.body, '/run-e2e')) + && format('e2e-{0}-pr-{1}', github.repository, github.event.issue.number) + || format('e2e-noop-{0}', github.run_id) }} cancel-in-progress: true env: GCP_PROJECT_ID: ${{ vars.GCP_PROJECT_ID || 'devops-infra-428314' }} GCP_WIF_PROVIDER: ${{ vars.GCP_WIF_PROVIDER || 'projects/795309574007/locations/global/workloadIdentityPools/ci-core-e2e-runner/providers/ci-core-e2e-runner' }} GCP_SERVICE_ACCOUNT: ${{ vars.GCP_SERVICE_ACCOUNT || 'ci-core-e2e-runner@devops-workload-identities.iam.gserviceaccount.com' }} - GCP_SECRET_APP_ID: ${{ vars.GCP_SECRET_APP_ID || 'ci-core-e2e-runner-app-id' }} + GCP_SECRET_APP_CLIENT_ID: ${{ vars.GCP_SECRET_APP_CLIENT_ID || 'ci-core-e2e-runner-app-client-id' }} GCP_SECRET_APP_PRIVATE_KEY: ${{ vars.GCP_SECRET_APP_PRIVATE_KEY || 'ci-core-e2e-runner-app-private-key' }} + # Suppress notify-outcome's compact PR banner. Detailed results + # table still posted. Remove to re-enable. + E2E_REPORT_SKIP_RESULT: "true" jobs: # =========================================================================== - # Job 0: Parse trigger event → compute PR context, runner-ref, matrix-file - # Gates on author association (members/collaborators/owners only), draft - # status (skip drafts), and fork status (skip external PRs — they can't - # safely access secrets on pull_request; the commenter path re-gates). + # acknowledge — PR-side bookkeeping and comment tokenization. + # + # The `if:` guard lives here (not inside e2e-acknowledge.yml) because + # only the caller can guard on `github.event_name` + comment author + # association before the reusable workflow is even resolved. On + # workflow_dispatch, `github.event.issue` is null → guard false → + # acknowledge is skipped (and the plan job's `if:` opts back in for + # the dispatch path). + # =========================================================================== + acknowledge: + # PR-state guard: refuse /run-e2e on closed / merged PRs. After a + # PR merges, its head branch is typically deleted, which breaks + # every "content at PR head" fetch (third_party version files, + # target-repo matrix.yaml) — the resolver silently falls through + # to the baseline matrix and downstream cache keys drift off + # whatever the baseline's branch tip happens to be at that moment. + # If you actually need to retest, re-run on main or open a fresh + # PR with the same content. + if: >- + github.event.issue.pull_request + && github.event.issue.state == 'open' + && startsWith(github.event.comment.body, '/run-e2e') + && contains(fromJSON('["MEMBER","OWNER","COLLABORATOR"]'), github.event.comment.author_association) + uses: genlayerlabs/genlayer-e2e/.github/workflows/e2e-acknowledge.yml@main + with: + comment-id: ${{ github.event.comment.id }} + comment-body: ${{ github.event.comment.body }} + issue-number: ${{ github.event.issue.number }} + target-repo: ${{ github.repository }} + server-url: ${{ github.server_url }} + run-id: ${{ github.run_id }} + secrets: inherit + # =========================================================================== - parse: + # plan — pin profile / track / matrix-refs / wave-plans / cache-key. + # Dual-path internally (PR vs dispatch); see e2e-planner.yml. + # + # `if:` opts back in on workflow_dispatch where acknowledge is + # intentionally skipped. PR-comment path with an unauthorized author + # (acknowledge skipped because guard failed) does NOT re-enter here — + # the `github.event_name == 'workflow_dispatch'` clause filters it out. + # =========================================================================== + plan: + needs: acknowledge if: | - (github.event_name == 'issue_comment' - && github.event.issue.pull_request - && startsWith(github.event.comment.body, '/run-e2e') - && contains(fromJSON('["MEMBER","OWNER","COLLABORATOR"]'), github.event.comment.author_association)) - || - (github.event_name == 'pull_request' - && !github.event.pull_request.draft - && github.event.pull_request.head.repo.full_name == github.repository - && contains(fromJSON('["MEMBER","OWNER","COLLABORATOR"]'), github.event.pull_request.author_association)) - || - (github.event_name == 'pull_request_review' - && github.event.review.state == 'approved' - && github.event.pull_request.head.repo.full_name == github.repository - && contains(fromJSON('["MEMBER","OWNER","COLLABORATOR"]'), github.event.review.author_association)) - runs-on: ubuntu-latest - outputs: - pr-number: ${{ steps.parse.outputs.pr_number }} - comment-id: ${{ steps.parse.outputs.comment_id }} - profile: ${{ steps.parse.outputs.profile }} - runner-ref: ${{ steps.parse.outputs.runner_ref }} - matrix-file: ${{ steps.parse.outputs.matrix_file }} - steps: - - name: Parse trigger - id: parse - env: - EVENT_NAME: ${{ github.event_name }} - COMMENT_BODY: ${{ github.event.comment.body }} - GH_TOKEN: ${{ github.token }} - # Allowlist of valid track names. Mirrors the convention - # documented in ci-core-e2e-runner README.md (Participation - # section). Reject anything else — the resolved track ends up - # as both the matrix-fetch ref and the runner-checkout ref, so - # arbitrary input would let a comment author point at any - # branch/SHA on the runner repo. - TRACK_PATTERN: '^(main|v[0-9]+(\.[0-9]+)?(-dev)?)$' - run: | - set -euo pipefail + !cancelled() && + (needs.acknowledge.result == 'success' || + (needs.acknowledge.result == 'skipped' && github.event_name == 'workflow_dispatch')) + uses: genlayerlabs/genlayer-e2e/.github/workflows/e2e-planner.yml@main + with: + # Coalesce: acknowledge tokens win on the PR-comment path; on + # workflow_dispatch the tokens are empty and we fall back to + # the manual choice inputs. + profile: ${{ needs.acknowledge.outputs.profile-token || inputs.profile }} + track: ${{ needs.acknowledge.outputs.track-token || inputs.track }} + scope: ${{ needs.acknowledge.outputs.scope-token || inputs.scope }} + # SYNC_INJECT(default_stack_fallback) rewrites the literal 'all' on + # consumer copies (e.g. 'dev-env' for genlayer-node), so an + # issue_comment `/run-e2e` with no stack token still routes to + # the per-consumer default — inputs.stack is workflow_dispatch- + # only and resolves empty on the issue_comment path. + stack: ${{ needs.acknowledge.outputs.stack-token || inputs.stack || 'all' }} # SYNC_INJECT(default_stack_fallback) + target-repo: ${{ github.repository }} + pr-number: ${{ github.event.issue.number || '' }} + comment-id: ${{ github.event.comment.id || '' }} + check-run-id: ${{ needs.acknowledge.outputs.check-run-id || '' }} + # acknowledge picks the layered-cache cleavage based on the + # consumer repo. On workflow_dispatch acknowledge is skipped + # and its output is empty — the planner's empty default then + # disables layering (today's pre-Slice-A behaviour). + pre-build-cache: ${{ needs.acknowledge.outputs.pre-build-cache || '' }} - # ----- 1. Identify the PR + base ref + comment override (if any) ----- - override_track="" - case "${EVENT_NAME}" in - issue_comment) - pr_number='${{ github.event.issue.number }}' - comment_id='${{ github.event.comment.id }}' - # /run-e2e [] [] - # token 1 = /run-e2e; tokens after = profile and/or track. - # A token starting with 'v' or ending in '-dev' is the track, - # else it's the profile name. Either may be omitted. - args=$(echo "${COMMENT_BODY}" | head -1) - profile="default" - for tok in ${args}; do - [[ "${tok}" == "/run-e2e" ]] && continue - if [[ "${tok}" =~ ^(v[0-9]|main$|.*-dev$) ]]; then - override_track="${tok}" - else - profile="${tok}" - fi - done - # Need to fetch the PR to learn its base ref for the file lookup. - base_ref=$(gh api "/repos/${{ github.repository }}/pulls/${pr_number}" --jq '.base.ref') - ;; - pull_request|pull_request_review) - pr_number='${{ github.event.pull_request.number }}' - comment_id='' - profile='default' - base_ref='${{ github.event.pull_request.base.ref }}' - ;; - esac + # =========================================================================== + # build — full stack up + pack to cache. Synthetic PR context on the + # dispatch path: run_id stands in for pr-number; comment-id / + # check-run-id stay empty so downstream PR-facing steps are no-ops. + # =========================================================================== + build: + name: build (dev-env) + needs: [acknowledge, plan] + # Without an explicit `if:`, GHA's implicit `success()` would require + # acknowledge to have succeeded — but acknowledge is intentionally + # skipped on the workflow_dispatch path. Mirror the wave jobs and + # gate only on plan succeeding. + # + # Skip when the stack filter omits dev-env. `/run-e2e studio` makes + # every wave row's stack-target='studio' (build-studio handles + # those), so the dev-env bundle isn't needed. Mirrors build-studio's + # inverse gate below. + if: | + !cancelled() && + needs.plan.result == 'success' && + contains(needs.plan.outputs.stack-config, '"target":"dev-env"') + uses: genlayerlabs/genlayer-e2e/.github/workflows/e2e-build.yml@main + with: + track: ${{ github.ref_name }} + profile: ${{ needs.plan.outputs.profile }} + genvm-version: ${{ needs.plan.outputs.genvm-version }} + consensus-ref: ${{ needs.plan.outputs.consensus-ref }} + genlayer-node-ref: ${{ needs.plan.outputs.genlayer-node-ref }} + genlayer-explorer-ref: ${{ needs.plan.outputs.genlayer-explorer-ref }} + harness-ref: ${{ needs.plan.outputs.harness-ref }} + harness-sha: ${{ needs.plan.outputs.harness-sha }} + consensus-sha: ${{ needs.plan.outputs.consensus-sha }} + genlayer-node-sha: ${{ needs.plan.outputs.genlayer-node-sha }} + resolved-shas-json: ${{ needs.plan.outputs.resolved-shas-json }} + build-cache-key: ${{ needs.plan.outputs.build-cache-key }} + full-cache-key: ${{ needs.plan.outputs.full-cache-key }} + pre-build-cache: ${{ needs.plan.outputs.pre-build-cache }} + # Mirrors matrix/.yaml shape ({core, harness, tooling}). The + # conclusion job's Emit build summary step parses this with jq + # to render the full component Refs sub-list in the Execution + # block. Trailing JSON commas would be invalid — keep the same + # field set as the matrix file. + matrix-json: >- + {"core":{"genlayer-node":"${{ needs.plan.outputs.genlayer-node-ref }}","genlayer-consensus":"${{ needs.plan.outputs.consensus-ref }}","genvm":"${{ needs.plan.outputs.genvm-version }}"},"harness":{"genlayer-dev-env":"${{ needs.plan.outputs.harness-ref }}"},"tooling":{"genlayer-js":"${{ needs.plan.outputs.genlayer-js-ref }}","genlayer-py":"${{ needs.plan.outputs.genlayer-py-ref }}","genlayer-cli":"${{ needs.plan.outputs.genlayer-cli-ref }}","genlayer-studio":"${{ needs.plan.outputs.genlayer-studio-ref }}","genlayer-explorer":"${{ needs.plan.outputs.genlayer-explorer-ref }}","genlayer-testing-suite":"${{ needs.plan.outputs.genlayer-testing-suite-ref }}","genvm-linter":"${{ needs.plan.outputs.genvm-linter-ref }}","genlayer-wallet":"${{ needs.plan.outputs.genlayer-wallet-ref }}"}} + pr-number: ${{ github.event.issue.number || github.run_id }} + comment-id: ${{ github.event.comment.id || '' }} + target-repo: ${{ github.repository }} + check-run-id: ${{ needs.acknowledge.outputs.check-run-id || '' }} + head-sha: ${{ needs.acknowledge.outputs.head-sha || github.sha }} + github-retry-max: ${{ needs.plan.outputs.github-retry-max }} + github-retry-initial-delay: ${{ needs.plan.outputs.github-retry-initial-delay }} + github-retry-max-delay: ${{ needs.plan.outputs.github-retry-max-delay }} - # ----- 2. Resolve track: comment override > .github/e2e-track > main ----- - # The base branch's `.github/e2e-track` file is the source of - # truth for which version-matrix track this branch's PRs run - # against. Each long-lived branch (v1, v2-dev, etc.) declares - # its target in this file. See the runner repo's README, - # "Participation" section, for the lifecycle. - if [[ -n "${override_track}" ]]; then - track="${override_track}" - track_source="comment override" - else - track=$(gh api "/repos/${{ github.repository }}/contents/.github/e2e-track?ref=${base_ref}" \ - --jq '.content' 2>/dev/null | base64 -d | tr -d '[:space:]' || echo "") - if [[ -n "${track}" ]]; then - track_source=".github/e2e-track on ${base_ref}" - else - track="main" - track_source="fallback (no .github/e2e-track on ${base_ref})" - echo "::warning::No .github/e2e-track on ${base_ref}. Falling back to main track. Add the file to make this branch's track explicit — see ci-core-e2e-runner README." - fi - fi + # =========================================================================== + # build-studio — bring up a Studio stack and pack it for Studio-target shards. + # Runs in parallel with the dev-env build. Devenv-target wave rows continue + # to consume the existing full-cache-key; Studio-target rows restore the + # per-run Studio bundle produced here. + # =========================================================================== + build-studio: + name: build (studio) + needs: [acknowledge, plan] + if: | + !cancelled() && + needs.plan.result == 'success' && + contains(needs.plan.outputs.stack-config, '"target":"studio"') + uses: genlayerlabs/genlayer-e2e/.github/workflows/e2e-build-studio.yml@main + with: + track: ${{ github.ref_name }} + profile: ${{ needs.plan.outputs.profile }} + genvm-version: ${{ needs.plan.outputs.genvm-version }} + genlayer-studio-ref: ${{ needs.plan.outputs.genlayer-studio-ref }} + studio-cache-key: ${{ needs.plan.outputs.studio-cache-key }} + pr-number: ${{ github.event.issue.number || github.run_id }} + comment-id: ${{ github.event.comment.id || '' }} + target-repo: ${{ github.repository }} + check-run-id: ${{ needs.acknowledge.outputs.check-run-id || '' }} + head-sha: ${{ needs.acknowledge.outputs.head-sha || github.sha }} - # ----- 3. Validate track against allowlist ----- - if ! [[ "${track}" =~ ${TRACK_PATTERN} ]]; then - echo "::error::Invalid track '${track}' (source: ${track_source}). Must match ${TRACK_PATTERN}." - exit 1 - fi + # =========================================================================== + # Wave jobs — cascade pattern with sentinel-as-skip. Each wave matrix + # comes from `needs.plan.outputs.wave-plans` (one JSON object folding + # every per-wave plan array). + # =========================================================================== + wave-1: + # `name:` overrides GHA's default `wave-1 (component, test-task, …)` + # matrix-tuple display. Reads matrix.job-name (resolved from + # components.yaml's `job-name` field, falling back to the + # component key) so the listing reads e.g. `genlayer-core / shard + # (shard-1, true) / e2e`. + # + # When build fails, append "(skipped - build fails)" to the tile so + # the UI attributes the skip to its root-cause layer. The + # `matrix.component != 'none'` guard prevents existing sentinel rows + # (e.g., scope-filtered or impacted-set empty waves) from being + # relabelled — those keep their baked-in "(skipped - manual)" / + # "(skipped - scope)" / "(skipped - no scenarios)" label unchanged. + # Waves 2-4 mirror this pattern with extra upstream-wave clauses + # reading `needs.wave-K.outputs.failure-label` (the per-component + # layer tag emitted by e2e-run.yml when that wave's run failed). + name: ${{ (matrix.component != 'none' && ((matrix.stack-target == 'studio' && needs.build-studio.outputs.build-status != 'success') || (matrix.stack-target != 'studio' && needs.build.outputs.build-status != 'success'))) && format('{0} (skipped - build fails)', matrix.job-name) || matrix.job-name }} + needs: [acknowledge, plan, build, build-studio] + # No `build-status == 'success'` gate — when build fails we want + # wave-1 to RUN (so the `name:` expression evaluates and tiles + # render cleanly) but no-op via the sentinel-component override + # below. Same mechanism as the existing wave-2/3/4 cascade. + # + # `!cancelled() &&` bypasses GHA's implicit needs-failure-cascade: + # when an upstream `needs:` job (here, `build`) fails, GHA defaults + # to auto-skipping downstream jobs unless their `if:` explicitly + # opts in via `always()` / `!cancelled()` / `failure()`. A skipped + # job does NOT have its `name:` expression evaluated, so without + # this prefix wave-1's tile shows the raw `${{ ... }}` text on + # build failure. Waves 2-4 already carry the same prefix. + # + # resolve-components / build-wave-plans emit a sentinel-row plan + # (component='none') when no impacted component maps to this wave, + # so the matrix always has at least one row and GHA can render + # `${{ matrix.job-name }}` for the placeholder tile (per + # actions/runner#1985, the unresolved name expression needs a + # matrix row to bind to). The sentinel's empty features-source / + # tags / test-task naturally cascade through e2e-run.yml's + # allocate → shard → conclusion chain to a no-op success — see + # resolve-components/action.yml for the full cascade explanation. + if: | + !cancelled() && + needs.plan.result == 'success' + strategy: + fail-fast: false + matrix: + include: ${{ fromJson(needs.plan.outputs.wave-plans)['wave-1'] }} + uses: genlayerlabs/genlayer-e2e/.github/workflows/e2e-run.yml@main + with: + # Cascade override: if build did NOT produce a clean verdict, + # force the sentinel path so wave-1 no-ops cleanly. Same + # mechanism waves 2-4 use for upstream-wave failures — see + # e2e-run.yml's sentinel branches. + component: ${{ ((matrix.stack-target == 'studio' && needs.build-studio.outputs.build-status != 'success') || (matrix.stack-target != 'studio' && needs.build.outputs.build-status != 'success')) && 'none' || matrix.component }} + track: ${{ github.ref_name }} + job-name: ${{ matrix.job-name || matrix.component }} + stack-target: ${{ matrix.stack-target || 'dev-env' }} + setup-task: ${{ matrix.setup-task }} + test-task: ${{ matrix.test-task }} + tags: ${{ matrix.tags }} + split: ${{ matrix.split }} + features-source: ${{ matrix.features-source }} + retry: ${{ matrix.retry }} + max-shard-split: ${{ matrix.max-shard-split || 0 }} + failure-tag: ${{ matrix.failure-tag || '' }} + genvm-version: ${{ needs.plan.outputs.genvm-version }} + genlayer-node-ref: ${{ needs.plan.outputs.genlayer-node-ref }} + consensus-ref: ${{ needs.plan.outputs.consensus-ref }} + genlayer-js-ref: ${{ needs.plan.outputs.genlayer-js-ref }} + genlayer-py-ref: ${{ needs.plan.outputs.genlayer-py-ref }} + genlayer-cli-ref: ${{ needs.plan.outputs.genlayer-cli-ref }} + genlayer-studio-ref: ${{ needs.plan.outputs.genlayer-studio-ref }} + genlayer-explorer-ref: ${{ needs.plan.outputs.genlayer-explorer-ref }} + genlayer-testing-suite-ref: ${{ needs.plan.outputs.genlayer-testing-suite-ref }} + genvm-linter-ref: ${{ needs.plan.outputs.genvm-linter-ref }} + genlayer-wallet-ref: ${{ needs.plan.outputs.genlayer-wallet-ref }} + harness-ref: ${{ needs.plan.outputs.harness-ref }} + harness-sha: ${{ needs.plan.outputs.harness-sha }} + cache-key: ${{ needs.plan.outputs.full-cache-key }} + studio-cache-key: ${{ needs.plan.outputs.studio-cache-key }} + profile: ${{ needs.plan.outputs.profile }} + pr-number: ${{ github.event.issue.number || github.run_id }} + comment-id: ${{ github.event.comment.id || '' }} + target-repo: ${{ github.repository }} + check-run-id: ${{ needs.acknowledge.outputs.check-run-id || '' }} + head-sha: ${{ needs.acknowledge.outputs.head-sha || github.sha }} + github-retry-max: ${{ needs.plan.outputs.github-retry-max }} + github-retry-initial-delay: ${{ needs.plan.outputs.github-retry-initial-delay }} + github-retry-max-delay: ${{ needs.plan.outputs.github-retry-max-delay }} - # ----- 4. Map track → matrix file ----- - # Matrix file convention: matrix/.yaml — with the - # historical exception that `main` track reads the v0.5 - # stable matrix until v0.6 becomes stable. - case "${track}" in - main) matrix_file='matrix/v0.5.yaml' ;; - *) matrix_file="matrix/${track}.yaml" ;; - esac + wave-2: + # Cascade-skip label rules (walked in order, first match wins): + # 1. build failed → "(skipped - build fails)" + # 2. wave-1's failure-label is non-empty (e.g. "core") → + # "(skipped - {label} fails)" + # 3. wave-1 failed but emitted no tag (failure-label empty) → + # generic "(skipped - fails)" + # else → matrix.job-name (real run or sentinel-baked label) + # + # `failure-label` is e2e-run.yml's per-component output, populated + # from `inputs.failure-tag` only when the run's test-conclusion is + # 'failure'. Empty otherwise — so a successful or sentinel-skipped + # wave doesn't carry a stale tag forward. + name: ${{ (matrix.component != 'none' && ((matrix.stack-target == 'studio' && needs.build-studio.outputs.build-status != 'success') || (matrix.stack-target != 'studio' && needs.build.outputs.build-status != 'success'))) && format('{0} (skipped - build fails)', matrix.job-name) || (matrix.component != 'none' && needs.wave-1.outputs.failure-label != '') && format('{0} (skipped - {1} fails)', matrix.job-name, needs.wave-1.outputs.failure-label) || (matrix.component != 'none' && needs.wave-1.result == 'failure') && format('{0} (skipped - fails)', matrix.job-name) || matrix.job-name }} + needs: [acknowledge, plan, build, build-studio, wave-1] + # No cascade gate — wave-2 always runs when plan is OK. If + # build or wave-1 failed, with.component is overridden to 'none' + # below, tripping e2e-run.yml's sentinel path (allocate/shard/ + # check-run/retry/cleanup-artifacts skip; conclusion emits + # 'skipped'). Same flow as manual skip:true. + if: | + !cancelled() && + needs.plan.result == 'success' + strategy: + fail-fast: false + matrix: + include: ${{ fromJson(needs.plan.outputs.wave-plans)['wave-2'] }} + uses: genlayerlabs/genlayer-e2e/.github/workflows/e2e-run.yml@main + with: + # Cascade override: force sentinel path when any upstream layer + # (build / wave-1) failed. `.result == 'failure'` is the + # reliable trip signal — failure-label is only used for the + # tile label content above, not the trip decision. + component: ${{ (((matrix.stack-target == 'studio' && needs.build-studio.outputs.build-status != 'success') || (matrix.stack-target != 'studio' && needs.build.outputs.build-status != 'success')) || needs.wave-1.result == 'failure') && 'none' || matrix.component }} + track: ${{ github.ref_name }} + job-name: ${{ matrix.job-name || matrix.component }} + stack-target: ${{ matrix.stack-target || 'dev-env' }} + setup-task: ${{ matrix.setup-task }} + test-task: ${{ matrix.test-task }} + tags: ${{ matrix.tags }} + split: ${{ matrix.split }} + features-source: ${{ matrix.features-source }} + retry: ${{ matrix.retry }} + max-shard-split: ${{ matrix.max-shard-split || 0 }} + failure-tag: ${{ matrix.failure-tag || '' }} + genvm-version: ${{ needs.plan.outputs.genvm-version }} + genlayer-node-ref: ${{ needs.plan.outputs.genlayer-node-ref }} + consensus-ref: ${{ needs.plan.outputs.consensus-ref }} + genlayer-js-ref: ${{ needs.plan.outputs.genlayer-js-ref }} + genlayer-py-ref: ${{ needs.plan.outputs.genlayer-py-ref }} + genlayer-cli-ref: ${{ needs.plan.outputs.genlayer-cli-ref }} + genlayer-studio-ref: ${{ needs.plan.outputs.genlayer-studio-ref }} + genlayer-explorer-ref: ${{ needs.plan.outputs.genlayer-explorer-ref }} + genlayer-testing-suite-ref: ${{ needs.plan.outputs.genlayer-testing-suite-ref }} + genvm-linter-ref: ${{ needs.plan.outputs.genvm-linter-ref }} + genlayer-wallet-ref: ${{ needs.plan.outputs.genlayer-wallet-ref }} + harness-ref: ${{ needs.plan.outputs.harness-ref }} + harness-sha: ${{ needs.plan.outputs.harness-sha }} + cache-key: ${{ needs.plan.outputs.full-cache-key }} + studio-cache-key: ${{ needs.plan.outputs.studio-cache-key }} + profile: ${{ needs.plan.outputs.profile }} + pr-number: ${{ github.event.issue.number || github.run_id }} + comment-id: ${{ github.event.comment.id || '' }} + target-repo: ${{ github.repository }} + check-run-id: ${{ needs.acknowledge.outputs.check-run-id || '' }} + head-sha: ${{ needs.acknowledge.outputs.head-sha || github.sha }} + github-retry-max: ${{ needs.plan.outputs.github-retry-max }} + github-retry-initial-delay: ${{ needs.plan.outputs.github-retry-initial-delay }} + github-retry-max-delay: ${{ needs.plan.outputs.github-retry-max-delay }} - # ----- 5. Emit outputs + summary ----- - { - echo "pr_number=${pr_number}" - echo "comment_id=${comment_id}" - echo "profile=${profile}" - echo "runner_ref=${track}" - echo "matrix_file=${matrix_file}" - } >> "$GITHUB_OUTPUT" + wave-3: + # See wave-2 for the cascade-skip label semantics. Walk order + # (first match wins): build → wave-1 failure-label → wave-2 + # failure-label → generic-fallback. The `.result == 'failure'` + # fallback catches the rare case where an upstream wave failed + # but didn't emit a failure-tag (e.g. internal job-level error + # before conclusion ran). + name: ${{ (matrix.component != 'none' && ((matrix.stack-target == 'studio' && needs.build-studio.outputs.build-status != 'success') || (matrix.stack-target != 'studio' && needs.build.outputs.build-status != 'success'))) && format('{0} (skipped - build fails)', matrix.job-name) || (matrix.component != 'none' && needs.wave-1.outputs.failure-label != '') && format('{0} (skipped - {1} fails)', matrix.job-name, needs.wave-1.outputs.failure-label) || (matrix.component != 'none' && needs.wave-2.outputs.failure-label != '') && format('{0} (skipped - {1} fails)', matrix.job-name, needs.wave-2.outputs.failure-label) || (matrix.component != 'none' && (needs.wave-1.result == 'failure' || needs.wave-2.result == 'failure')) && format('{0} (skipped - fails)', matrix.job-name) || matrix.job-name }} + needs: [acknowledge, plan, build, build-studio, wave-1, wave-2] + # No cascade gate — wave-3 always runs. If build or any upstream + # wave failed, with.component is overridden to 'none' below, + # tripping e2e-run.yml's sentinel path (no GCE provisioned, + # conclusion emits 'skipped'). See wave-2 for the full rationale. + if: | + !cancelled() && + needs.plan.result == 'success' + strategy: + fail-fast: false + matrix: + include: ${{ fromJson(needs.plan.outputs.wave-plans)['wave-3'] }} + uses: genlayerlabs/genlayer-e2e/.github/workflows/e2e-run.yml@main + with: + # Cascade override: force sentinel path when any upstream layer + # (build / wave-1 / wave-2) failed. Uses `.result == 'failure'` + # for reliability — failure-label is only consumed for the + # tile label content above, not the trip decision. + component: ${{ (((matrix.stack-target == 'studio' && needs.build-studio.outputs.build-status != 'success') || (matrix.stack-target != 'studio' && needs.build.outputs.build-status != 'success')) || needs.wave-1.result == 'failure' || needs.wave-2.result == 'failure') && 'none' || matrix.component }} + track: ${{ github.ref_name }} + job-name: ${{ matrix.job-name || matrix.component }} + stack-target: ${{ matrix.stack-target || 'dev-env' }} + setup-task: ${{ matrix.setup-task }} + test-task: ${{ matrix.test-task }} + tags: ${{ matrix.tags }} + split: ${{ matrix.split }} + features-source: ${{ matrix.features-source }} + retry: ${{ matrix.retry }} + max-shard-split: ${{ matrix.max-shard-split || 0 }} + failure-tag: ${{ matrix.failure-tag || '' }} + genvm-version: ${{ needs.plan.outputs.genvm-version }} + genlayer-node-ref: ${{ needs.plan.outputs.genlayer-node-ref }} + consensus-ref: ${{ needs.plan.outputs.consensus-ref }} + genlayer-js-ref: ${{ needs.plan.outputs.genlayer-js-ref }} + genlayer-py-ref: ${{ needs.plan.outputs.genlayer-py-ref }} + genlayer-cli-ref: ${{ needs.plan.outputs.genlayer-cli-ref }} + genlayer-studio-ref: ${{ needs.plan.outputs.genlayer-studio-ref }} + genlayer-explorer-ref: ${{ needs.plan.outputs.genlayer-explorer-ref }} + genlayer-testing-suite-ref: ${{ needs.plan.outputs.genlayer-testing-suite-ref }} + genvm-linter-ref: ${{ needs.plan.outputs.genvm-linter-ref }} + genlayer-wallet-ref: ${{ needs.plan.outputs.genlayer-wallet-ref }} + harness-ref: ${{ needs.plan.outputs.harness-ref }} + harness-sha: ${{ needs.plan.outputs.harness-sha }} + cache-key: ${{ needs.plan.outputs.full-cache-key }} + studio-cache-key: ${{ needs.plan.outputs.studio-cache-key }} + profile: ${{ needs.plan.outputs.profile }} + pr-number: ${{ github.event.issue.number || github.run_id }} + comment-id: ${{ github.event.comment.id || '' }} + target-repo: ${{ github.repository }} + check-run-id: ${{ needs.acknowledge.outputs.check-run-id || '' }} + head-sha: ${{ needs.acknowledge.outputs.head-sha || github.sha }} + github-retry-max: ${{ needs.plan.outputs.github-retry-max }} + github-retry-initial-delay: ${{ needs.plan.outputs.github-retry-initial-delay }} + github-retry-max-delay: ${{ needs.plan.outputs.github-retry-max-delay }} - echo "Event: ${EVENT_NAME}" - echo "PR: ${pr_number}" - echo "Base ref: ${base_ref}" - echo "Profile: ${profile}" - echo "Track: ${track} (source: ${track_source})" - echo "Matrix file: ${matrix_file}" + wave-4: + # See wave-2 for the cascade-skip label semantics. Walk order + # (first match wins): build → wave-1 → wave-2 → wave-3 failure- + # label, then generic-fallback via `.result == 'failure'`. + name: ${{ (matrix.component != 'none' && ((matrix.stack-target == 'studio' && needs.build-studio.outputs.build-status != 'success') || (matrix.stack-target != 'studio' && needs.build.outputs.build-status != 'success'))) && format('{0} (skipped - build fails)', matrix.job-name) || (matrix.component != 'none' && needs.wave-1.outputs.failure-label != '') && format('{0} (skipped - {1} fails)', matrix.job-name, needs.wave-1.outputs.failure-label) || (matrix.component != 'none' && needs.wave-2.outputs.failure-label != '') && format('{0} (skipped - {1} fails)', matrix.job-name, needs.wave-2.outputs.failure-label) || (matrix.component != 'none' && needs.wave-3.outputs.failure-label != '') && format('{0} (skipped - {1} fails)', matrix.job-name, needs.wave-3.outputs.failure-label) || (matrix.component != 'none' && (needs.wave-1.result == 'failure' || needs.wave-2.result == 'failure' || needs.wave-3.result == 'failure')) && format('{0} (skipped - fails)', matrix.job-name) || matrix.job-name }} + needs: [acknowledge, plan, build, build-studio, wave-1, wave-2, wave-3] + # No cascade gate — wave-4 always runs. See wave-2 for the + # cascade-as-sentinel rationale. + if: | + !cancelled() && + needs.plan.result == 'success' + strategy: + fail-fast: false + matrix: + include: ${{ fromJson(needs.plan.outputs.wave-plans)['wave-4'] }} + uses: genlayerlabs/genlayer-e2e/.github/workflows/e2e-run.yml@main + with: + # Cascade override: force sentinel path when any upstream layer + # (build / wave-1 / wave-2 / wave-3) failed. + component: ${{ (((matrix.stack-target == 'studio' && needs.build-studio.outputs.build-status != 'success') || (matrix.stack-target != 'studio' && needs.build.outputs.build-status != 'success')) || needs.wave-1.result == 'failure' || needs.wave-2.result == 'failure' || needs.wave-3.result == 'failure') && 'none' || matrix.component }} + track: ${{ github.ref_name }} + job-name: ${{ matrix.job-name || matrix.component }} + stack-target: ${{ matrix.stack-target || 'dev-env' }} + setup-task: ${{ matrix.setup-task }} + test-task: ${{ matrix.test-task }} + tags: ${{ matrix.tags }} + split: ${{ matrix.split }} + features-source: ${{ matrix.features-source }} + retry: ${{ matrix.retry }} + max-shard-split: ${{ matrix.max-shard-split || 0 }} + failure-tag: ${{ matrix.failure-tag || '' }} + genvm-version: ${{ needs.plan.outputs.genvm-version }} + genlayer-node-ref: ${{ needs.plan.outputs.genlayer-node-ref }} + consensus-ref: ${{ needs.plan.outputs.consensus-ref }} + genlayer-js-ref: ${{ needs.plan.outputs.genlayer-js-ref }} + genlayer-py-ref: ${{ needs.plan.outputs.genlayer-py-ref }} + genlayer-cli-ref: ${{ needs.plan.outputs.genlayer-cli-ref }} + genlayer-studio-ref: ${{ needs.plan.outputs.genlayer-studio-ref }} + genlayer-explorer-ref: ${{ needs.plan.outputs.genlayer-explorer-ref }} + genlayer-testing-suite-ref: ${{ needs.plan.outputs.genlayer-testing-suite-ref }} + genvm-linter-ref: ${{ needs.plan.outputs.genvm-linter-ref }} + genlayer-wallet-ref: ${{ needs.plan.outputs.genlayer-wallet-ref }} + harness-ref: ${{ needs.plan.outputs.harness-ref }} + harness-sha: ${{ needs.plan.outputs.harness-sha }} + cache-key: ${{ needs.plan.outputs.full-cache-key }} + studio-cache-key: ${{ needs.plan.outputs.studio-cache-key }} + profile: ${{ needs.plan.outputs.profile }} + pr-number: ${{ github.event.issue.number || github.run_id }} + comment-id: ${{ github.event.comment.id || '' }} + target-repo: ${{ github.repository }} + check-run-id: ${{ needs.acknowledge.outputs.check-run-id || '' }} + head-sha: ${{ needs.acknowledge.outputs.head-sha || github.sha }} + github-retry-max: ${{ needs.plan.outputs.github-retry-max }} + github-retry-initial-delay: ${{ needs.plan.outputs.github-retry-initial-delay }} + github-retry-max-delay: ${{ needs.plan.outputs.github-retry-max-delay }} # =========================================================================== - # Job 1: Generate feedback (eyes reaction, check run), resolve versions + # result — final guard that makes the workflow's conclusion reflect + # the REAL outcome. Mirrors `plan` at the start (plan → build → + # waves → result). + # + # Per-wave verdict comes from each wave's `test-conclusion` output + # (sourced from e2e-run.yml's `conclusion` job), which reflects retry + # recovery — so a first-try shard failure that retry recovered + # counts as 'success'. When test-conclusion is empty (wave was + # skipped or never reached the conclusion job), fall back to GHA's + # `.result` for the rough verdict. # =========================================================================== - resolve: - needs: parse + result: + needs: [acknowledge, plan, build, build-studio, wave-1, wave-2, wave-3, wave-4] + # `always() && plan.result != 'skipped'` rather than bare `always()`: + # noop issue_comments (any non-/run-e2e comment in this repo, since + # the workflow lives at `on: issue_comment`) skip acknowledge → plan + # → build → waves all the way down. Without this guard, result still + # runs, and its env block resolves + # `toJson(fromJson(needs.plan.outputs.wave-plans)['wave-N'])` against + # plan's empty output → fromJson('') fails the template at + # job-start (see run 26223668789). Letting result skip on + # plan==skipped keeps the noop pipeline clean — `acknowledge / plan / + # build / waves / result` all skipped, no red marker. + if: always() && needs.plan.result != 'skipped' runs-on: ubuntu-latest - outputs: - profile: ${{ steps.resolve.outputs.profile }} - pr-number: ${{ steps.resolve.outputs.pr-number }} - comment-id: ${{ steps.resolve.outputs.comment-id }} - repo: ${{ steps.resolve.outputs.repo }} - genvm-version: ${{ steps.resolve.outputs.genvm-version }} - genlayer-node-ref: ${{ steps.resolve.outputs.genlayer-node-ref }} - consensus-ref: ${{ steps.resolve.outputs.consensus-ref }} - genlayer-js-ref: ${{ steps.resolve.outputs.genlayer-js-ref }} - genlayer-py-ref: ${{ steps.resolve.outputs.genlayer-py-ref }} - genlayer-cli-ref: ${{ steps.resolve.outputs.genlayer-cli-ref }} - genlayer-explorer-ref: ${{ steps.resolve.outputs.genlayer-explorer-ref }} - genlayer-testing-suite-ref: ${{ steps.resolve.outputs.genlayer-testing-suite-ref }} - tag-filter: ${{ steps.resolve.outputs.tag-filter }} - impacted-components: ${{ steps.resolve.outputs.impacted-components }} - check-run-id: ${{ steps.check-run.outputs.check_run_id }} - head-sha: ${{ steps.check-run.outputs.head_sha }} steps: - # Check out ci-core-e2e-runner at the parsed track ref BEFORE anything - # else so subsequent `uses:` can reference local paths. This is the - # workaround for GitHub Actions not allowing expressions in action - # `uses:` refs — we can't write `...@${{ needs.parse.outputs.runner-ref }}` - # on a composite action, but we CAN check out the repo at an - # arbitrary ref and call `./path/to/action` locally. - # - # DOCS_REPO_TOKEN (PAT scoped to ci-core-e2e-runner) is the bootstrap - # auth. After this step, subsequent gh/git calls use the short-lived - # App token generated by ./runner/.github/actions/gcp-app-token. - - name: Checkout ci-core-e2e-runner at ${{ needs.parse.outputs.runner-ref }} - uses: actions/checkout@v4 - with: - repository: genlayerlabs/ci-core-e2e-runner - ref: ${{ needs.parse.outputs.runner-ref }} - token: ${{ secrets.DOCS_REPO_TOKEN }} - path: runner - + # App token for the final notify-outcome — completing the + # check-run + swapping the 👀 reaction requires the App token + # (consumer's GITHUB_TOKEN can't update a check-run the App + # created). Cross-repo `uses:` because no checkout has run yet. - name: Generate GitHub App token id: app-token - uses: ./runner/.github/actions/gcp-app-token + uses: genlayerlabs/genlayer-e2e/.github/actions/gcp-app-token@main - - name: React with eyes on trigger comment - if: needs.parse.outputs.comment-id != '' - env: - GH_TOKEN: ${{ steps.app-token.outputs.token }} - run: | - gh api --method POST \ - "/repos/${{ github.repository }}/issues/comments/${{ needs.parse.outputs.comment-id }}/reactions" \ - -f content='eyes' + # App token, not the default github.token: when this workflow is + # synced to a consumer, github.token is the CONSUMER's repo-scoped + # token and can't read the private genlayer-e2e repo (exit 128 + # auth failure on the actions/checkout step — observed on + # genlayer-node run 26240246363). + - uses: actions/checkout@v6 + with: + repository: genlayerlabs/genlayer-e2e + ref: main + token: ${{ steps.app-token.outputs.token }} - - name: Create check run - id: check-run - env: - GH_TOKEN: ${{ steps.app-token.outputs.token }} - run: | - head_sha=$(gh api "/repos/${{ github.repository }}/pulls/${{ needs.parse.outputs.pr-number }}" --jq '.head.sha') - echo "head_sha=${head_sha}" >> "$GITHUB_OUTPUT" + # Per-(component, stack-target) verdict artifacts uploaded by + # each e2e-run.yml conclusion job. One artifact per matrix row + # — pattern flattens them into a single directory keyed by + # artifact-name (= component). Aggregate reads this directory + # to build per-wave verdicts without relying on + # `needs.wave-N.outputs.test-conclusion` (which is racy under + # matrix fan-out — last write wins). + - name: Download test-conclusion artifacts + id: download-conclusions + continue-on-error: true + uses: actions/download-artifact@v8 + with: + pattern: e2e-test-conclusion-*-pr${{ github.event.issue.number || github.run_id }} + path: /tmp/test-conclusions - check_run_id=$(gh api --method POST \ - "/repos/${{ github.repository }}/check-runs" \ - -f name='E2E Tests' \ - -f head_sha="${head_sha}" \ - -f status='in_progress' \ - -f "details_url=${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" \ - --jq '.id') - echo "check_run_id=${check_run_id}" >> "$GITHUB_OUTPUT" + - name: Aggregate outcomes + id: aggregate + # `continue-on-error: true` so a failed aggregation (exit 1 on + # any wave failure) doesn't shortcut the notify-outcome step + # below. The Enforce step at the end re-propagates failure to + # the workflow conclusion. + continue-on-error: true + env: + PLAN_RESULT: ${{ needs.plan.result }} + # BUILD_STATUS is the AND of the two stack-scoped builds, + # but a build that wasn't requested (its stack filtered out + # by /run-e2e ) counts as success — its job is + # `skipped`, not `failure`. The contains() checks gate each + # build's contribution by whether its stack-target appears + # in the wave-plans output. + BUILD_STATUS: ${{ ((!contains(needs.plan.outputs.stack-config, '"target":"dev-env"') || needs.build.outputs.build-status == 'success') && (!contains(needs.plan.outputs.stack-config, '"target":"studio"') || needs.build-studio.outputs.build-status == 'success')) && 'success' || 'failure' }} + BUILD_RESULT: ${{ format('dev-env={0}, studio={1}', needs.build.result, needs.build-studio.result) }} + # Classifier-emitted stage + detail surfaced in the build row's + # Notes column when BUILD_STATUS != success. Empty when build + # was a cache-hit (no execute job ran) — the aggregate script + # falls back to the legacy verdict-word render. + BUILD_STAGE: ${{ (contains(needs.plan.outputs.stack-config, '"target":"studio"') && needs.build-studio.outputs.build-status != 'success') && 'build:studio' || needs.build.outputs.build-stage || '' }} + BUILD_DETAIL: ${{ (contains(needs.plan.outputs.stack-config, '"target":"studio"') && needs.build-studio.outputs.build-status != 'success') && 'Studio build failed' || needs.build.outputs.build-detail || '' }} + WAVE_1_RESULT: ${{ needs.wave-1.result }} + WAVE_1_PLAN: ${{ toJson(fromJson(needs.plan.outputs.wave-plans)['wave-1']) }} + WAVE_2_RESULT: ${{ needs.wave-2.result }} + WAVE_2_PLAN: ${{ toJson(fromJson(needs.plan.outputs.wave-plans)['wave-2']) }} + WAVE_3_RESULT: ${{ needs.wave-3.result }} + WAVE_3_PLAN: ${{ toJson(fromJson(needs.plan.outputs.wave-plans)['wave-3']) }} + WAVE_4_RESULT: ${{ needs.wave-4.result }} + WAVE_4_PLAN: ${{ toJson(fromJson(needs.plan.outputs.wave-plans)['wave-4']) }} + # Per-(component, stack-target) verdict directory (one file + # per artifact, name == component, content ∈ {success, + # failure, skipped}). Replaces the legacy single-value + # WAVE_N_TEST_CONCLUSION env which collapses under matrix + # fan-out (last write wins) — see Download test-conclusion + # artifacts step above. PR_NUMBER lets the script construct + # the exact artifact path; on workflow_dispatch (no PR) the + # run_id stands in, matching the wave jobs' pr-number input. + CONCLUSIONS_DIR: /tmp/test-conclusions + PR_NUMBER: ${{ github.event.issue.number || github.run_id }} + run: ./taskfiles/runner/scripts/aggregate-wave-outcomes.sh - # Local path — resolver comes from the track branch, not main. - # Track-specific changes (new matrix schema, new components, - # new Depends-On logic) live on the track branch and are picked - # up automatically. - - uses: ./runner/actions/e2e-resolve - id: resolve + # Final notify-outcome — flips 👀 → 🚀 (overall pass) or 👎 + # (any wave failed), completes the "E2E Tests" check-run, and + # (with E2E_REPORT_SKIP_RESULT="true" suppressing the compact + # banner) skips posting a duplicate PR comment. Per-component + # PR comments were already posted by each wave's e2e-report.sh. + # Gated on check-run-id presence so workflow_dispatch (no + # acknowledge → no check-run) skips silently. + # + # Also skip when plan failed: the planner's own "Notify resolve + # failure" step already posted the structured error message + # (e.g. "Malformed Depends-On line: ...") and updated the + # check-run + reaction. The aggregate's failed-pipeline banner + # here would be a half-empty table that just says "plan failed" + # — no extra signal, and it buries the specific error message + # under a generic-looking second comment. + - name: Notify final outcome + if: always() && needs.acknowledge.outputs.check-run-id != '' && needs.plan.result != 'failure' + continue-on-error: true + uses: genlayerlabs/genlayer-e2e/.github/actions/notify-outcome@main with: - cross-repo-token: ${{ steps.app-token.outputs.token }} - profile: ${{ needs.parse.outputs.profile }} - pr-number: ${{ needs.parse.outputs.pr-number }} - comment-id: ${{ needs.parse.outputs.comment-id }} - matrix-file: ${{ needs.parse.outputs.matrix-file }} - matrix-ref: ${{ needs.parse.outputs.runner-ref }} + outcome: ${{ steps.aggregate.outcome == 'success' && 'success' || 'failure' }} + check-run-title: 'E2E Tests' + repo: ${{ github.repository }} + comment-id: ${{ github.event.comment.id }} + check-run-id: ${{ needs.acknowledge.outputs.check-run-id }} + pr-number: ${{ github.event.issue.number }} + github-token: ${{ steps.app-token.outputs.token }} - # =========================================================================== - # Job 2: Run E2E tests on self-hosted runner (reusable workflow) - # Workflow invocation pinned to @main because GitHub Actions does not - # allow expressions (not `needs`, `inputs`, or `vars`) in - # `jobs..uses`. See: - # https://docs.github.com/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_iduses - # - # Track-aware behaviour still flows through: the resolver + matrix - # are loaded from the track ref via gh api, and the tests/taskfile - # that shard-run.yml invokes come from the track branch (shard-run - # clones the runner repo at the caller's configured ref). - # =========================================================================== - e2e: - needs: [parse, resolve] - uses: genlayerlabs/ci-core-e2e-runner/.github/workflows/e2e-run.yml@feat/version-matrix-phase1 - with: - genvm-version: ${{ needs.resolve.outputs.genvm-version }} - genlayer-node-ref: ${{ needs.resolve.outputs.genlayer-node-ref }} - consensus-ref: ${{ needs.resolve.outputs.consensus-ref }} - genlayer-js-ref: ${{ needs.resolve.outputs.genlayer-js-ref }} - genlayer-py-ref: ${{ needs.resolve.outputs.genlayer-py-ref }} - genlayer-cli-ref: ${{ needs.resolve.outputs.genlayer-cli-ref }} - genlayer-explorer-ref: ${{ needs.resolve.outputs.genlayer-explorer-ref }} - genlayer-testing-suite-ref: ${{ needs.resolve.outputs.genlayer-testing-suite-ref }} - tag-filter: ${{ needs.resolve.outputs.tag-filter }} - profile: ${{ needs.resolve.outputs.profile }} - pr-number: ${{ needs.resolve.outputs.pr-number }} - comment-id: ${{ needs.resolve.outputs.comment-id }} - target-repo: ${{ needs.resolve.outputs.repo }} - check-run-id: ${{ needs.resolve.outputs.check-run-id }} - head-sha: ${{ needs.resolve.outputs.head-sha }} + # Re-propagate the aggregate's exit status to the workflow + # conclusion. Without this, the result job would always succeed + # (because aggregate has `continue-on-error: true`) and the + # whole pipeline would render as green even on real failures. + - name: Enforce overall outcome + if: steps.aggregate.outcome == 'failure' + run: | + echo "::error::Pipeline failed — see ::error:: lines in Aggregate outcomes step" + exit 1 From f6a035cf832b11e16bf8a888c3957399c6df5380 Mon Sep 17 00:00:00 2001 From: "ci-core-e2e-runner[bot]" <263344042+ci-core-e2e-runner[bot]@users.noreply.github.com> Date: Tue, 26 May 2026 20:24:38 +0100 Subject: [PATCH 08/14] ci(workflows): sync e2e-housekeeper.yml from genlayer-e2e (#175) Co-authored-by: ci-core-e2e-runner[bot] <263344042+ci-core-e2e-runner[bot]@users.noreply.github.com> --- .github/workflows/e2e-housekeeper.yml | 84 +++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 .github/workflows/e2e-housekeeper.yml diff --git a/.github/workflows/e2e-housekeeper.yml b/.github/workflows/e2e-housekeeper.yml new file mode 100644 index 0000000..ce911f5 --- /dev/null +++ b/.github/workflows/e2e-housekeeper.yml @@ -0,0 +1,84 @@ +name: E2E Housekeeper + +# =========================================================================== +# Source-of-truth E2E housekeeper workflow. +# +# This file is BOTH: +# - The workflow that runs in this repo (genlayer-e2e) for genlayer- +# e2e's own cache pool. +# - The file synced byte-identically to every consumer repo as +# `.github/workflows/e2e-housekeeper.yml` (sync-template.yaml owns +# the fan-out). +# +# Mirrors the architecture of e2e-pipeline.yml — one file in the source +# repo, copied verbatim to consumers, no wrapper layer. Adding a new +# scheduled upkeep step (artifact pruning, runner sweep, …) only needs +# editing this file; sync-template.yaml opens a PR in each consumer. +# +# Cache storage is per-repo, so the eviction step runs in the CALLER's +# context: `gh cache list` / `gh cache delete` operate on the caller's +# pool via the inherited GITHUB_TOKEN. The runner's filesystem starts +# empty, so step 1 checks out genlayer-e2e to access the extracted +# `evict-stale-caches.sh` script — github.token in a synced consumer +# context still has cross-org read access on the org's private repos. +# =========================================================================== + +on: + schedule: + - cron: '0 6 * * *' # daily 06:00 UTC + # No inputs: production triggers (schedule today, PR-merged later) + # don't pass them, and the script's defaults (24h idle / 200 page + # cap) are stable. workflow_dispatch stays as a no-arg "run the + # cron now" button — handy in genlayer-e2e while iterating. + workflow_dispatch: + +# Least-privilege. `evict-stale-caches.sh` invokes `gh cache list` +# (read) and `gh cache delete` (write) against the caller's cache pool +# via secrets.GITHUB_TOKEN. The GHA Cache API lives under the actions: +# permission namespace, so deletion requires actions:write. `contents: +# read` covers the checkout that fetches this repo's scripts. +permissions: + actions: write + contents: read + +# Serialize runs so two overlapping firings (manual dispatch + schedule) +# don't both try to delete the same entry. +concurrency: + group: cache-cleanup + cancel-in-progress: false + +jobs: + evict-stale: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + # Pull the extracted script. Explicit `repository:` because — when + # this file is synced to a consumer — actions/checkout's default + # target is the CONSUMER's repo, not genlayer-e2e. github.token + # in the consumer context has org-wide read on private repos so + # the clone works without an App token. + - name: Checkout genlayer-e2e + uses: actions/checkout@v6 + with: + repository: genlayerlabs/genlayer-e2e + token: ${{ github.token }} + + - name: Delete idle caches + env: + # `gh cache delete` consumes GH_TOKEN. github.repository + # resolves to the caller's repo (where the cron fires + the + # cache pool lives). + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + run: ./taskfiles/housekeeper/scripts/evict-stale-caches.sh --age 24 --limit 200 + + # Companion sweep for artifacts (logs, shard outputs, per-component + # summaries). Same 24h idle window so the two sweeps stay in sync. + # `if: always()` so an early cache-sweep failure doesn't skip the + # artifact pass — they're independent. + - name: Delete idle artifacts + if: always() + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + run: ./taskfiles/housekeeper/scripts/evict-stale-artifacts.sh --age 24 --limit 1000 From b24bf5f89e79d7858b9f3835a9cde4efc1a15cf9 Mon Sep 17 00:00:00 2001 From: "ci-core-e2e-runner[bot]" <263344042+ci-core-e2e-runner[bot]@users.noreply.github.com> Date: Tue, 26 May 2026 21:26:14 +0100 Subject: [PATCH 09/14] ci(workflows): sync e2e.yml from genlayer-e2e (#176) Co-authored-by: ci-core-e2e-runner[bot] <263344042+ci-core-e2e-runner[bot]@users.noreply.github.com> --- .github/workflows/e2e.yml | 46 +++++++++++++++++++++++---------------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index efc2849..7ffb8e3 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -115,7 +115,7 @@ on: whose declared `stack-targets` don't include the chosen stack cascade-skip with reason "stack". required: false - default: all # SYNC_INJECT(default_stack) + default: all # SYNC_INJECT(default_stack) type: choice options: - all @@ -150,7 +150,7 @@ env: GCP_SECRET_APP_PRIVATE_KEY: ${{ vars.GCP_SECRET_APP_PRIVATE_KEY || 'ci-core-e2e-runner-app-private-key' }} # Suppress notify-outcome's compact PR banner. Detailed results # table still posted. Remove to re-enable. - E2E_REPORT_SKIP_RESULT: "true" + E2E_REPORT_SKIP_RESULT: 'true' jobs: # =========================================================================== @@ -215,7 +215,7 @@ jobs: # issue_comment `/run-e2e` with no stack token still routes to # the per-consumer default — inputs.stack is workflow_dispatch- # only and resolves empty on the issue_comment path. - stack: ${{ needs.acknowledge.outputs.stack-token || inputs.stack || 'all' }} # SYNC_INJECT(default_stack_fallback) + stack: ${{ needs.acknowledge.outputs.stack-token || inputs.stack || 'all' }} # SYNC_INJECT(default_stack_fallback) target-repo: ${{ github.repository }} pr-number: ${{ github.event.issue.number || '' }} comment-id: ${{ github.event.comment.id || '' }} @@ -602,7 +602,15 @@ jobs: # `.result` for the rough verdict. # =========================================================================== result: - needs: [acknowledge, plan, build, build-studio, wave-1, wave-2, wave-3, wave-4] + needs: + - acknowledge + - plan + - build + - build-studio + - wave-1 + - wave-2 + - wave-3 + - wave-4 # `always() && plan.result != 'skipped'` rather than bare `always()`: # noop issue_comments (any non-/run-e2e comment in this repo, since # the workflow lives at `on: issue_comment`) skip acknowledge → plan @@ -658,29 +666,29 @@ jobs: # the workflow conclusion. continue-on-error: true env: - PLAN_RESULT: ${{ needs.plan.result }} + PLAN_RESULT: ${{ needs.plan.result }} # BUILD_STATUS is the AND of the two stack-scoped builds, # but a build that wasn't requested (its stack filtered out # by /run-e2e ) counts as success — its job is # `skipped`, not `failure`. The contains() checks gate each # build's contribution by whether its stack-target appears # in the wave-plans output. - BUILD_STATUS: ${{ ((!contains(needs.plan.outputs.stack-config, '"target":"dev-env"') || needs.build.outputs.build-status == 'success') && (!contains(needs.plan.outputs.stack-config, '"target":"studio"') || needs.build-studio.outputs.build-status == 'success')) && 'success' || 'failure' }} - BUILD_RESULT: ${{ format('dev-env={0}, studio={1}', needs.build.result, needs.build-studio.result) }} + BUILD_STATUS: ${{ ((!contains(needs.plan.outputs.stack-config, '"target":"dev-env"') || needs.build.outputs.build-status == 'success') && (!contains(needs.plan.outputs.stack-config, '"target":"studio"') || needs.build-studio.outputs.build-status == 'success')) && 'success' || 'failure' }} + BUILD_RESULT: ${{ format('dev-env={0}, studio={1}', needs.build.result, needs.build-studio.result) }} # Classifier-emitted stage + detail surfaced in the build row's # Notes column when BUILD_STATUS != success. Empty when build # was a cache-hit (no execute job ran) — the aggregate script # falls back to the legacy verdict-word render. - BUILD_STAGE: ${{ (contains(needs.plan.outputs.stack-config, '"target":"studio"') && needs.build-studio.outputs.build-status != 'success') && 'build:studio' || needs.build.outputs.build-stage || '' }} - BUILD_DETAIL: ${{ (contains(needs.plan.outputs.stack-config, '"target":"studio"') && needs.build-studio.outputs.build-status != 'success') && 'Studio build failed' || needs.build.outputs.build-detail || '' }} - WAVE_1_RESULT: ${{ needs.wave-1.result }} - WAVE_1_PLAN: ${{ toJson(fromJson(needs.plan.outputs.wave-plans)['wave-1']) }} - WAVE_2_RESULT: ${{ needs.wave-2.result }} - WAVE_2_PLAN: ${{ toJson(fromJson(needs.plan.outputs.wave-plans)['wave-2']) }} - WAVE_3_RESULT: ${{ needs.wave-3.result }} - WAVE_3_PLAN: ${{ toJson(fromJson(needs.plan.outputs.wave-plans)['wave-3']) }} - WAVE_4_RESULT: ${{ needs.wave-4.result }} - WAVE_4_PLAN: ${{ toJson(fromJson(needs.plan.outputs.wave-plans)['wave-4']) }} + BUILD_STAGE: ${{ (contains(needs.plan.outputs.stack-config, '"target":"studio"') && needs.build-studio.outputs.build-status != 'success') && 'build:studio' || needs.build.outputs.build-stage || '' }} + BUILD_DETAIL: ${{ (contains(needs.plan.outputs.stack-config, '"target":"studio"') && needs.build-studio.outputs.build-status != 'success') && 'Studio build failed' || needs.build.outputs.build-detail || '' }} + WAVE_1_RESULT: ${{ needs.wave-1.result }} + WAVE_1_PLAN: ${{ toJson(fromJson(needs.plan.outputs.wave-plans)['wave-1']) }} + WAVE_2_RESULT: ${{ needs.wave-2.result }} + WAVE_2_PLAN: ${{ toJson(fromJson(needs.plan.outputs.wave-plans)['wave-2']) }} + WAVE_3_RESULT: ${{ needs.wave-3.result }} + WAVE_3_PLAN: ${{ toJson(fromJson(needs.plan.outputs.wave-plans)['wave-3']) }} + WAVE_4_RESULT: ${{ needs.wave-4.result }} + WAVE_4_PLAN: ${{ toJson(fromJson(needs.plan.outputs.wave-plans)['wave-4']) }} # Per-(component, stack-target) verdict directory (one file # per artifact, name == component, content ∈ {success, # failure, skipped}). Replaces the legacy single-value @@ -689,8 +697,8 @@ jobs: # artifacts step above. PR_NUMBER lets the script construct # the exact artifact path; on workflow_dispatch (no PR) the # run_id stands in, matching the wave jobs' pr-number input. - CONCLUSIONS_DIR: /tmp/test-conclusions - PR_NUMBER: ${{ github.event.issue.number || github.run_id }} + CONCLUSIONS_DIR: /tmp/test-conclusions + PR_NUMBER: ${{ github.event.issue.number || github.run_id }} run: ./taskfiles/runner/scripts/aggregate-wave-outcomes.sh # Final notify-outcome — flips 👀 → 🚀 (overall pass) or 👎 From 0ff92e42435c30e0a4e556a94fd7fca70ca0e438 Mon Sep 17 00:00:00 2001 From: "ci-core-e2e-runner[bot]" <263344042+ci-core-e2e-runner[bot]@users.noreply.github.com> Date: Tue, 26 May 2026 21:26:17 +0100 Subject: [PATCH 10/14] ci(workflows): sync e2e-housekeeper.yml from genlayer-e2e (#177) Co-authored-by: ci-core-e2e-runner[bot] <263344042+ci-core-e2e-runner[bot]@users.noreply.github.com> --- .github/workflows/e2e-housekeeper.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/e2e-housekeeper.yml b/.github/workflows/e2e-housekeeper.yml index ce911f5..50e64a6 100644 --- a/.github/workflows/e2e-housekeeper.yml +++ b/.github/workflows/e2e-housekeeper.yml @@ -25,7 +25,7 @@ name: E2E Housekeeper on: schedule: - - cron: '0 6 * * *' # daily 06:00 UTC + - cron: '0 6 * * *' # daily 06:00 UTC # No inputs: production triggers (schedule today, PR-merged later) # don't pass them, and the script's defaults (24h idle / 200 page # cap) are stable. workflow_dispatch stays as a no-arg "run the @@ -69,7 +69,7 @@ jobs: # resolves to the caller's repo (where the cron fires + the # cache pool lives). GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GH_REPO: ${{ github.repository }} + GH_REPO: ${{ github.repository }} run: ./taskfiles/housekeeper/scripts/evict-stale-caches.sh --age 24 --limit 200 # Companion sweep for artifacts (logs, shard outputs, per-component @@ -80,5 +80,5 @@ jobs: if: always() env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GH_REPO: ${{ github.repository }} + GH_REPO: ${{ github.repository }} run: ./taskfiles/housekeeper/scripts/evict-stale-artifacts.sh --age 24 --limit 1000 From 0bb78e01ccb3e1d669d2e044b7ee5e730528f3d5 Mon Sep 17 00:00:00 2001 From: Edgars Date: Tue, 2 Jun 2026 01:24:59 +0100 Subject: [PATCH 11/14] feat: add v0.6 fee-aware transactions --- README.md | 155 ++++ src/contracts/actions.ts | 1451 ++++++++++++++++++++++++++++--- src/index.ts | 1 + src/transactions/fees.ts | 226 +++++ src/types/clients.ts | 57 +- src/types/transactions.ts | 269 +++++- tests/contracts-actions.test.ts | 1243 +++++++++++++++++++++++++- 7 files changed, 3293 insertions(+), 109 deletions(-) create mode 100644 src/transactions/fees.ts diff --git a/README.md b/README.md index d99e336..39934b9 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,161 @@ const receipt = await client.waitForTransactionReceipt({ ``` +### Fee presets for transactions + +Apps can build a trusted fee preset once they know the transaction shape, then +submit the same preset with the transaction. The user may still override these +values in wallet or app UI before signing. + +```typescript +const estimate = await client.estimateTransactionFees({ + leaderTimeunitsAllocation: 100n, + validatorTimeunitsAllocation: 200n, + rotations: [0n], +}); + +const txHash = await client.writeContract({ + account, + address: contractAddress, + functionName: "update_storage", + args: ["new_storage"], + fees: { + distribution: estimate.distribution, + feeValue: estimate.feeValue, + }, +}); +``` + +If `fees.distribution` is provided without `feeValue`, the SDK derives the fee +deposit from FeeManager on network backends, or from `sim_getFeeConfig` on +Studio. Use `messageAllocations` with `estimateTransactionFees` for transactions +that can emit funded messages. + +Use the SDK call-key helpers when targeting a specific emitted message. Internal +messages are keyed by the GenVM method name; external EVM messages are keyed by +the first 4 bytes of the calldata selector. + +```typescript +import { + MessageType, + deriveExternalMessageCallKey, + deriveInternalMessageCallKey, + encodeExternalMessageFeeParams, + encodeInternalMessageFeeParams, +} from "genlayer-js"; + +const estimate = await client.estimateTransactionFees({ + messageAllocations: [ + { + messageType: MessageType.Internal, + recipient: childContractAddress, + callKey: deriveInternalMessageCallKey("settle_campaign"), + budget: 700_000n, + feeParams: encodeInternalMessageFeeParams({ + leaderTimeunitsAllocation: 100n, + validatorTimeunitsAllocation: 200n, + }), + }, + { + messageType: MessageType.External, + recipient: tokenAddress, + callKey: deriveExternalMessageCallKey("0xa9059cbb"), + budget: 210_000n, + feeParams: encodeExternalMessageFeeParams({ + gasLimit: 21_000n, + maxGasPrice: 10n, + }), + }, + ], +}); +``` + +You can also pass the same preset to Studio/localnet simulation. On Studio, +`includeReceipt` uses `sim_call` so the returned object includes the GenVM +receipt and fee accounting report: + +```typescript +const recommended = await client.estimateTransactionFeesForWrite({ + account, + address: contractAddress, + functionName: "update_storage", + args: ["new_storage"], +}); + +await client.writeContract({ + account, + address: contractAddress, + functionName: "update_storage", + args: ["new_storage"], + fees: { + distribution: recommended.distribution, + messageAllocations: recommended.messageAllocations, + feeValue: recommended.feeValue, + }, +}); +``` + +For tests or tools that need to inspect the raw simulation, use the explicit +two-step flow: + +```typescript +const simulation = await client.simulateWriteContract({ + account, + address: contractAddress, + functionName: "update_storage", + args: ["new_storage"], + fees: { + distribution: estimate.distribution, + feeValue: estimate.feeValue, + }, + includeReceipt: true, +}); + +console.log(simulation.feeAccounting); + +const recommended = await client.estimateTransactionFeesFromSimulation({ + simulation, +}); + +await client.writeContract({ + account, + address: contractAddress, + functionName: "update_storage", + args: ["new_storage"], + fees: { + distribution: recommended.distribution, + messageAllocations: recommended.messageAllocations, + feeValue: recommended.feeValue, + }, +}); +``` + +For transactions that are already submitted, use the fee-management helpers: + +```typescript +await client.topUpFees({ + txId, + value: 1_100n, + distribution: { + leaderTimeunitsAllocation: 100n, + validatorTimeunitsAllocation: 200n, + rotations: [0n], + }, +}); + +await client.topUpAndSubmitAppeal({ + txId, + value: 1_400n, + distribution: { + appealRounds: 1n, + rotations: [0n, 0n], + }, +}); +``` + +`topUpFees` returns the backend RPC hash. On network backends this is the EVM +transaction hash; on Studio/localnet it is the target GenLayer transaction id. + ### Checking execution results A transaction can be finalized by consensus but still have a failed execution. Always check `txExecutionResult` before reading contract state: diff --git a/src/contracts/actions.ts b/src/contracts/actions.ts index 13caeea..5c61747 100644 --- a/src/contracts/actions.ts +++ b/src/contracts/actions.ts @@ -9,31 +9,155 @@ import { CalldataEncodable, Address, TransactionHashVariant, + TransactionFeeOptions, + TransactionFeeEstimate, + FeeEstimateOptions, + SimulationFeeEstimateOptions, + SimulationFeeUsage, + WriteFeeEstimateOptions, + FeePolicyQuote, + BigNumberish, + FeesDistribution, + FeesDistributionInput, + MessageFeeAllocationInput, + MessageType, + SimulateWriteContractResult, + StudioExecutionFeeReport, + StudioFeeAccounting, } from "@/types"; import {fromHex, toHex, zeroAddress, encodeFunctionData, PublicClient, parseEventLogs, type Abi} from "viem"; import {TransactionHash} from "@/types/transactions"; import {toJsonSafeDeep, b64ToArray, arrayToB64} from "@/utils/jsonifier"; +import { + CALL_KEY_WILDCARD, + createFeesDistribution, + MESSAGE_ALLOCATION_ROOT_PARENT_INDEX, + normalizeMessageFeeAllocations, + normalizeTransactionFees, + NormalizedTransactionFees, +} from "@/transactions/fees"; + +const prefixHex = (hex: string): `0x${string}` => { + return (hex.startsWith("0x") ? hex : `0x${hex}`) as `0x${string}`; +}; /** - * Extract hex data from a gen_call result. + * Extract hex data from a simulation result. * Some RPCs return a bare hex string, others return an object like - * { data: "hex...", status: { code, message }, ... }. + * { data: "hex...", status: { code, message }, ... }. Studio's `sim_call` + * returns the full receipt with `result` as base64-encoded GenVM result bytes, + * where byte 0 is the result code and the payload starts at byte 1. */ function extractGenCallResult(result: unknown): `0x${string}` { if (typeof result === "string") { - return `0x${result}` as `0x${string}`; + return prefixHex(result); } if (result && typeof result === "object" && "data" in result) { const obj = result as {data: string; status?: {code: number; message: string}}; if (obj.status && obj.status.code !== 0) { throw new Error(`gen_call failed: ${obj.status.message}`); } - return `0x${obj.data}` as `0x${string}`; + return prefixHex(obj.data); + } + if (result && typeof result === "object" && "result" in result) { + const obj = result as {result: string; execution_result?: string}; + if (obj.execution_result && obj.execution_result !== "SUCCESS") { + throw new Error(`sim_call failed: ${obj.execution_result}`); + } + if (typeof obj.result === "string" && obj.result.startsWith("0x")) { + return prefixHex(obj.result); + } + const resultBytes = b64ToArray(obj.result); + if (resultBytes.length === 0) { + throw new Error("sim_call returned an empty result payload"); + } + return toHex(resultBytes.slice(1)); } - throw new Error(`Unexpected gen_call response: ${JSON.stringify(result)}`); + throw new Error(`Unexpected simulation response: ${JSON.stringify(result)}`); +} + +function normalizeGenCallReceipt(result: unknown, data: `0x${string}`): Record { + if (result && typeof result === "object" && !Array.isArray(result)) { + return result as Record; + } + return {data}; +} + +function extractGenCallFeeAccounting(result: unknown): StudioFeeAccounting | undefined { + if (!result || typeof result !== "object" || Array.isArray(result)) return undefined; + const genvmResult = (result as Record).genvm_result; + if (!genvmResult || typeof genvmResult !== "object" || Array.isArray(genvmResult)) return undefined; + const feeAccounting = (genvmResult as Record).fee_accounting; + if (!feeAccounting || typeof feeAccounting !== "object" || Array.isArray(feeAccounting)) return undefined; + return feeAccounting as StudioFeeAccounting; +} + +function extractGenCallFeeReport(feeAccounting?: StudioFeeAccounting): StudioExecutionFeeReport | undefined { + const report = feeAccounting?.execution_fee_report; + if (!report || typeof report !== "object" || Array.isArray(report)) return undefined; + return report; +} + +function transactionFeesToRpc(fees?: TransactionFeeOptions) { + if (!fees) return undefined; + const normalized = normalizeTransactionFees(fees); + return { + distribution: { + leaderTimeunitsAllocation: normalized.distribution.leaderTimeunitsAllocation.toString(), + validatorTimeunitsAllocation: normalized.distribution.validatorTimeunitsAllocation.toString(), + appealRounds: normalized.distribution.appealRounds.toString(), + executionBudgetPerRound: normalized.distribution.executionBudgetPerRound.toString(), + executionConsumed: normalized.distribution.executionConsumed.toString(), + totalMessageFees: normalized.distribution.totalMessageFees.toString(), + rotations: normalized.distribution.rotations.map((rotation) => rotation.toString()), + maxPriceGenPerTimeUnit: normalized.distribution.maxPriceGenPerTimeUnit.toString(), + storageFeeMaxGasPrice: normalized.distribution.storageFeeMaxGasPrice.toString(), + receiptFeeMaxGasPrice: normalized.distribution.receiptFeeMaxGasPrice.toString(), + }, + messageAllocations: normalized.messageAllocations.map((allocation) => ({ + messageType: allocation.messageType, + onAcceptance: allocation.onAcceptance, + parentIndex: allocation.parentIndex.toString(), + recipient: allocation.recipient, + callKey: allocation.callKey, + budget: allocation.budget.toString(), + feeParams: allocation.feeParams, + })), + ...(normalized.feeValue === undefined ? {} : {feeValue: normalized.feeValue.toString()}), + }; } export const contractActions = (client: GenLayerClient, publicClient: PublicClient) => { + const estimateFeeValue = async ( + distribution: FeesDistribution, + policy?: FeePolicyQuote, + ): Promise => { + if (client.chain.feeManagerContract?.address) { + const roundFees = await publicClient.readContract({ + address: client.chain.feeManagerContract.address as `0x${string}`, + abi: FEE_MANAGER_CALCULATE_ROUND_FEES_ABI as any, + functionName: "calculateRoundFees", + args: [ + distribution, + BigInt(client.chain.defaultNumberOfInitialValidators), + 0n, + ], + }) as bigint; + return roundFees + distribution.totalMessageFees; + } + + if (client.chain.isStudio) { + const studioPolicy = policy ?? await readCurrentFeePolicy(client, publicClient); + return calculateLocalRoundFees( + distribution, + client.chain.defaultNumberOfInitialValidators, + studioPolicy, + ) + distribution.totalMessageFees; + } + + throw new Error("Fee value estimation is not supported on this chain (missing feeManagerContract)."); + }; + return { /** Retrieves the source code of a deployed contract. */ getContractCode: async (address: Address): Promise => { @@ -139,22 +263,32 @@ export const contractActions = (client: GenLayerClient, publicCli return toJsonSafeDeep(decoded) as any; }, /** Simulates a state-modifying contract call without executing on-chain. */ - simulateWriteContract: async (args: { + simulateWriteContract: async < + RawReturn extends boolean | undefined = undefined, + IncludeReceipt extends boolean | undefined = undefined, + >(args: { account?: Account; address: Address; functionName: string; args?: CalldataEncodable[]; kwargs?: Map | {[key: string]: CalldataEncodable}; rawReturn?: RawReturn; + includeReceipt?: IncludeReceipt; + value?: BigNumberish; leaderOnly?: boolean; + fees?: TransactionFeeOptions; transactionHashVariant?: TransactionHashVariant; - }): Promise => { + }): Promise + : RawReturn extends true ? `0x${string}` : CalldataEncodable> => { const { account, address, functionName, args: callArgs, kwargs, + value, + fees, leaderOnly = false, transactionHashVariant = TransactionHashVariant.LATEST_NONFINAL, } = args; @@ -164,24 +298,51 @@ export const contractActions = (client: GenLayerClient, publicCli const senderAddress = account?.address ?? client.account?.address ?? zeroAddress; - const requestParams = { + const requestParams: Record = { type: "write", to: address, from: senderAddress, data: serializedData, transaction_hash_variant: transactionHashVariant, }; + const userValue = toUInt(value, "value", 0n); + if (userValue > 0n) { + requestParams.value = toHex(userValue); + } + const rpcFees = transactionFeesToRpc(fees); + if (rpcFees) { + requestParams.fees = rpcFees; + } + const simulationMethod = args.includeReceipt && client.chain.isStudio ? "sim_call" : "gen_call"; const result = await client.request({ - method: "gen_call", + method: simulationMethod, params: [requestParams], }); const prefixedResult = extractGenCallResult(result); + let decodedResult: `0x${string}` | CalldataEncodable; if (args.rawReturn) { - return prefixedResult; + decodedResult = prefixedResult; + } else { + const resultBinary = fromHex(prefixedResult, "bytes"); + decodedResult = calldata.decode(resultBinary) as any; } - const resultBinary = fromHex(prefixedResult, "bytes"); - return calldata.decode(resultBinary) as any; + + if (args.includeReceipt) { + const feeAccounting = extractGenCallFeeAccounting(result); + return { + result: decodedResult, + receipt: normalizeGenCallReceipt(result, prefixedResult), + feeAccounting, + feeReport: extractGenCallFeeReport(feeAccounting), + } as IncludeReceipt extends true + ? SimulateWriteContractResult + : RawReturn extends true ? `0x${string}` : CalldataEncodable; + } + + return decodedResult as IncludeReceipt extends true + ? SimulateWriteContractResult + : RawReturn extends true ? `0x${string}` : CalldataEncodable; }, /** Executes a state-modifying function on a contract through consensus. Returns the transaction hash. */ writeContract: async (args: { @@ -190,9 +351,11 @@ export const contractActions = (client: GenLayerClient, publicCli functionName: string; args?: CalldataEncodable[]; kwargs?: Map | {[key: string]: CalldataEncodable}; - value: bigint; + value?: bigint; leaderOnly?: boolean; consensusMaxRotations?: number; + validUntil?: BigNumberish; + fees?: TransactionFeeOptions; }): Promise<`0x${string}`> => { const { account, @@ -203,25 +366,34 @@ export const contractActions = (client: GenLayerClient, publicCli value = 0n, leaderOnly = false, consensusMaxRotations = client.chain.defaultConsensusMaxRotations, + validUntil, + fees, } = args; const data = [calldata.encode(calldata.makeCalldataObject(functionName, callArgs, kwargs)), leaderOnly]; const serializedData = serialize(data); const senderAccount = account || client.account; - const {primaryEncodedData, fallbackEncodedData} = _encodeAddTransactionData({ + const transactionFees = await _resolveTransactionFees({ + client, + publicClient, + fees, + numOfInitialValidators: client.chain.defaultNumberOfInitialValidators, + }); + const transactionVariants = _encodeAddTransactionData({ client, senderAccount, recipient: address, data: serializedData, consensusMaxRotations, + validUntil, + userValue: value, + transactionFees, }); return _sendTransaction({ client, publicClient, - encodedData: primaryEncodedData, - fallbackEncodedData, + transactionVariants, senderAccount, - value, }); }, /** Deploys a new intelligent contract to GenLayer. Returns the transaction hash. */ @@ -232,6 +404,8 @@ export const contractActions = (client: GenLayerClient, publicCli kwargs?: Map | {[key: string]: CalldataEncodable}; leaderOnly?: boolean; consensusMaxRotations?: number; + validUntil?: BigNumberish; + fees?: TransactionFeeOptions; }) => { const { account, @@ -240,6 +414,8 @@ export const contractActions = (client: GenLayerClient, publicCli kwargs, leaderOnly = false, consensusMaxRotations = client.chain.defaultConsensusMaxRotations, + validUntil, + fees, } = args; const data = [ @@ -249,21 +425,178 @@ export const contractActions = (client: GenLayerClient, publicCli ]; const serializedData = serialize(data); const senderAccount = account || client.account; - const {primaryEncodedData, fallbackEncodedData} = _encodeAddTransactionData({ + const transactionFees = await _resolveTransactionFees({ + client, + publicClient, + fees, + numOfInitialValidators: client.chain.defaultNumberOfInitialValidators, + }); + const transactionVariants = _encodeAddTransactionData({ client, senderAccount, recipient: zeroAddress, data: serializedData, consensusMaxRotations, + validUntil, + userValue: 0n, + transactionFees, }); return _sendTransaction({ client, publicClient, - encodedData: primaryEncodedData, - fallbackEncodedData, + transactionVariants, senderAccount, }); }, + /** Returns the active fee price policy used to build user-side caps. */ + getCurrentFeePolicy: async (): Promise => { + return readCurrentFeePolicy(client, publicClient); + }, + /** Builds a fee distribution with caps derived from the active fee policy. */ + estimateFeesDistribution: async (args?: FeeEstimateOptions): Promise => { + const policy = await readCurrentFeePolicy(client, publicClient); + return buildEstimatedFeesDistribution(args, policy); + }, + /** + * Builds a complete transaction `fees` object, including feeValue. + * Studio has no on-chain FeeManager in the chain definition, so this uses + * the same deterministic round-fee math as Studio trusted mode there. + */ + estimateTransactionFees: async (args?: FeeEstimateOptions): Promise => { + const policy = await readCurrentFeePolicy(client, publicClient); + const distribution = buildEstimatedFeesDistribution(args, policy); + + return { + distribution, + messageAllocations: args?.messageAllocations, + feeValue: await estimateFeeValue(distribution, policy), + policy, + }; + }, + /** + * Builds a trusted fee preset from a representative Studio simulation. + * This turns the returned fee accounting/report into execution and message + * budgets while preserving mode-2 message allocations when the simulation + * was run with them. + */ + estimateTransactionFeesFromSimulation: async ( + args: SimulationFeeEstimateOptions, + ): Promise => { + const policy = await readCurrentFeePolicy(client, publicClient); + const {estimateOptions, observed, messageAllocations} = + buildEstimatedFeesOptionsFromSimulation(args, policy); + const distribution = buildEstimatedFeesDistribution(estimateOptions, policy); + + return { + distribution, + messageAllocations, + feeValue: await estimateFeeValue(distribution, policy), + policy, + observed, + }; + }, + /** + * Builds a trusted fee preset for a concrete write call in one step. + * The method first gives the simulation a baseline fee budget, then uses + * the returned Studio/GenVM fee accounting to derive the preset the dapp + * should pass with the real transaction. + */ + estimateTransactionFeesForWrite: async ( + args: WriteFeeEstimateOptions, + ): Promise => { + const { + account, + address, + functionName, + args: callArgs, + kwargs, + value, + leaderOnly = false, + transactionHashVariant = TransactionHashVariant.LATEST_NONFINAL, + executionHeadroomBps, + messageHeadroomBps, + ...feeOptions + } = args; + + const policy = await readCurrentFeePolicy(client, publicClient); + const initialDistribution = buildEstimatedFeesDistribution(feeOptions, policy); + const initialEstimate: TransactionFeeEstimate = { + distribution: initialDistribution, + messageAllocations: feeOptions.messageAllocations, + feeValue: await estimateFeeValue(initialDistribution, policy), + policy, + }; + + const encodedData = [ + calldata.encode(calldata.makeCalldataObject(functionName, callArgs, kwargs)), + leaderOnly, + ]; + const serializedData = serialize(encodedData); + const senderAddress = account?.address ?? client.account?.address ?? zeroAddress; + const requestParams: Record = { + type: "write", + to: address, + from: senderAddress, + data: serializedData, + transaction_hash_variant: transactionHashVariant, + }; + const userValue = toUInt(value, "value", 0n); + if (userValue > 0n) { + requestParams.value = toHex(userValue); + } + const rpcFees = transactionFeesToRpc({ + distribution: initialEstimate.distribution, + messageAllocations: initialEstimate.messageAllocations, + feeValue: initialEstimate.feeValue, + }); + if (rpcFees) { + requestParams.fees = rpcFees; + } + + if (client.chain.isStudio) { + const studioEstimate = await client.request({ + method: "sim_estimateTransactionFees", + params: [requestParams], + }); + const authoritativeEstimate = transactionFeeEstimateFromStudioEstimate( + studioEstimate, + policy, + ); + if (authoritativeEstimate) { + return authoritativeEstimate; + } + } + + const simulationResult = await client.request({ + method: "gen_call", + params: [requestParams], + }); + extractGenCallResult(simulationResult); + const feeAccounting = extractGenCallFeeAccounting(simulationResult); + const simulation = { + feeAccounting, + feeReport: extractGenCallFeeReport(feeAccounting), + }; + const {estimateOptions, observed, messageAllocations} = + buildEstimatedFeesOptionsFromSimulation( + { + ...feeOptions, + executionHeadroomBps, + messageHeadroomBps, + simulation, + }, + policy, + ); + const distribution = buildEstimatedFeesDistribution(estimateOptions, policy); + + return { + distribution, + messageAllocations, + feeValue: await estimateFeeValue(distribution, policy), + policy, + observed, + }; + }, /** Calculates the minimum bond required to appeal a transaction. */ getMinAppealBond: async (args: {txId: `0x${string}`}): Promise => { const {txId} = args; @@ -346,30 +679,7 @@ export const contractActions = (client: GenLayerClient, publicCli value?: bigint; }) => { const {account, txId} = args; - let {value} = args; - - if (value === undefined) { - if (client.chain.feeManagerContract?.address && client.chain.roundsStorageContract?.address) { - const roundNumber = await publicClient.readContract({ - address: client.chain.roundsStorageContract.address as `0x${string}`, - abi: client.chain.roundsStorageContract.abi as Abi, - functionName: "getRoundNumber", - args: [txId], - }) as bigint; - - const transaction = await client.getTransaction({hash: txId as TransactionHash}); - const txStatus = Number(transaction.status); - - value = await publicClient.readContract({ - address: client.chain.feeManagerContract.address as `0x${string}`, - abi: client.chain.feeManagerContract.abi as Abi, - functionName: "calculateMinAppealBond", - args: [txId, roundNumber, txStatus], - }) as bigint; - } else { - value = 0n; - } - } + const value = await _resolveAppealValue({client, publicClient, txId, value: args.value}); const senderAccount = account || client.account; const encodedData = _encodeSubmitAppealData({client, txId}); @@ -386,6 +696,54 @@ export const contractActions = (client: GenLayerClient, publicCli }); return txId; }, + /** + * Deposits additional fee budget for an existing consensus transaction. + * Returns the backend RPC hash: an EVM transaction hash on network + * backends, or the target GenLayer tx id on Studio/localnet. + */ + topUpFees: async (args: { + account?: Account; + txId: `0x${string}`; + distribution: FeesDistributionInput; + value: bigint; + }): Promise<`0x${string}`> => { + const {account, txId, distribution, value} = args; + const senderAccount = account || client.account; + const encodedData = _encodeTopUpFeesData({txId, distribution}); + return _sendConsensusCall({ + client, + publicClient, + encodedData, + senderAccount, + value, + operationName: "Top up fees", + }); + }, + /** + * Deposits appeal fee budget and submits an appeal in the same consensus call. + * Returns the existing GenLayer transaction id, matching appealTransaction. + */ + topUpAndSubmitAppeal: async (args: { + account?: Account; + txId: `0x${string}`; + distribution: FeesDistributionInput; + value?: bigint; + }): Promise<`0x${string}`> => { + const {account, txId, distribution} = args; + const value = await _resolveAppealValue({client, publicClient, txId, value: args.value}); + + const senderAccount = account || client.account; + const encodedData = _encodeTopUpAndSubmitAppealData({txId, distribution}); + await _sendConsensusCall({ + client, + publicClient, + encodedData, + senderAccount, + value, + operationName: "Top up and submit appeal", + }); + return txId; + }, /** Finalizes a single GenLayer transaction that is ready to be finalized. Returns the EVM transaction hash. */ finalizeTransaction: async (args: { account?: Account; @@ -473,7 +831,7 @@ const ADD_TRANSACTION_ABI_V6 = [ { type: "function", name: "addTransaction", - stateMutability: "nonpayable", + stateMutability: "payable", inputs: [ {name: "_sender", type: "address"}, {name: "_recipient", type: "address"}, @@ -486,9 +844,124 @@ const ADD_TRANSACTION_ABI_V6 = [ }, ] as const; -const getAddTransactionInputCount = (abi: readonly unknown[] | undefined): number => { +const FEES_DISTRIBUTION_COMPONENTS = [ + {name: "leaderTimeunitsAllocation", type: "uint256"}, + {name: "validatorTimeunitsAllocation", type: "uint256"}, + {name: "appealRounds", type: "uint256"}, + {name: "executionBudgetPerRound", type: "uint256"}, + {name: "executionConsumed", type: "uint256"}, + {name: "totalMessageFees", type: "uint256"}, + {name: "rotations", type: "uint256[]"}, + {name: "maxPriceGenPerTimeUnit", type: "uint256"}, + {name: "storageFeeMaxGasPrice", type: "uint256"}, + {name: "receiptFeeMaxGasPrice", type: "uint256"}, +] as const; + +const MESSAGE_FEE_ALLOCATION_COMPONENTS = [ + {name: "messageType", type: "uint8"}, + {name: "onAcceptance", type: "bool"}, + {name: "parentIndex", type: "uint256"}, + {name: "recipient", type: "address"}, + {name: "callKey", type: "bytes32"}, + {name: "budget", type: "uint256"}, + {name: "feeParams", type: "bytes"}, +] as const; + +const ADD_TRANSACTION_PARAMS_COMPONENTS = [ + {name: "sender", type: "address"}, + {name: "recipient", type: "address"}, + {name: "numOfInitialValidators", type: "uint256"}, + {name: "maxRotations", type: "uint256"}, + {name: "validUntil", type: "uint256"}, + {name: "saltNonce", type: "uint256"}, + {name: "userValue", type: "uint256"}, + {name: "feesDistribution", type: "tuple", components: FEES_DISTRIBUTION_COMPONENTS}, + {name: "txCalldata", type: "bytes"}, + {name: "messageAllocations", type: "tuple[]", components: MESSAGE_FEE_ALLOCATION_COMPONENTS}, +] as const; + +const ADD_TRANSACTION_ABI_WITH_FEES = [ + { + type: "function", + name: "addTransaction", + stateMutability: "payable", + inputs: [ + {name: "_params", type: "tuple", components: ADD_TRANSACTION_PARAMS_COMPONENTS}, + ], + outputs: [], + }, +] as const; + +const CONSENSUS_FEE_MANAGEMENT_ABI = [ + { + type: "function", + name: "topUpFees", + stateMutability: "payable", + inputs: [ + {name: "_txId", type: "bytes32"}, + {name: "_feesDistribution", type: "tuple", components: FEES_DISTRIBUTION_COMPONENTS}, + ], + outputs: [], + }, + { + type: "function", + name: "topUpAndSubmitAppeal", + stateMutability: "payable", + inputs: [ + {name: "_txId", type: "bytes32"}, + {name: "_feesDistribution", type: "tuple", components: FEES_DISTRIBUTION_COMPONENTS}, + ], + outputs: [], + }, +] as const; + +const FEE_MANAGER_CALCULATE_ROUND_FEES_ABI = [ + { + type: "function", + name: "GENPerTimeUnit", + stateMutability: "view", + inputs: [], + outputs: [{name: "", type: "uint256"}], + }, + { + type: "function", + name: "storageUnitPrice", + stateMutability: "view", + inputs: [], + outputs: [{name: "", type: "uint256"}], + }, + { + type: "function", + name: "quoteGasPrice", + stateMutability: "view", + inputs: [], + outputs: [{name: "", type: "uint256"}], + }, + { + type: "function", + name: "messageFeeParamsBudgetFloor", + stateMutability: "view", + inputs: [], + outputs: [{name: "", type: "uint256"}], + }, + { + type: "function", + name: "calculateRoundFees", + stateMutability: "view", + inputs: [ + {name: "_feesDistribution", type: "tuple", components: FEES_DISTRIBUTION_COMPONENTS}, + {name: "_numOfValidators", type: "uint256"}, + {name: "round", type: "uint256"}, + ], + outputs: [{name: "totalFeesToPay", type: "uint256"}], + }, +] as const; + +type AddTransactionAbiVersion = "fees" | "v6" | "v5"; + +const getAddTransactionAbiVersion = (abi: readonly unknown[] | undefined): AddTransactionAbiVersion => { if (!abi || !Array.isArray(abi)) { - return 0; + return "v5"; } const addTransactionFunction = abi.find(item => { @@ -498,9 +971,631 @@ const getAddTransactionInputCount = (abi: readonly unknown[] | undefined): numbe const candidate = item as {type?: string; name?: string}; return candidate.type === "function" && candidate.name === "addTransaction"; - }) as {inputs?: readonly unknown[]} | undefined; + }) as {inputs?: readonly {type?: string; components?: readonly unknown[]}[]} | undefined; + + const inputs = addTransactionFunction?.inputs; + if (!Array.isArray(inputs)) { + return "v5"; + } + + if (inputs.length === 1 && inputs[0]?.type === "tuple") { + return "fees"; + } + + return inputs.length >= 6 ? "v6" : "v5"; +}; + +type EncodedTransactionVariant = { + encodedData: `0x${string}`; + value: bigint; +}; + +const toUInt = (value: BigNumberish | undefined, fieldName: string, fallback: bigint): bigint => { + if (value === undefined) { + return fallback; + } + if (typeof value === "number" && !Number.isSafeInteger(value)) { + throw new Error(`${fieldName} must be a safe integer when provided as a number.`); + } + const normalized = BigInt(value); + if (normalized < 0n) { + throw new Error(`${fieldName} must be greater than or equal to zero.`); + } + return normalized; +}; + +const getDefaultValidUntil = () => BigInt(Math.floor(Date.now() / 1000) + 3600); + +const requiresFeeDepositCalculation = (distribution: FeesDistribution): boolean => ( + distribution.leaderTimeunitsAllocation !== 0n || + distribution.validatorTimeunitsAllocation !== 0n || + distribution.executionBudgetPerRound !== 0n || + distribution.totalMessageFees !== 0n +); + +const DEFAULT_PRICE_CAP_HEADROOM_BPS = 12_000n; +const DEFAULT_LEADER_TIMEUNITS_ALLOCATION = 100n; +const DEFAULT_VALIDATOR_TIMEUNITS_ALLOCATION = 200n; +const DEFAULT_TRANSACTION_EXECUTION_BUDGET_PER_ROUND = 500_000n; +const MIN_RECEIPT_BYTES = 512n; +const DEFAULT_RECEIPT_SLOTS_CHANGED = 7n; +const DEFAULT_INTRINSIC_GAS = 21_000n; +const DEFAULT_BOOTLOADER_OVERHEAD = 60_000n; +const DEFAULT_GAS_PER_CHANGED_SLOT = 1_000n; +const DEFAULT_CALLDATA_GAS_PER_BYTE = 16n; +const DEFAULT_FIXED_PROPOSE_RECEIPT_GAS = 210_000n; +const TRANSACTION_GAS_HEADROOM_BPS = 20_000n; +const VALIDATORS_PER_ROUND = [ + 5n, + 7n, + 11n, + 13n, + 23n, + 25n, + 47n, + 49n, + 95n, + 97n, + 191n, + 193n, + 383n, + 385n, + 767n, + 769n, + 1535n, + 1537n, +] as const; + +const withCapHeadroom = (value: bigint, headroomBps: bigint): bigint => { + if (value === 0n) return 0n; + return (value * headroomBps + 9_999n) / 10_000n; +}; + +const withTransactionGasHeadroom = (value: bigint): bigint => { + if (value === 0n) return 0n; + return (value * TRANSACTION_GAS_HEADROOM_BPS + 9_999n) / 10_000n; +}; - return Array.isArray(addTransactionFunction?.inputs) ? addTransactionFunction.inputs.length : 0; +const bigintFromUnknown = (value: unknown, fieldName: string, fallback = 0n): bigint => { + if (value == null) return fallback; + if (typeof value === "bigint") return value; + if (typeof value === "number" && Number.isSafeInteger(value)) return BigInt(value); + if (typeof value === "string" && value.trim() !== "") return BigInt(value); + throw new Error(`${fieldName} is not an integer value.`); +}; + +const extractStudioFeePolicy = (config: unknown): FeePolicyQuote => { + const configRecord = config && typeof config === "object" && !Array.isArray(config) + ? config as Record + : undefined; + const policy = configRecord?.policy; + const enabled = configRecord?.enabled; + if (enabled !== undefined && typeof enabled !== "boolean") { + throw new Error(`sim_getFeeConfig enabled flag is not a boolean.`); + } + + const policyRecord = policy && typeof policy === "object" && !Array.isArray(policy) + ? policy as Record + : undefined; + if (!policyRecord) { + throw new Error(`sim_getFeeConfig did not expose a policy object.`); + } + const genPerTimeUnit = bigintFromUnknown(policyRecord.genPerTimeUnit, "policy.genPerTimeUnit"); + const storageUnitPrice = bigintFromUnknown(policyRecord.storageUnitPrice, "policy.storageUnitPrice"); + const receiptGasPrice = bigintFromUnknown(policyRecord.receiptGasPrice, "policy.receiptGasPrice"); + const intrinsicGas = bigintFromUnknown(policyRecord.intrinsicGas, "policy.intrinsicGas", DEFAULT_INTRINSIC_GAS); + const bootloaderOverhead = bigintFromUnknown( + policyRecord.bootloaderOverhead, + "policy.bootloaderOverhead", + DEFAULT_BOOTLOADER_OVERHEAD, + ); + const gasPerChangedSlot = bigintFromUnknown( + policyRecord.gasPerChangedSlot, + "policy.gasPerChangedSlot", + DEFAULT_GAS_PER_CHANGED_SLOT, + ); + const calldataGasPerByte = bigintFromUnknown( + policyRecord.calldataGasPerByte, + "policy.calldataGasPerByte", + DEFAULT_CALLDATA_GAS_PER_BYTE, + ); + const fixedProposeReceiptGas = bigintFromUnknown( + policyRecord.fixedProposeReceiptGas, + "policy.fixedProposeReceiptGas", + DEFAULT_FIXED_PROPOSE_RECEIPT_GAS, + ); + const executionBudgetFloor = policyRecord.messageFeeParamsBudgetFloor == null + ? receiptGasPrice * ( + fixedProposeReceiptGas + + intrinsicGas + + bootloaderOverhead + + (MIN_RECEIPT_BYTES * calldataGasPerByte) + + (DEFAULT_RECEIPT_SLOTS_CHANGED * gasPerChangedSlot) + ) + : bigintFromUnknown( + policyRecord.messageFeeParamsBudgetFloor, + "policy.messageFeeParamsBudgetFloor", + ); + + return { + enabled: enabled ?? ( + genPerTimeUnit > 0n || + storageUnitPrice > 0n || + receiptGasPrice > 0n + ), + genPerTimeUnit, + storageUnitPrice, + receiptGasPrice, + executionBudgetFloor, + }; +}; + +const readCurrentFeePolicy = async ( + client: GenLayerClient, + publicClient: PublicClient, +): Promise => { + if (client.chain.isStudio) { + const config = await client.request({method: "sim_getFeeConfig", params: []}); + return extractStudioFeePolicy(config); + } + + if (!client.chain.feeManagerContract?.address) { + throw new Error("Fee policy estimation is not supported on this chain (missing feeManagerContract)."); + } + + const address = client.chain.feeManagerContract.address as `0x${string}`; + const abi = FEE_MANAGER_CALCULATE_ROUND_FEES_ABI as any; + const [genPerTimeUnit, storageUnitPrice, receiptGasPrice, executionBudgetFloor] = await Promise.all([ + publicClient.readContract({address, abi, functionName: "GENPerTimeUnit", args: []}) as Promise, + publicClient.readContract({address, abi, functionName: "storageUnitPrice", args: []}) as Promise, + publicClient.readContract({address, abi, functionName: "quoteGasPrice", args: []}) as Promise, + publicClient.readContract({address, abi, functionName: "messageFeeParamsBudgetFloor", args: []}) as Promise, + ]); + + return { + enabled: genPerTimeUnit > 0n || storageUnitPrice > 0n || receiptGasPrice > 0n, + genPerTimeUnit, + storageUnitPrice, + receiptGasPrice, + executionBudgetFloor, + }; +}; + +const maxBigint = (...values: bigint[]): bigint => values.reduce( + (max, value) => value > max ? value : max, + 0n, +); + +const defaultExecutionBudgetPerRound = (policy: FeePolicyQuote): bigint => { + if (!policy.enabled || (policy.storageUnitPrice === 0n && policy.receiptGasPrice === 0n)) { + return 0n; + } + + return maxBigint( + DEFAULT_TRANSACTION_EXECUTION_BUDGET_PER_ROUND, + policy.executionBudgetFloor, + ); +}; + +const buildEstimatedFeesDistribution = ( + options: FeeEstimateOptions | undefined, + policy: FeePolicyQuote, +): FeesDistribution => { + const headroomBps = toUInt( + options?.priceCapHeadroomBps, + "priceCapHeadroomBps", + DEFAULT_PRICE_CAP_HEADROOM_BPS, + ); + const executionBudgetDefault = defaultExecutionBudgetPerRound(policy); + const totalMessageFees = options?.totalMessageFees ?? ( + options?.messageAllocations + ? normalizeMessageFeeAllocations(options.messageAllocations).reduce( + (sum, allocation) => { + if ( + allocation.messageType === MessageType.External || + allocation.parentIndex === MESSAGE_ALLOCATION_ROOT_PARENT_INDEX + ) { + return sum + allocation.budget; + } + return sum; + }, + 0n, + ) + : undefined + ); + + return createFeesDistribution({ + leaderTimeunitsAllocation: options?.leaderTimeunitsAllocation ?? ( + policy.enabled ? DEFAULT_LEADER_TIMEUNITS_ALLOCATION : 0n + ), + validatorTimeunitsAllocation: options?.validatorTimeunitsAllocation ?? ( + policy.enabled ? DEFAULT_VALIDATOR_TIMEUNITS_ALLOCATION : 0n + ), + appealRounds: options?.appealRounds, + executionBudgetPerRound: options?.executionBudgetPerRound ?? executionBudgetDefault, + executionConsumed: options?.executionConsumed, + totalMessageFees, + rotations: options?.rotations, + maxPriceGenPerTimeUnit: + options?.maxPriceGenPerTimeUnit ?? withCapHeadroom(policy.genPerTimeUnit, headroomBps), + storageFeeMaxGasPrice: + options?.storageFeeMaxGasPrice ?? withCapHeadroom(policy.storageUnitPrice, headroomBps), + receiptFeeMaxGasPrice: + options?.receiptFeeMaxGasPrice ?? withCapHeadroom(policy.receiptGasPrice, headroomBps), + }); +}; + +const asRecord = (value: unknown): Record | undefined => ( + value && typeof value === "object" && !Array.isArray(value) + ? value as Record + : undefined +); + +const feeAccountingFromSimulation = ( + simulation: SimulationFeeEstimateOptions["simulation"], +): StudioFeeAccounting | undefined => { + const direct = simulation.feeAccounting; + if (direct) return direct; + + const receipt = asRecord((simulation as {receipt?: unknown}).receipt); + const genvmResult = asRecord(receipt?.genvm_result); + const feeAccounting = asRecord(genvmResult?.fee_accounting); + return feeAccounting as StudioFeeAccounting | undefined; +}; + +const messageAllocationsFromAccounting = ( + accounting: StudioFeeAccounting | undefined, +): MessageFeeAllocationInput[] | undefined => { + if (!Array.isArray(accounting?.message_allocations) || accounting.message_allocations.length === 0) { + return undefined; + } + + return accounting.message_allocations.map((raw, index) => { + const allocation = asRecord(raw); + if (!allocation) { + throw new Error(`simulation.feeAccounting.message_allocations[${index}] must be an object.`); + } + return { + messageType: Number(toUInt( + allocation.messageType as BigNumberish | undefined, + `simulation.feeAccounting.message_allocations[${index}].messageType`, + 0n, + )) as MessageType, + onAcceptance: Boolean(allocation.onAcceptance), + parentIndex: toUInt( + allocation.parentIndex as BigNumberish | undefined, + `simulation.feeAccounting.message_allocations[${index}].parentIndex`, + MESSAGE_ALLOCATION_ROOT_PARENT_INDEX, + ), + recipient: String(allocation.recipient ?? zeroAddress) as Address, + callKey: prefixHex(String(allocation.callKey ?? CALL_KEY_WILDCARD)) as `0x${string}`, + budget: toUInt( + allocation.budget as BigNumberish | undefined, + `simulation.feeAccounting.message_allocations[${index}].budget`, + 0n, + ), + feeParams: prefixHex(String(allocation.feeParams ?? "0x")) as `0x${string}`, + }; + }); +}; + +const observedSimulationFeeUsage = ( + args: SimulationFeeEstimateOptions, + policy: FeePolicyQuote, +): SimulationFeeUsage => { + const accounting = feeAccountingFromSimulation(args.simulation); + const report = args.simulation.feeReport ?? accounting?.execution_fee_report; + const executionHeadroomBps = toUInt( + args.executionHeadroomBps, + "executionHeadroomBps", + DEFAULT_PRICE_CAP_HEADROOM_BPS, + ); + const messageHeadroomBps = toUInt( + args.messageHeadroomBps, + "messageHeadroomBps", + DEFAULT_PRICE_CAP_HEADROOM_BPS, + ); + + const executionFeeConsumed = bigintFromUnknown( + accounting?.execution_fee_consumed, + "simulation.feeAccounting.execution_fee_consumed", + ); + const executionFeeReportTotal = bigintFromUnknown( + report?.totalEstimatedFee, + "simulation.feeReport.totalEstimatedFee", + ); + const observedExecutionBudget = executionFeeConsumed + executionFeeReportTotal; + const recommendedExecutionBudgetPerRound = observedExecutionBudget > 0n + ? maxBigint( + defaultExecutionBudgetPerRound(policy), + withCapHeadroom(observedExecutionBudget, executionHeadroomBps), + ) + : 0n; + + const messageFeeConsumed = bigintFromUnknown( + accounting?.message_fee_consumed, + "simulation.feeAccounting.message_fee_consumed", + ); + const genvmMessageFeeConsumed = bigintFromUnknown( + accounting?.genvm_message_fee_consumed, + "simulation.feeAccounting.genvm_message_fee_consumed", + ); + const messageFeeBudget = bigintFromUnknown( + accounting?.message_fee_budget, + "simulation.feeAccounting.message_fee_budget", + ); + const externalMessageReimbursed = bigintFromUnknown( + accounting?.external_message_fee_reimbursed, + "simulation.feeAccounting.external_message_fee_reimbursed", + ); + const messageFeeRefunded = bigintFromUnknown( + accounting?.message_fee_refunded, + "simulation.feeAccounting.message_fee_refunded", + ); + const externalMessageReserved = bigintFromUnknown( + accounting?.external_message_fee_reserved, + "simulation.feeAccounting.external_message_fee_reserved", + ); + const externalMessageRemainder = bigintFromUnknown( + accounting?.external_message_fee_remainder, + "simulation.feeAccounting.external_message_fee_remainder", + ); + const internalDeclaredBudget = (report?.messageReveal?.messages ?? []).reduce( + (sum, message, index) => ( + message.messageType === "Internal" + ? sum + bigintFromUnknown( + message.declaredBudget, + `simulation.feeReport.messageReveal.messages[${index}].declaredBudget`, + ) + : sum + ), + 0n, + ); + const observedMessageBudget = maxBigint( + messageFeeConsumed, + internalDeclaredBudget + externalMessageReimbursed, + ); + + return { + executionFeeConsumed, + executionFeeReportTotal, + recommendedExecutionBudgetPerRound, + genvmMessageFeeConsumed, + messageFeeBudget, + messageFeeConsumed, + messageFeeRefunded, + internalDeclaredBudget, + externalMessageReserved, + externalMessageReimbursed, + externalMessageRemainder, + recommendedTotalMessageFees: observedMessageBudget > 0n + ? withCapHeadroom(observedMessageBudget, messageHeadroomBps) + : 0n, + }; +}; + +const transactionFeeEstimateFromStudioEstimate = ( + result: unknown, + policy: FeePolicyQuote, +): TransactionFeeEstimate | undefined => { + const estimate = asRecord(result); + const preset = asRecord(estimate?.recommendedPreset); + const distributionInput = asRecord(preset?.distribution); + if (!preset || !distributionInput || preset.feeValue === undefined) { + return undefined; + } + + const rawAllocations = Array.isArray(preset.messageAllocations) + ? preset.messageAllocations as MessageFeeAllocationInput[] + : undefined; + const feeAccounting = asRecord(estimate?.feeAccounting) as StudioFeeAccounting | undefined; + const feeReport = ( + asRecord(estimate?.feeReport) ?? + asRecord(feeAccounting?.execution_fee_report) + ) as StudioExecutionFeeReport | undefined; + + return { + distribution: createFeesDistribution(distributionInput as FeesDistributionInput), + messageAllocations: rawAllocations && rawAllocations.length > 0 + ? normalizeMessageFeeAllocations(rawAllocations) + : undefined, + feeValue: bigintFromUnknown(preset.feeValue, "recommendedPreset.feeValue"), + policy, + observed: observedSimulationFeeUsage( + { + simulation: { + feeAccounting, + feeReport, + }, + }, + policy, + ), + }; +}; + +const buildEstimatedFeesOptionsFromSimulation = ( + args: SimulationFeeEstimateOptions, + policy: FeePolicyQuote, +): { + estimateOptions: FeeEstimateOptions; + observed: SimulationFeeUsage; + messageAllocations?: MessageFeeAllocationInput[]; +} => { + const { + simulation, + executionHeadroomBps, + messageHeadroomBps, + ...feeOptions + } = args; + void simulation; + void executionHeadroomBps; + void messageHeadroomBps; + + const accounting = feeAccountingFromSimulation(args.simulation); + const observed = observedSimulationFeeUsage(args, policy); + const messageAllocations = + feeOptions.messageAllocations ?? messageAllocationsFromAccounting(accounting); + + return { + estimateOptions: { + ...feeOptions, + messageAllocations, + executionBudgetPerRound: feeOptions.executionBudgetPerRound ?? ( + observed.recommendedExecutionBudgetPerRound > 0n + ? observed.recommendedExecutionBudgetPerRound + : undefined + ), + totalMessageFees: feeOptions.totalMessageFees ?? ( + messageAllocations + ? undefined + : observed.recommendedTotalMessageFees > 0n + ? observed.recommendedTotalMessageFees + : undefined + ), + }, + observed, + messageAllocations, + }; +}; + +const validatorIndex = (numOfValidators: number): number => { + const needle = BigInt(numOfValidators); + const index = VALIDATORS_PER_ROUND.findIndex((validators) => validators === needle); + if (index < 0) { + throw new Error(`InvalidNumOfValidators: ${numOfValidators}`); + } + return index; +}; + +const calculateFeeForRound = ( + numOfValidators: bigint, + rotations: bigint, + leaderTimeunitsAllocation: bigint, + validatorTimeunitsAllocation: bigint, +): bigint => rotations * ( + leaderTimeunitsAllocation + (numOfValidators * validatorTimeunitsAllocation) +); + +const calculateLocalRoundFees = ( + distribution: FeesDistribution, + numOfInitialValidators: number, + policy: FeePolicyQuote, +): bigint => { + if (distribution.appealRounds !== BigInt(distribution.rotations.length - 1)) { + throw new Error("InvalidAppealRounds"); + } + if ( + distribution.maxPriceGenPerTimeUnit > 0n && + policy.genPerTimeUnit > distribution.maxPriceGenPerTimeUnit + ) { + throw new Error("MaxPriceExceeded"); + } + if ( + distribution.storageFeeMaxGasPrice > 0n && + policy.storageUnitPrice > distribution.storageFeeMaxGasPrice + ) { + throw new Error("MaxPriceExceeded"); + } + if ( + distribution.receiptFeeMaxGasPrice > 0n && + policy.receiptGasPrice > distribution.receiptFeeMaxGasPrice + ) { + throw new Error("MaxPriceExceeded"); + } + + const startIndex = validatorIndex(numOfInitialValidators); + if (startIndex + Number(distribution.appealRounds * 2n) >= VALIDATORS_PER_ROUND.length) { + throw new Error("InvalidNumOfValidators"); + } + + let total = calculateFeeForRound( + VALIDATORS_PER_ROUND[startIndex], + distribution.rotations[0] + 1n, + distribution.leaderTimeunitsAllocation, + distribution.validatorTimeunitsAllocation, + ); + let rotationsIndex = 1; + let rotationsThisRound = 1n; + for (let offset = 1; offset <= Number(distribution.appealRounds * 2n); offset++) { + if (offset % 2 === 0 && rotationsIndex < distribution.rotations.length) { + rotationsThisRound = distribution.rotations[rotationsIndex] + 1n; + rotationsIndex += 1; + } else if (offset % 2 === 1) { + rotationsThisRound = 1n; + } + + total += calculateFeeForRound( + VALIDATORS_PER_ROUND[startIndex + offset], + rotationsThisRound, + distribution.leaderTimeunitsAllocation, + distribution.validatorTimeunitsAllocation, + ); + } + + if (policy.genPerTimeUnit > 0n) { + total *= policy.genPerTimeUnit; + } + + const leaderRounds = distribution.rotations.reduce( + (sum, rotations) => sum + rotations + 1n, + distribution.appealRounds, + ); + total += distribution.executionBudgetPerRound * leaderRounds; + return total; +}; + +const _resolveTransactionFees = async ({ + client, + publicClient, + fees, + numOfInitialValidators, +}: { + client: GenLayerClient; + publicClient: PublicClient; + fees?: TransactionFeeOptions; + numOfInitialValidators: number; +}): Promise => { + const transactionFees = normalizeTransactionFees(fees); + if (transactionFees.feeValue !== undefined || !requiresFeeDepositCalculation(transactionFees.distribution)) { + return { + ...transactionFees, + feeValue: transactionFees.feeValue ?? 0n, + }; + } + + if (!client.chain.feeManagerContract?.address) { + if (client.chain.isStudio) { + const policy = await readCurrentFeePolicy(client, publicClient); + return { + ...transactionFees, + feeValue: policy.enabled + ? calculateLocalRoundFees( + transactionFees.distribution, + numOfInitialValidators, + policy, + ) + transactionFees.distribution.totalMessageFees + : 0n, + }; + } + + throw new Error("fees.feeValue is required when the chain does not expose a feeManagerContract."); + } + + const roundFees = await publicClient.readContract({ + address: client.chain.feeManagerContract.address as `0x${string}`, + abi: FEE_MANAGER_CALCULATE_ROUND_FEES_ABI as any, + functionName: "calculateRoundFees", + args: [ + transactionFees.distribution, + BigInt(numOfInitialValidators), + 0n, + ], + }) as bigint; + + return { + ...transactionFees, + feeValue: roundFees + transactionFees.distribution.totalMessageFees, + }; }; const _encodeAddTransactionData = ({ @@ -509,58 +1604,97 @@ const _encodeAddTransactionData = ({ recipient, data, consensusMaxRotations = client.chain.defaultConsensusMaxRotations, + validUntil, + userValue = 0n, + transactionFees, }: { client: GenLayerClient; senderAccount?: Account; recipient?: `0x${string}`; data?: `0x${string}`; consensusMaxRotations?: number; -}): {primaryEncodedData: `0x${string}`; fallbackEncodedData: `0x${string}`} => { + validUntil?: BigNumberish; + userValue?: bigint; + transactionFees: NormalizedTransactionFees; +}): EncodedTransactionVariant[] => { const validatedSenderAccount = validateAccount(senderAccount); + const txCalldata = data ?? "0x"; + const txRecipient = recipient ?? zeroAddress; + const txValidUntil = toUInt(validUntil, "validUntil", getDefaultValidUntil()); + const feeValue = transactionFees.feeValue ?? 0n; const addTransactionArgs: [ Address, - `0x${string}` | undefined, + `0x${string}`, + number, number, - number | undefined, - `0x${string}` | undefined, + `0x${string}`, ] = [ validatedSenderAccount.address, - recipient, + txRecipient, client.chain.defaultNumberOfInitialValidators, consensusMaxRotations, - data, + txCalldata, ]; - const encodedDataV5 = encodeFunctionData({ - abi: ADD_TRANSACTION_ABI_V5 as any, - functionName: "addTransaction", - args: addTransactionArgs, - }); + const buildVariant = (abiVersion: AddTransactionAbiVersion): EncodedTransactionVariant => { + if (abiVersion === "fees") { + const params = { + sender: validatedSenderAccount.address, + recipient: txRecipient, + numOfInitialValidators: BigInt(client.chain.defaultNumberOfInitialValidators), + maxRotations: BigInt(consensusMaxRotations), + validUntil: txValidUntil, + saltNonce: 0n, + userValue, + feesDistribution: transactionFees.distribution, + txCalldata, + messageAllocations: transactionFees.messageAllocations, + }; - // `_validUntil = 0` is treated as "expired" by the on-chain consensus - // contract, so every submission with a v6 signature would revert. Use - // `now + 1 hour` — enough buffer for wallet confirmation + mining, short - // enough that stale signed txs don't hang around forever. - const validUntil = BigInt(Math.floor(Date.now() / 1000) + 3600); + return { + encodedData: encodeFunctionData({ + abi: ADD_TRANSACTION_ABI_WITH_FEES as any, + functionName: "addTransaction", + args: [params], + }), + value: userValue + feeValue, + }; + } - const encodedDataV6 = encodeFunctionData({ - abi: ADD_TRANSACTION_ABI_V6 as any, - functionName: "addTransaction", - args: [...addTransactionArgs, validUntil], - }); + if (abiVersion === "v6") { + return { + encodedData: encodeFunctionData({ + abi: ADD_TRANSACTION_ABI_V6 as any, + functionName: "addTransaction", + args: [...addTransactionArgs, txValidUntil], + }), + value: userValue, + }; + } - if (getAddTransactionInputCount(client.chain.consensusMainContract?.abi) >= 6) { return { - primaryEncodedData: encodedDataV6, - fallbackEncodedData: encodedDataV5, + encodedData: encodeFunctionData({ + abi: ADD_TRANSACTION_ABI_V5 as any, + functionName: "addTransaction", + args: addTransactionArgs, + }), + value: userValue, }; + }; + + if (transactionFees.requiresFeeAwareTransaction) { + return [buildVariant("fees")]; } - return { - primaryEncodedData: encodedDataV5, - fallbackEncodedData: encodedDataV6, + const detectedVersion = getAddTransactionAbiVersion(client.chain.consensusMainContract?.abi); + const orderByDetectedVersion: Record = { + fees: ["fees", "v6", "v5"], + v6: ["v6", "v5", "fees"], + v5: ["v5", "v6", "fees"], }; + + return orderByDetectedVersion[detectedVersion].map(buildVariant); }; const _encodeSubmitAppealData = ({ @@ -577,12 +1711,78 @@ const _encodeSubmitAppealData = ({ }); }; +const _resolveAppealValue = async ({ + client, + publicClient, + txId, + value, +}: { + client: GenLayerClient; + publicClient: PublicClient; + txId: `0x${string}`; + value?: bigint; +}): Promise => { + if (value !== undefined) { + return value; + } + + if (!client.chain.feeManagerContract?.address || !client.chain.roundsStorageContract?.address) { + return 0n; + } + + const roundNumber = await publicClient.readContract({ + address: client.chain.roundsStorageContract.address as `0x${string}`, + abi: client.chain.roundsStorageContract.abi as Abi, + functionName: "getRoundNumber", + args: [txId], + }) as bigint; + + const transaction = await client.getTransaction({hash: txId as TransactionHash}); + const txStatus = Number(transaction.status); + + return publicClient.readContract({ + address: client.chain.feeManagerContract.address as `0x${string}`, + abi: client.chain.feeManagerContract.abi as Abi, + functionName: "calculateMinAppealBond", + args: [txId, roundNumber, txStatus], + }) as Promise; +}; + +const _encodeTopUpFeesData = ({ + txId, + distribution, +}: { + txId: `0x${string}`; + distribution: FeesDistributionInput; +}): `0x${string}` => { + return encodeFunctionData({ + abi: CONSENSUS_FEE_MANAGEMENT_ABI, + functionName: "topUpFees", + args: [txId, createFeesDistribution(distribution)], + }); +}; + +const _encodeTopUpAndSubmitAppealData = ({ + txId, + distribution, +}: { + txId: `0x${string}`; + distribution: FeesDistributionInput; +}): `0x${string}` => { + return encodeFunctionData({ + abi: CONSENSUS_FEE_MANAGEMENT_ABI, + functionName: "topUpAndSubmitAppeal", + args: [txId, createFeesDistribution(distribution)], + }); +}; + /** * Sends a pre-encoded call to the consensus main contract, bypassing the * NewTransaction/CreatedTransaction log extraction used by _sendTransaction. * Used for consensus admin calls (appeal, finalize, etc.) that operate on * existing GenLayer transactions rather than creating new ones. - * Returns the EVM transaction hash. + * Returns the backend RPC hash: an EVM transaction hash on network backends, + * or the target GenLayer tx id on Studio/localnet fee-management calls. */ const _sendConsensusCall = async ({ client, @@ -636,6 +1836,9 @@ const _sendConsensusCall = async ({ }; const serializedTransaction = await validatedAccount.signTransaction(txRequest); const evmHash = await client.sendRawTransaction({serializedTransaction}); + if (client.chain.isStudio) { + return evmHash; + } const receipt = await publicClient.waitForTransactionReceipt({hash: evmHash}); if (receipt.status === "reverted") { throw new Error(`${operationName} reverted: EVM tx ${evmHash}`); @@ -653,6 +1856,9 @@ const _sendConsensusCall = async ({ gas: `0x${estimatedGas.toString(16)}` as `0x${string}`, }], })) as `0x${string}`; + if (client.chain.isStudio) { + return evmHash; + } const receipt = await publicClient.waitForTransactionReceipt({hash: evmHash}); if (receipt.status === "reverted") { throw new Error(`${operationName} reverted: EVM tx ${evmHash}`); @@ -734,35 +1940,73 @@ const extractTxIdFromLogs = ( const _sendTransaction = async ({ client, publicClient, - encodedData, - fallbackEncodedData, + transactionVariants, senderAccount, - value = 0n, }: { client: GenLayerClient; publicClient: PublicClient; - encodedData: `0x${string}`; - fallbackEncodedData?: `0x${string}`; + transactionVariants: EncodedTransactionVariant[]; senderAccount?: Account; - value?: bigint; }) => { if (!client.chain.consensusMainContract?.address) { throw new Error(`Consensus main contract address not found in chain config for "${client.chain.name}".`); } + if (transactionVariants.length === 0) { + throw new Error("No transaction variants available to send."); + } const validatedSenderAccount = validateAccount(senderAccount); const nonce = await client.getCurrentNonce({address: validatedSenderAccount.address}); - const sendWithEncodedData = async (encodedDataForSend: `0x${string}`) => { + const knownRevertSelectorNames: Record = { + "0x8d53e553": "InsufficientFees", + "0xb4132db3": "MaxPriceExceeded", + "0x57df8523": "ExecutionBudgetExceeded", + }; + + const stringifyRpcError = (error: unknown): string => { + const parts: string[] = []; + if (error instanceof Error) { + parts.push(error.message); + } + const record = error && typeof error === "object" ? error as Record : {}; + for (const key of ["details", "shortMessage", "data"]) { + const value = record[key]; + if (typeof value === "string" && value.trim() !== "") { + parts.push(value); + } + } + const cause = record.cause; + if (cause && typeof cause === "object") { + const causeRecord = cause as Record; + for (const key of ["message", "data"]) { + const value = causeRecord[key]; + if (typeof value === "string" && value.trim() !== "") { + parts.push(value); + } + } + } + const text = Array.from(new Set(parts)).join(" "); + const selectorName = Object.entries(knownRevertSelectorNames) + .find(([selector]) => text.includes(selector))?.[1]; + return selectorName && !text.includes(selectorName) + ? `${text} (${selectorName})` + : text; + }; + + const sendWithEncodedData = async (transactionVariant: EncodedTransactionVariant) => { let estimatedGas: bigint; + let gasEstimationError: string | undefined; try { estimatedGas = await client.estimateTransactionGas({ from: validatedSenderAccount.address, to: client.chain.consensusMainContract?.address as Address, - data: encodedDataForSend, - value: value, + data: transactionVariant.encodedData, + value: transactionVariant.value, }); + estimatedGas = withTransactionGasHeadroom(estimatedGas); } catch (err) { + gasEstimationError = stringifyRpcError(err); console.error("Gas estimation failed, using default 200_000:", err); estimatedGas = 200_000n; } @@ -781,10 +2025,10 @@ const _sendTransaction = async ({ const transactionRequest = { account: validatedSenderAccount, to: client.chain.consensusMainContract?.address as Address, - data: encodedDataForSend, + data: transactionVariant.encodedData, type: "legacy" as const, nonce: Number(nonce), - value: value, + value: transactionVariant.value, gas: estimatedGas, gasPrice: BigInt(gasPriceHex), chainId: client.chain.id, @@ -795,7 +2039,11 @@ const _sendTransaction = async ({ const receipt = await publicClient.waitForTransactionReceipt({hash: txHash}); if (receipt.status === "reverted") { - throw new Error(`Transaction reverted: EVM tx ${txHash} to consensus contract ${client.chain.consensusMainContract?.address} was reverted.`); + throw new Error( + `Transaction reverted: EVM tx ${txHash} to consensus contract ${client.chain.consensusMainContract?.address} was reverted.${ + gasEstimationError ? ` Gas estimation error: ${gasEstimationError}` : "" + }`, + ); } const txId = extractTxIdFromLogs(client, receipt.logs); @@ -833,8 +2081,8 @@ const _sendTransaction = async ({ const formattedRequest = { from: validatedSenderAccount.address, to: client.chain.consensusMainContract?.address as Address, - data: encodedDataForSend, - value: `0x${value.toString(16)}`, + data: transactionVariant.encodedData, + value: `0x${transactionVariant.value.toString(16)}`, gas: `0x${estimatedGas.toString(16)}`, nonce: `0x${nonceBigInt.toString(16)}`, type: "0x0", // legacy tx @@ -858,7 +2106,11 @@ const _sendTransaction = async ({ const externalReceipt = await publicClient.waitForTransactionReceipt({hash: evmTxHash}); if (externalReceipt.status === "reverted") { - throw new Error(`Transaction reverted: EVM tx ${evmTxHash} to consensus contract ${client.chain.consensusMainContract?.address} was reverted.`); + throw new Error( + `Transaction reverted: EVM tx ${evmTxHash} to consensus contract ${client.chain.consensusMainContract?.address} was reverted.${ + gasEstimationError ? ` Gas estimation error: ${gasEstimationError}` : "" + }`, + ); } const externalTxId = extractTxIdFromLogs(client, externalReceipt.logs); @@ -871,12 +2123,15 @@ const _sendTransaction = async ({ return externalTxId; }; - try { - return await sendWithEncodedData(encodedData); - } catch (error) { - if (!fallbackEncodedData || !isAddTransactionAbiMismatchError(error)) { - throw error; + for (let i = 0; i < transactionVariants.length; i++) { + try { + return await sendWithEncodedData(transactionVariants[i]); + } catch (error) { + if (i === transactionVariants.length - 1 || !isAddTransactionAbiMismatchError(error)) { + throw error; + } } - return await sendWithEncodedData(fallbackEncodedData); } + + throw new Error("Unable to send transaction."); }; diff --git a/src/index.ts b/src/index.ts index d39d818..507a1c7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,5 +9,6 @@ export { } from "./transactions/decoders"; export * as chains from "./chains"; export * as abi from "./abi"; +export * from "./transactions/fees"; export {parseStakingAmount, formatStakingAmount} from "./staking"; export {buildGenVmPositionalArgs} from "./contracts/schema"; diff --git a/src/transactions/fees.ts b/src/transactions/fees.ts new file mode 100644 index 0000000..a4c1cfc --- /dev/null +++ b/src/transactions/fees.ts @@ -0,0 +1,226 @@ +import {encodeAbiParameters, hexToBytes, keccak256, toHex, type Hex} from "viem"; + +import { + BigNumberish, + ExternalMessageFeeParamsInput, + FeesDistribution, + FeesDistributionInput, + InternalMessageFeeParamsInput, + MessageFeeAllocationInput, + MessageFeeAllocationNode, + MessageType, + TransactionFeeOptions, +} from "@/types"; + +export const MESSAGE_ALLOCATION_ROOT_PARENT_INDEX = (1n << 256n) - 1n; +export const CALL_KEY_WILDCARD = "0x0000000000000000000000000000000000000000000000000000000000000000" as const; +export const CALL_KEY_UNNAMED = CALL_KEY_WILDCARD; +export const CALL_KEY_DEPLOY = CALL_KEY_WILDCARD; + +const bytesToPaddedCallKey = (bytes: Uint8Array): Hex => { + if (bytes.length > 32) { + throw new Error("call key source bytes must be 32 bytes or fewer."); + } + return `0x${toHex(bytes).slice(2).padEnd(64, "0")}` as Hex; +}; + +export const deriveInternalMessageCallKey = (methodName = ""): Hex => { + const methodBytes = new TextEncoder().encode(methodName); + if (methodBytes.length < 32) { + return bytesToPaddedCallKey(methodBytes); + } + + const hashed = keccak256(methodBytes); + const lastByte = Number.parseInt(hashed.slice(-2), 16) | 1; + return `${hashed.slice(0, -2)}${lastByte.toString(16).padStart(2, "0")}` as Hex; +}; + +export const deriveExternalMessageCallKey = (selectorOrCalldata: Hex | Uint8Array = "0x"): Hex => { + const bytes = typeof selectorOrCalldata === "string" + ? hexToBytes(selectorOrCalldata) + : selectorOrCalldata; + + if (bytes.length < 4) { + return CALL_KEY_UNNAMED; + } + + return bytesToPaddedCallKey(bytes.slice(0, 4)); +}; + +export const DEFAULT_FEES_DISTRIBUTION: FeesDistribution = { + leaderTimeunitsAllocation: 0n, + validatorTimeunitsAllocation: 0n, + appealRounds: 0n, + executionBudgetPerRound: 0n, + executionConsumed: 0n, + totalMessageFees: 0n, + rotations: [0n], + maxPriceGenPerTimeUnit: 0n, + storageFeeMaxGasPrice: 0n, + receiptFeeMaxGasPrice: 0n, +}; + +export type NormalizedTransactionFees = { + distribution: FeesDistribution; + messageAllocations: MessageFeeAllocationNode[]; + feeValue?: bigint; + requiresFeeAwareTransaction: boolean; +}; + +const toUInt = (value: BigNumberish | undefined, fieldName: string, fallback = 0n): bigint => { + if (value === undefined) { + return fallback; + } + + if (typeof value === "number" && !Number.isSafeInteger(value)) { + throw new Error(`${fieldName} must be a safe integer when provided as a number.`); + } + + const normalized = BigInt(value); + if (normalized < 0n) { + throw new Error(`${fieldName} must be greater than or equal to zero.`); + } + return normalized; +}; + +const normalizeRotations = ( + rotations: BigNumberish[] | undefined, + appealRounds: bigint, + fieldName: string, +): bigint[] => { + const expectedLength = Number(appealRounds + 1n); + if (!Number.isSafeInteger(expectedLength)) { + throw new Error(`${fieldName} appealRounds is too large.`); + } + + if (!rotations) { + return Array.from({length: expectedLength}, () => 0n); + } + + const normalized = rotations.map((rotation, index) => toUInt(rotation, `${fieldName}[${index}]`)); + if (normalized.length !== expectedLength) { + throw new Error(`${fieldName} must contain appealRounds + 1 entries.`); + } + return normalized; +}; + +const hasNonDefaultFeesDistribution = (distribution: FeesDistribution): boolean => { + return ( + distribution.leaderTimeunitsAllocation !== 0n || + distribution.validatorTimeunitsAllocation !== 0n || + distribution.appealRounds !== 0n || + distribution.executionBudgetPerRound !== 0n || + distribution.executionConsumed !== 0n || + distribution.totalMessageFees !== 0n || + distribution.rotations.length !== 1 || + distribution.rotations[0] !== 0n || + distribution.maxPriceGenPerTimeUnit !== 0n || + distribution.storageFeeMaxGasPrice !== 0n || + distribution.receiptFeeMaxGasPrice !== 0n + ); +}; + +export const createFeesDistribution = (input: FeesDistributionInput = {}): FeesDistribution => { + const appealRounds = toUInt(input.appealRounds, "fees.distribution.appealRounds"); + return { + leaderTimeunitsAllocation: toUInt(input.leaderTimeunitsAllocation, "fees.distribution.leaderTimeunitsAllocation"), + validatorTimeunitsAllocation: toUInt(input.validatorTimeunitsAllocation, "fees.distribution.validatorTimeunitsAllocation"), + appealRounds, + executionBudgetPerRound: toUInt(input.executionBudgetPerRound, "fees.distribution.executionBudgetPerRound"), + executionConsumed: toUInt(input.executionConsumed, "fees.distribution.executionConsumed"), + totalMessageFees: toUInt(input.totalMessageFees, "fees.distribution.totalMessageFees"), + rotations: normalizeRotations(input.rotations, appealRounds, "fees.distribution.rotations"), + maxPriceGenPerTimeUnit: toUInt(input.maxPriceGenPerTimeUnit, "fees.distribution.maxPriceGenPerTimeUnit"), + storageFeeMaxGasPrice: toUInt(input.storageFeeMaxGasPrice, "fees.distribution.storageFeeMaxGasPrice"), + receiptFeeMaxGasPrice: toUInt(input.receiptFeeMaxGasPrice, "fees.distribution.receiptFeeMaxGasPrice"), + }; +}; + +export const encodeInternalMessageFeeParams = (input: InternalMessageFeeParamsInput = {}) => { + const appealRounds = toUInt(input.appealRounds, "internalMessageFeeParams.appealRounds"); + return encodeAbiParameters( + [ + { + name: "params", + type: "tuple", + components: [ + {name: "leaderTimeunitsAllocation", type: "uint256"}, + {name: "validatorTimeunitsAllocation", type: "uint256"}, + {name: "appealRounds", type: "uint256"}, + {name: "executionBudgetPerRound", type: "uint256"}, + {name: "rotations", type: "uint256[]"}, + ], + }, + ], + [ + { + leaderTimeunitsAllocation: toUInt(input.leaderTimeunitsAllocation, "internalMessageFeeParams.leaderTimeunitsAllocation"), + validatorTimeunitsAllocation: toUInt(input.validatorTimeunitsAllocation, "internalMessageFeeParams.validatorTimeunitsAllocation"), + appealRounds, + executionBudgetPerRound: toUInt(input.executionBudgetPerRound, "internalMessageFeeParams.executionBudgetPerRound"), + rotations: normalizeRotations(input.rotations, appealRounds, "internalMessageFeeParams.rotations"), + }, + ], + ); +}; + +export const encodeExternalMessageFeeParams = (input: ExternalMessageFeeParamsInput = {}) => { + return encodeAbiParameters( + [ + { + name: "params", + type: "tuple", + components: [ + {name: "gasLimit", type: "uint256"}, + {name: "maxGasPrice", type: "uint256"}, + ], + }, + ], + [ + { + gasLimit: toUInt(input.gasLimit, "externalMessageFeeParams.gasLimit"), + maxGasPrice: toUInt(input.maxGasPrice, "externalMessageFeeParams.maxGasPrice"), + }, + ], + ); +}; + +export const normalizeMessageFeeAllocations = ( + allocations: MessageFeeAllocationInput[] = [], +): MessageFeeAllocationNode[] => { + return allocations.map((allocation, index) => ({ + messageType: allocation.messageType, + onAcceptance: allocation.onAcceptance ?? allocation.messageType !== MessageType.External, + parentIndex: toUInt( + allocation.parentIndex, + `fees.messageAllocations[${index}].parentIndex`, + MESSAGE_ALLOCATION_ROOT_PARENT_INDEX, + ), + recipient: allocation.recipient, + callKey: allocation.callKey ?? CALL_KEY_WILDCARD, + budget: toUInt(allocation.budget, `fees.messageAllocations[${index}].budget`), + feeParams: allocation.feeParams ?? "0x", + })); +}; + +export const normalizeTransactionFees = (fees?: TransactionFeeOptions): NormalizedTransactionFees => { + const distribution = createFeesDistribution(fees?.distribution); + const messageAllocations = normalizeMessageFeeAllocations(fees?.messageAllocations); + const feeValue = fees?.feeValue === undefined + ? undefined + : toUInt(fees.feeValue, "fees.feeValue"); + + return { + distribution, + messageAllocations, + feeValue, + requiresFeeAwareTransaction: + hasNonDefaultFeesDistribution(distribution) || + messageAllocations.length > 0 || + (feeValue ?? 0n) !== 0n, + }; +}; + +export { + MessageType, +}; diff --git a/src/types/clients.ts b/src/types/clients.ts index fc06534..e50433d 100644 --- a/src/types/clients.ts +++ b/src/types/clients.ts @@ -1,5 +1,20 @@ import {Transport, Client, PublicActions, WalletActions} from "viem"; -import {GenLayerTransaction, TransactionHash, TransactionStatus, TransactionHashVariant, DebugTraceResult} from "./transactions"; +import { + GenLayerTransaction, + TransactionHash, + TransactionStatus, + TransactionHashVariant, + DebugTraceResult, + TransactionFeeOptions, + TransactionFeeEstimate, + FeeEstimateOptions, + SimulationFeeEstimateOptions, + WriteFeeEstimateOptions, + FeePolicyQuote, + BigNumberish, + FeesDistributionInput, + SimulateWriteContractResult, +} from "./transactions"; import {GenLayerChain} from "./chains"; import {Address, Account} from "./accounts"; import {CalldataEncodable} from "./calldata"; @@ -21,7 +36,10 @@ export type GenLayerMethod = | {method: "eth_getTransactionCount"; params: [address: Address, block: string]} | {method: "eth_estimateGas"; params: [transactionParams: any]} | {method: "gen_call"; params: [requestParams: any]} - | {method: "sim_cancelTransaction"; params: [hash: TransactionHash, signature?: string, adminKey?: string]}; + | {method: "sim_call"; params: [requestParams: any]} + | {method: "sim_estimateTransactionFees"; params: [requestParams: any]} + | {method: "sim_cancelTransaction"; params: [hash: TransactionHash, signature?: string, adminKey?: string]} + | {method: "sim_getFeeConfig"; params: []}; /* Take all the properties from Client @@ -58,20 +76,30 @@ export type GenLayerClient = Omit< functionName: string; args?: CalldataEncodable[]; kwargs?: Map | {[key: string]: CalldataEncodable}; - value: bigint; + value?: bigint; leaderOnly?: boolean; consensusMaxRotations?: number; + validUntil?: BigNumberish; + fees?: TransactionFeeOptions; }) => Promise; - simulateWriteContract: (args: { + simulateWriteContract: < + RawReturn extends boolean | undefined = undefined, + IncludeReceipt extends boolean | undefined = undefined, + >(args: { account?: Account; address: Address; functionName: string; args?: CalldataEncodable[]; kwargs?: Map | { [key: string]: CalldataEncodable }; rawReturn?: RawReturn; + includeReceipt?: IncludeReceipt; + value?: BigNumberish; leaderOnly?: boolean; + fees?: TransactionFeeOptions; transactionHashVariant?: TransactionHashVariant; - }) => Promise; + }) => Promise + : RawReturn extends true ? `0x${string}` : CalldataEncodable>; deployContract: (args: { account?: Account; code: string | Uint8Array; @@ -79,6 +107,8 @@ export type GenLayerClient = Omit< kwargs?: Map | {[key: string]: CalldataEncodable}; leaderOnly?: boolean; consensusMaxRotations?: number; + validUntil?: BigNumberish; + fees?: TransactionFeeOptions; }) => Promise<`0x${string}`>; getTransaction: (args: {hash: TransactionHash}) => Promise; getCurrentNonce: (args: {address: Address}) => Promise; @@ -114,6 +144,18 @@ export type GenLayerClient = Omit< txId: `0x${string}`; value?: bigint; }) => Promise; + topUpFees: (args: { + account?: Account; + txId: `0x${string}`; + distribution: FeesDistributionInput; + value: bigint; + }) => Promise<`0x${string}`>; + topUpAndSubmitAppeal: (args: { + account?: Account; + txId: `0x${string}`; + distribution: FeesDistributionInput; + value?: bigint; + }) => Promise<`0x${string}`>; finalizeTransaction: (args: { account?: Account; txId: `0x${string}`; @@ -123,4 +165,9 @@ export type GenLayerClient = Omit< txIds: readonly `0x${string}`[]; }) => Promise<`0x${string}`>; getMinAppealBond: (args: {txId: `0x${string}`}) => Promise; + getCurrentFeePolicy: () => Promise; + estimateFeesDistribution: (args?: FeeEstimateOptions) => Promise; + estimateTransactionFees: (args?: FeeEstimateOptions) => Promise; + estimateTransactionFeesFromSimulation: (args: SimulationFeeEstimateOptions) => Promise; + estimateTransactionFeesForWrite: (args: WriteFeeEstimateOptions) => Promise; } & StakingActions; diff --git a/src/types/transactions.ts b/src/types/transactions.ts index db3cb4a..9e24526 100644 --- a/src/types/transactions.ts +++ b/src/types/transactions.ts @@ -1,8 +1,10 @@ import {Hex} from "viem"; -import {Address} from "./accounts"; +import {Account, Address} from "./accounts"; +import type {CalldataEncodable} from "./calldata"; export type Hash = `0x${string}` & {length: 66}; export type TransactionHash = Hash; +export type BigNumberish = bigint | number | string; export enum TransactionStatus { UNINITIALIZED = "UNINITIALIZED", @@ -151,6 +153,271 @@ export enum TransactionHashVariant { LATEST_NONFINAL = "latest-nonfinal", } +export enum MessageType { + External = 0, + Internal = 1, +} + +export type FeesDistribution = { + leaderTimeunitsAllocation: bigint; + validatorTimeunitsAllocation: bigint; + appealRounds: bigint; + executionBudgetPerRound: bigint; + executionConsumed: bigint; + totalMessageFees: bigint; + rotations: bigint[]; + maxPriceGenPerTimeUnit: bigint; + storageFeeMaxGasPrice: bigint; + receiptFeeMaxGasPrice: bigint; +}; + +export type FeesDistributionInput = { + leaderTimeunitsAllocation?: BigNumberish; + validatorTimeunitsAllocation?: BigNumberish; + appealRounds?: BigNumberish; + executionBudgetPerRound?: BigNumberish; + executionConsumed?: BigNumberish; + totalMessageFees?: BigNumberish; + rotations?: BigNumberish[]; + maxPriceGenPerTimeUnit?: BigNumberish; + storageFeeMaxGasPrice?: BigNumberish; + receiptFeeMaxGasPrice?: BigNumberish; +}; + +export type InternalMessageFeeParamsInput = { + leaderTimeunitsAllocation?: BigNumberish; + validatorTimeunitsAllocation?: BigNumberish; + appealRounds?: BigNumberish; + executionBudgetPerRound?: BigNumberish; + rotations?: BigNumberish[]; +}; + +export type ExternalMessageFeeParamsInput = { + gasLimit?: BigNumberish; + maxGasPrice?: BigNumberish; +}; + +export type MessageFeeAllocationNode = { + messageType: MessageType; + onAcceptance: boolean; + parentIndex: bigint; + recipient: Address; + callKey: Hex; + budget: bigint; + feeParams: Hex; +}; + +export type MessageFeeAllocationInput = { + messageType: MessageType; + onAcceptance?: boolean; + parentIndex?: BigNumberish; + recipient: Address; + callKey?: Hex; + budget?: BigNumberish; + feeParams?: Hex; +}; + +export type TransactionFeeOptions = { + distribution?: FeesDistributionInput; + messageAllocations?: MessageFeeAllocationInput[]; + feeValue?: BigNumberish; +}; + +export type FeePolicyQuote = { + enabled: boolean; + genPerTimeUnit: bigint; + storageUnitPrice: bigint; + receiptGasPrice: bigint; + executionBudgetFloor: bigint; +}; + +export type FeeEstimateOptions = FeesDistributionInput & { + /** + * Basis-points multiplier applied to current network prices when filling + * unset cap fields. Defaults to 12000 (20% headroom). + */ + priceCapHeadroomBps?: BigNumberish; + messageAllocations?: MessageFeeAllocationInput[]; +}; + +export type TransactionFeeEstimate = { + distribution: FeesDistribution; + messageAllocations?: MessageFeeAllocationInput[]; + feeValue: bigint; + policy: FeePolicyQuote; + observed?: SimulationFeeUsage; +}; + +export type SimulateWriteContractReceipt = Record; + +export type StudioExecutionFeeReportMessage = { + messageFeeMode?: "mode1" | "mode2" | "external"; + messageType: "External" | "Internal"; + recipient: Address; + value: BigNumberish; + dataBytes: BigNumberish; + onAcceptance: boolean; + saltNonce: BigNumberish; + feeParams?: Hex; + feeParamsDecoded?: InternalMessageFeeParamsInput | ExternalMessageFeeParamsInput | null; + feeParamsBytes: BigNumberish; + declaredBudget: BigNumberish; + allocationSubtree?: Hex; + allocationSubtreeBytes: BigNumberish; + callKey: Hex; +}; + +export type StudioGenvmFeeBucket = { + index?: BigNumberish; + name?: string; + consumed?: BigNumberish; +}; + +export type StudioGenvmFeeBucketReport = { + receiptAndNondetOutput?: BigNumberish; + storage?: BigNumberish; + message?: BigNumberish; + totalExecution?: BigNumberish; + totalWithMessage?: BigNumberish; + executionBudgetPerRound?: BigNumberish; + executionBudgetRemaining?: BigNumberish; + executionBudgetOverrun?: BigNumberish; + executionBudgetExceeded?: boolean; + buckets?: StudioGenvmFeeBucket[]; +}; + +export type StudioExecutionFeeReport = { + receiptGasPrice?: BigNumberish; + budgetExhaustionReason?: string | null; + proposalReceipt?: { + eqBlocksOutputsLength: BigNumberish; + receiptBytes: BigNumberish; + estimatedGas: BigNumberish; + fee: BigNumberish; + }; + messageReveal?: { + messageBytes: BigNumberish; + messageCount: BigNumberish; + estimatedGas: BigNumberish; + fee: BigNumberish; + consensusAdditionalGas?: BigNumberish; + consensusAdditionalFee?: BigNumberish; + studioFixedOverheadGas?: BigNumberish; + studioFixedOverheadFee?: BigNumberish; + messages?: StudioExecutionFeeReportMessage[]; + }; + genvmBuckets?: StudioGenvmFeeBucketReport; + chargeableExecution?: StudioGenvmFeeBucketReport; + executionMetering?: { + chargeableExecutionFee?: BigNumberish; + genvmReportedExecution?: BigNumberish; + genvmDeltaFromChargeable?: BigNumberish; + }; + messageFees?: { + budget?: BigNumberish; + declaredConsumed?: BigNumberish; + genvmMeteredConsumed?: BigNumberish; + externalReserved?: BigNumberish; + externalReimbursed?: BigNumberish; + externalRemainder?: BigNumberish; + totalConsumed?: BigNumberish; + declaredRefunded?: BigNumberish; + remaining?: BigNumberish; + meteringDelta?: BigNumberish; + reportedTotal?: BigNumberish; + }; + totalEstimatedFee?: BigNumberish; + totalStudioMeteredFee?: BigNumberish; +}; + +export type StudioFeeAccounting = Record & { + paid_fee_value?: BigNumberish; + required_fee_value?: BigNumberish; + primary_fee_required?: BigNumberish; + primary_fee_budget?: BigNumberish; + primary_fee_spent?: BigNumberish; + primary_fee_refunded?: BigNumberish; + execution_budget_total?: BigNumberish; + execution_fee_consumed?: BigNumberish; + execution_fee_consumed_buckets?: BigNumberish[]; + genvm_fee_consumed_buckets?: BigNumberish[]; + genvm_fee_bucket_report?: StudioGenvmFeeBucketReport; + genvm_message_fee_consumed?: BigNumberish; + message_fee_budget?: BigNumberish; + message_fee_consumed?: BigNumberish; + message_fee_refunded?: BigNumberish; + external_message_fee_reserved?: BigNumberish; + external_message_fee_reimbursed?: BigNumberish; + external_message_fee_remainder?: BigNumberish; + appeal_bonds_total?: BigNumberish; + total_refunded?: BigNumberish; + fees_distribution?: FeesDistributionInput; + message_allocations?: MessageFeeAllocationInput[]; + execution_fee_report?: StudioExecutionFeeReport; +}; + +export type SimulateWriteContractResult< + RawReturn extends boolean | undefined = undefined, +> = { + result: RawReturn extends true ? Hex : CalldataEncodable; + receipt: SimulateWriteContractReceipt; + feeAccounting?: StudioFeeAccounting; + feeReport?: StudioExecutionFeeReport; +}; + +export type SimulationFeeUsage = { + executionFeeConsumed: bigint; + executionFeeReportTotal: bigint; + recommendedExecutionBudgetPerRound: bigint; + genvmMessageFeeConsumed: bigint; + messageFeeBudget: bigint; + messageFeeConsumed: bigint; + messageFeeRefunded: bigint; + internalDeclaredBudget: bigint; + externalMessageReserved: bigint; + externalMessageReimbursed: bigint; + externalMessageRemainder: bigint; + recommendedTotalMessageFees: bigint; +}; + +export type SimulationFeeEstimateOptions = FeeEstimateOptions & { + simulation: Pick< + SimulateWriteContractResult, + "feeAccounting" | "feeReport" + >; + /** + * Basis-points multiplier applied to observed execution fee usage. + * Defaults to 12000 (20% headroom). + */ + executionHeadroomBps?: BigNumberish; + /** + * Basis-points multiplier applied to observed mode-1 message fee usage. + * Defaults to 12000 (20% headroom). + */ + messageHeadroomBps?: BigNumberish; +}; + +export type WriteFeeEstimateOptions = FeeEstimateOptions & { + account?: Account; + address: Address; + functionName: string; + args?: CalldataEncodable[]; + kwargs?: Map | {[key: string]: CalldataEncodable}; + value?: BigNumberish; + leaderOnly?: boolean; + transactionHashVariant?: TransactionHashVariant; + /** + * Basis-points multiplier applied to observed execution fee usage. + * Defaults to 12000 (20% headroom). + */ + executionHeadroomBps?: BigNumberish; + /** + * Basis-points multiplier applied to observed mode-1 message fee usage. + * Defaults to 12000 (20% headroom). + */ + messageHeadroomBps?: BigNumberish; +}; + export type DecodedDeployData = { code?: Hex; constructorArgs?: any; // Type this more strictly if possible diff --git a/tests/contracts-actions.test.ts b/tests/contracts-actions.test.ts index 876a20a..572b1fe 100644 --- a/tests/contracts-actions.test.ts +++ b/tests/contracts-actions.test.ts @@ -1,6 +1,15 @@ import {describe, it, expect, vi} from "vitest"; -import {encodeFunctionData, keccak256, toHex} from "viem"; +import {decodeAbiParameters, decodeFunctionData, encodeFunctionData, keccak256, toHex} from "viem"; import {contractActions} from "../src/contracts/actions"; +import { + CALL_KEY_DEPLOY, + CALL_KEY_WILDCARD, + deriveExternalMessageCallKey, + deriveInternalMessageCallKey, + encodeExternalMessageFeeParams, + encodeInternalMessageFeeParams, + MessageType, +} from "../src/transactions/fees"; const MAIN_CONTRACT_ADDRESS = "0x0000000000000000000000000000000000000001"; const SENDER_ADDRESS = "0x0000000000000000000000000000000000000002"; @@ -81,6 +90,81 @@ const ADD_TRANSACTION_ABI_V6 = [ }, ] as const; +const FEES_DISTRIBUTION_COMPONENTS = [ + {name: "leaderTimeunitsAllocation", type: "uint256"}, + {name: "validatorTimeunitsAllocation", type: "uint256"}, + {name: "appealRounds", type: "uint256"}, + {name: "executionBudgetPerRound", type: "uint256"}, + {name: "executionConsumed", type: "uint256"}, + {name: "totalMessageFees", type: "uint256"}, + {name: "rotations", type: "uint256[]"}, + {name: "maxPriceGenPerTimeUnit", type: "uint256"}, + {name: "storageFeeMaxGasPrice", type: "uint256"}, + {name: "receiptFeeMaxGasPrice", type: "uint256"}, +] as const; + +const MESSAGE_FEE_ALLOCATION_COMPONENTS = [ + {name: "messageType", type: "uint8"}, + {name: "onAcceptance", type: "bool"}, + {name: "parentIndex", type: "uint256"}, + {name: "recipient", type: "address"}, + {name: "callKey", type: "bytes32"}, + {name: "budget", type: "uint256"}, + {name: "feeParams", type: "bytes"}, +] as const; + +const INTERNAL_MESSAGE_FEE_PARAMS_ABI = [ + { + name: "params", + type: "tuple", + components: [ + {name: "leaderTimeunitsAllocation", type: "uint256"}, + {name: "validatorTimeunitsAllocation", type: "uint256"}, + {name: "appealRounds", type: "uint256"}, + {name: "executionBudgetPerRound", type: "uint256"}, + {name: "rotations", type: "uint256[]"}, + ], + }, +] as const; + +const EXTERNAL_MESSAGE_FEE_PARAMS_ABI = [ + { + name: "params", + type: "tuple", + components: [ + {name: "gasLimit", type: "uint256"}, + {name: "maxGasPrice", type: "uint256"}, + ], + }, +] as const; + +const ADD_TRANSACTION_ABI_WITH_FEES = [ + { + type: "function", + name: "addTransaction", + stateMutability: "payable", + inputs: [ + { + name: "_params", + type: "tuple", + components: [ + {name: "sender", type: "address"}, + {name: "recipient", type: "address"}, + {name: "numOfInitialValidators", type: "uint256"}, + {name: "maxRotations", type: "uint256"}, + {name: "validUntil", type: "uint256"}, + {name: "saltNonce", type: "uint256"}, + {name: "userValue", type: "uint256"}, + {name: "feesDistribution", type: "tuple", components: FEES_DISTRIBUTION_COMPONENTS}, + {name: "txCalldata", type: "bytes"}, + {name: "messageAllocations", type: "tuple[]", components: MESSAGE_FEE_ALLOCATION_COMPONENTS}, + ], + }, + ], + outputs: [], + }, +] as const; + const selectorForV5 = encodeFunctionData({ abi: ADD_TRANSACTION_ABI_V5 as any, functionName: "addTransaction", @@ -93,12 +177,48 @@ const selectorForV6 = encodeFunctionData({ args: [SENDER_ADDRESS, RECIPIENT_ADDRESS, 5, 3, "0x", 0n], }).slice(0, 10); +const selectorForFees = encodeFunctionData({ + abi: ADD_TRANSACTION_ABI_WITH_FEES as any, + functionName: "addTransaction", + args: [{ + sender: SENDER_ADDRESS, + recipient: RECIPIENT_ADDRESS, + numOfInitialValidators: 5n, + maxRotations: 3n, + validUntil: 1n, + saltNonce: 0n, + userValue: 0n, + feesDistribution: { + leaderTimeunitsAllocation: 0n, + validatorTimeunitsAllocation: 0n, + appealRounds: 0n, + executionBudgetPerRound: 0n, + executionConsumed: 0n, + totalMessageFees: 0n, + rotations: [0n], + maxPriceGenPerTimeUnit: 0n, + storageFeeMaxGasPrice: 0n, + receiptFeeMaxGasPrice: 0n, + }, + txCalldata: "0x", + messageAllocations: [], + }], +}).slice(0, 10); + const setupWriteContractHarness = ({ initialAbi, signTransactionMock, + publicClient = {}, + feeManagerAddress, + isStudio = false, + requestMock, }: { initialAbi: readonly unknown[]; signTransactionMock?: ReturnType; + publicClient?: Record; + feeManagerAddress?: string; + isStudio?: boolean; + requestMock?: ReturnType; }) => { const estimateTransactionGas = vi.fn().mockResolvedValue(21_000n); const signTransaction = signTransactionMock ?? vi.fn().mockRejectedValue(new Error("stop_after_encoding")); @@ -106,6 +226,7 @@ const setupWriteContractHarness = ({ const client = { chain: { id: 61_127, + isStudio, defaultNumberOfInitialValidators: 5, defaultConsensusMaxRotations: 3, consensusMainContract: { @@ -113,6 +234,12 @@ const setupWriteContractHarness = ({ abi: [...initialAbi], bytecode: "0x", }, + feeManagerContract: feeManagerAddress + ? { + address: feeManagerAddress, + abi: [], + } + : null, }, account: { address: SENDER_ADDRESS, @@ -122,7 +249,7 @@ const setupWriteContractHarness = ({ initializeConsensusSmartContract: vi.fn().mockResolvedValue(undefined), getCurrentNonce: vi.fn().mockResolvedValue(0n), estimateTransactionGas, - request: vi.fn().mockImplementation(async ({method}: {method: string}) => { + request: requestMock ?? vi.fn().mockImplementation(async ({method}: {method: string}) => { if (method === "eth_gasPrice") { return "0x1"; } @@ -130,12 +257,189 @@ const setupWriteContractHarness = ({ }), }; - const actions = contractActions(client as any, {} as any); + const actions = contractActions(client as any, publicClient as any); - return {actions, estimateTransactionGas, client, signTransaction}; + return {actions, estimateTransactionGas, client, signTransaction, publicClient}; }; describe("contractActions addTransaction ABI compatibility", () => { + it("passes trusted fees and user value through Studio simulateWriteContract sim_call", async () => { + const request = vi.fn().mockResolvedValue({ + result: Buffer.from([0, 0xab, 0xcd]).toString("base64"), + execution_result: "SUCCESS", + genvm_result: { + fee_accounting: { + status: "active", + primary_fee_budget: "123", + execution_fee_report: { + receiptGasPrice: "1", + proposalReceipt: { + eqBlocksOutputsLength: "10", + receiptBytes: "1034", + estimatedGas: "314544", + fee: "314544", + }, + messageReveal: { + messageBytes: "320", + messageCount: "1", + estimatedGas: "187120", + fee: "187120", + messages: [ + { + messageType: "Internal", + recipient: RECIPIENT_ADDRESS, + value: "0", + dataBytes: "2", + onAcceptance: true, + saltNonce: "0", + feeParamsBytes: "2", + declaredBudget: "5", + allocationSubtreeBytes: "0", + callKey: `0x${"12".repeat(32)}`, + }, + ], + }, + totalEstimatedFee: "501664", + }, + }, + }, + }); + const actions = contractActions({ + chain: { + id: 61_127, + defaultNumberOfInitialValidators: 5, + defaultConsensusMaxRotations: 3, + isStudio: true, + }, + account: { + address: SENDER_ADDRESS, + }, + request, + } as any, {} as any); + + const result = await actions.simulateWriteContract({ + address: RECIPIENT_ADDRESS, + functionName: "update_storage", + args: ["simulated"], + rawReturn: true, + includeReceipt: true, + value: 12n, + fees: { + feeValue: 123n, + distribution: { + leaderTimeunitsAllocation: 100n, + validatorTimeunitsAllocation: 200n, + totalMessageFees: 5n, + rotations: [0n], + }, + messageAllocations: [ + { + messageType: MessageType.Internal, + recipient: RECIPIENT_ADDRESS, + budget: 5n, + feeParams: "0x1234", + }, + ], + }, + }); + + expect(request.mock.calls[0][0].method).toBe("sim_call"); + const params = request.mock.calls[0][0].params[0]; + expect(result.result).toBe("0xabcd"); + expect(result.feeAccounting).toEqual({ + status: "active", + primary_fee_budget: "123", + execution_fee_report: { + receiptGasPrice: "1", + proposalReceipt: { + eqBlocksOutputsLength: "10", + receiptBytes: "1034", + estimatedGas: "314544", + fee: "314544", + }, + messageReveal: { + messageBytes: "320", + messageCount: "1", + estimatedGas: "187120", + fee: "187120", + messages: [ + { + messageType: "Internal", + recipient: RECIPIENT_ADDRESS, + value: "0", + dataBytes: "2", + onAcceptance: true, + saltNonce: "0", + feeParamsBytes: "2", + declaredBudget: "5", + allocationSubtreeBytes: "0", + callKey: `0x${"12".repeat(32)}`, + }, + ], + }, + totalEstimatedFee: "501664", + }, + }); + expect(result.feeReport?.messageReveal?.messages?.[0].declaredBudget).toBe("5"); + expect(params.value).toBe("0xc"); + expect(params.fees.feeValue).toBe("123"); + expect(params.fees.distribution.leaderTimeunitsAllocation).toBe("100"); + expect(params.fees.distribution.validatorTimeunitsAllocation).toBe("200"); + expect(params.fees.distribution.totalMessageFees).toBe("5"); + expect(params.fees.distribution.rotations).toEqual(["0"]); + expect(params.fees.messageAllocations[0].messageType).toBe(MessageType.Internal); + expect(params.fees.messageAllocations[0].budget).toBe("5"); + }); + + it("encodes internal message fee params as the consensus tuple", () => { + const encoded = encodeInternalMessageFeeParams({ + leaderTimeunitsAllocation: 5n, + validatorTimeunitsAllocation: 10n, + appealRounds: 1n, + executionBudgetPerRound: 20n, + rotations: [2n, 3n], + }); + + const [decoded] = decodeAbiParameters(INTERNAL_MESSAGE_FEE_PARAMS_ABI, encoded) as any; + expect(decoded.leaderTimeunitsAllocation).toBe(5n); + expect(decoded.validatorTimeunitsAllocation).toBe(10n); + expect(decoded.appealRounds).toBe(1n); + expect(decoded.executionBudgetPerRound).toBe(20n); + expect(decoded.rotations).toEqual([2n, 3n]); + }); + + it("encodes external message fee params as the consensus tuple", () => { + const encoded = encodeExternalMessageFeeParams({ + gasLimit: 21_000n, + maxGasPrice: 10n, + }); + + const [decoded] = decodeAbiParameters(EXTERNAL_MESSAGE_FEE_PARAMS_ABI, encoded) as any; + expect(decoded.gasLimit).toBe(21_000n); + expect(decoded.maxGasPrice).toBe(10n); + }); + + it("derives GenVM-compatible message call keys", () => { + const shortInternal = deriveInternalMessageCallKey("update_storage"); + expect(shortInternal).toBe( + `0x${Buffer.from("update_storage", "utf8").toString("hex").padEnd(64, "0")}`, + ); + + const exactLengthMethod = "a".repeat(32); + const hashed = keccak256(toHex(new TextEncoder().encode(exactLengthMethod))); + const lastByte = Number.parseInt(hashed.slice(-2), 16) | 1; + expect(deriveInternalMessageCallKey(exactLengthMethod)).toBe( + `${hashed.slice(0, -2)}${lastByte.toString(16).padStart(2, "0")}`, + ); + + expect(deriveInternalMessageCallKey()).toBe(CALL_KEY_WILDCARD); + expect(CALL_KEY_DEPLOY).toBe(CALL_KEY_WILDCARD); + expect(deriveExternalMessageCallKey("0xaabbccdd11223344")).toBe( + `0xaabbccdd${"0".repeat(56)}`, + ); + expect(deriveExternalMessageCallKey("0x123456")).toBe(CALL_KEY_WILDCARD); + }); + it("encodes addTransaction with 5 args when ABI has 5 inputs", async () => { const {actions, estimateTransactionGas} = setupWriteContractHarness({ initialAbi: ADD_TRANSACTION_ABI_V5, @@ -170,6 +474,691 @@ describe("contractActions addTransaction ABI compatibility", () => { expect(encodedData.slice(0, 10)).toBe(selectorForV6); }); + it("encodes addTransaction with v0.6 fee params when ABI has tuple input", async () => { + const {actions, estimateTransactionGas} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + }); + + await expect( + actions.writeContract({ + address: RECIPIENT_ADDRESS, + functionName: "ping", + value: 7n, + validUntil: 123n, + }), + ).rejects.toThrow("stop_after_encoding"); + + const estimateParams = estimateTransactionGas.mock.calls[0][0]; + const encodedData = estimateParams.data as `0x${string}`; + expect(encodedData.slice(0, 10)).toBe(selectorForFees); + expect(estimateParams.value).toBe(7n); + + const decoded = decodeFunctionData({ + abi: ADD_TRANSACTION_ABI_WITH_FEES as any, + data: encodedData, + }); + const params = decoded.args[0] as any; + expect(params.sender).toBe(SENDER_ADDRESS); + expect(params.recipient).toBe(RECIPIENT_ADDRESS); + expect(params.numOfInitialValidators).toBe(5n); + expect(params.maxRotations).toBe(3n); + expect(params.validUntil).toBe(123n); + expect(params.userValue).toBe(7n); + expect(params.feesDistribution.rotations).toEqual([0n]); + expect(params.messageAllocations).toEqual([]); + }); + + it("separates user value from v0.6 fee deposit value", async () => { + const {actions, estimateTransactionGas} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + }); + + await expect( + actions.writeContract({ + address: RECIPIENT_ADDRESS, + functionName: "ping", + value: 5n, + validUntil: 123n, + fees: { + feeValue: 123n, + distribution: { + totalMessageFees: 123n, + }, + messageAllocations: [{ + messageType: MessageType.Internal, + onAcceptance: false, + recipient: RECIPIENT_ADDRESS, + budget: 123n, + feeParams: "0x1234", + }], + }, + }), + ).rejects.toThrow("stop_after_encoding"); + + const estimateParams = estimateTransactionGas.mock.calls[0][0]; + expect(estimateParams.value).toBe(128n); + + const decoded = decodeFunctionData({ + abi: ADD_TRANSACTION_ABI_WITH_FEES as any, + data: estimateParams.data as `0x${string}`, + }); + const params = decoded.args[0] as any; + expect(params.userValue).toBe(5n); + expect(params.feesDistribution.totalMessageFees).toBe(123n); + expect(params.messageAllocations).toHaveLength(1); + expect(params.messageAllocations[0].messageType).toBe(MessageType.Internal); + expect(params.messageAllocations[0].onAcceptance).toBe(false); + expect(params.messageAllocations[0].budget).toBe(123n); + expect(params.messageAllocations[0].feeParams).toBe("0x1234"); + }); + + it("defaults external message allocations to on-finalization", async () => { + const {actions, estimateTransactionGas} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + }); + + await expect( + actions.writeContract({ + address: RECIPIENT_ADDRESS, + functionName: "ping", + validUntil: 123n, + fees: { + feeValue: 210_000n, + distribution: { + totalMessageFees: 210_000n, + }, + messageAllocations: [{ + messageType: MessageType.External, + recipient: RECIPIENT_ADDRESS, + budget: 210_000n, + feeParams: encodeExternalMessageFeeParams({ + gasLimit: 21_000n, + maxGasPrice: 10n, + }), + }], + }, + }), + ).rejects.toThrow("stop_after_encoding"); + + const decoded = decodeFunctionData({ + abi: ADD_TRANSACTION_ABI_WITH_FEES as any, + data: estimateTransactionGas.mock.calls[0][0].data as `0x${string}`, + }); + const params = decoded.args[0] as any; + expect(params.messageAllocations[0].messageType).toBe(MessageType.External); + expect(params.messageAllocations[0].onAcceptance).toBe(false); + }); + + it("calculates v0.6 fee deposit from FeeManager when feeValue is omitted", async () => { + const publicClient = { + readContract: vi.fn().mockResolvedValue(77n), + }; + const {actions, estimateTransactionGas} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + publicClient, + feeManagerAddress: "0x00000000000000000000000000000000000000fe", + }); + + await expect( + actions.writeContract({ + address: RECIPIENT_ADDRESS, + functionName: "ping", + value: 2n, + validUntil: 123n, + fees: { + distribution: { + leaderTimeunitsAllocation: 10n, + totalMessageFees: 3n, + }, + }, + }), + ).rejects.toThrow("stop_after_encoding"); + + expect(publicClient.readContract).toHaveBeenCalledWith(expect.objectContaining({ + functionName: "calculateRoundFees", + args: [expect.any(Object), 5n, 0n], + })); + expect(estimateTransactionGas.mock.calls[0][0].value).toBe(82n); + }); + + it("calculates v0.6 fee deposit from FeeManager when only execution budget is provided", async () => { + const publicClient = { + readContract: vi.fn().mockResolvedValue(500_000n), + }; + const {actions, estimateTransactionGas} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + publicClient, + feeManagerAddress: "0x00000000000000000000000000000000000000fe", + }); + + await expect( + actions.writeContract({ + address: RECIPIENT_ADDRESS, + functionName: "ping", + validUntil: 123n, + fees: { + distribution: { + executionBudgetPerRound: 500_000n, + }, + }, + }), + ).rejects.toThrow("stop_after_encoding"); + + expect(publicClient.readContract).toHaveBeenCalledWith(expect.objectContaining({ + functionName: "calculateRoundFees", + args: [expect.any(Object), 5n, 0n], + })); + expect(estimateTransactionGas.mock.calls[0][0].value).toBe(500_000n); + }); + + it("calculates v0.6 fee deposit locally on Studio when feeValue is omitted", async () => { + const requestMock = vi.fn().mockImplementation(async ({method}: {method: string}) => { + if (method === "sim_getFeeConfig") { + return { + enabled: true, + policy: { + genPerTimeUnit: "10", + storageUnitPrice: "20", + receiptGasPrice: "30", + }, + }; + } + if (method === "eth_gasPrice") return "0x1"; + throw new Error(`unexpected request ${method}`); + }); + const {actions, estimateTransactionGas} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + isStudio: true, + requestMock, + }); + + await expect( + actions.writeContract({ + address: RECIPIENT_ADDRESS, + functionName: "ping", + validUntil: 123n, + fees: { + distribution: { + leaderTimeunitsAllocation: 100n, + validatorTimeunitsAllocation: 200n, + maxPriceGenPerTimeUnit: 10n, + }, + }, + }), + ).rejects.toThrow("stop_after_encoding"); + + expect(estimateTransactionGas.mock.calls[0][0].value).toBe(11_000n); + }); + + it("estimates fee distribution caps and fee value from FeeManager prices", async () => { + const publicClient = { + readContract: vi.fn().mockImplementation(async ({functionName}: {functionName: string}) => { + if (functionName === "GENPerTimeUnit") return 10n; + if (functionName === "storageUnitPrice") return 20n; + if (functionName === "quoteGasPrice") return 30n; + if (functionName === "messageFeeParamsBudgetFloor") return 1_234n; + if (functionName === "calculateRoundFees") return 77n; + throw new Error(`unexpected readContract ${functionName}`); + }), + }; + const {actions} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + publicClient, + feeManagerAddress: "0x00000000000000000000000000000000000000fe", + }); + + const fees = await actions.estimateTransactionFees({totalMessageFees: 5n}); + + expect(fees.policy).toEqual({ + enabled: true, + genPerTimeUnit: 10n, + storageUnitPrice: 20n, + receiptGasPrice: 30n, + executionBudgetFloor: 1_234n, + }); + expect(fees.distribution.maxPriceGenPerTimeUnit).toBe(12n); + expect(fees.distribution.storageFeeMaxGasPrice).toBe(24n); + expect(fees.distribution.receiptFeeMaxGasPrice).toBe(36n); + expect(fees.distribution.executionBudgetPerRound).toBe(500_000n); + expect(fees.feeValue).toBe(82n); + }); + + it("defaults total message fees from root and external message allocation budgets", async () => { + const publicClient = { + readContract: vi.fn().mockImplementation(async ({functionName}: {functionName: string}) => { + if (functionName === "GENPerTimeUnit") return 10n; + if (functionName === "storageUnitPrice") return 20n; + if (functionName === "quoteGasPrice") return 30n; + if (functionName === "messageFeeParamsBudgetFloor") return 1_234n; + if (functionName === "calculateRoundFees") return 77n; + throw new Error(`unexpected readContract ${functionName}`); + }), + }; + const {actions} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + publicClient, + feeManagerAddress: "0x00000000000000000000000000000000000000fe", + }); + + const fees = await actions.estimateTransactionFees({ + messageAllocations: [ + { + messageType: MessageType.Internal, + recipient: RECIPIENT_ADDRESS, + budget: 50n, + feeParams: "0x1234", + }, + { + messageType: MessageType.Internal, + parentIndex: 0n, + recipient: RECIPIENT_ADDRESS, + budget: 10n, + feeParams: "0x1234", + }, + { + messageType: MessageType.External, + recipient: RECIPIENT_ADDRESS, + budget: 30n, + feeParams: "0x1234", + }, + ], + }); + + expect(fees.distribution.totalMessageFees).toBe(80n); + expect(fees.feeValue).toBe(157n); + }); + + it("estimates Studio fee value from sim_getFeeConfig when no FeeManager contract exists", async () => { + const requestMock = vi.fn().mockImplementation(async ({method}: {method: string}) => { + if (method === "sim_getFeeConfig") { + return { + enabled: true, + policy: { + genPerTimeUnit: "10", + storageUnitPrice: "20", + receiptGasPrice: "30", + }, + }; + } + if (method === "eth_gasPrice") return "0x1"; + throw new Error(`unexpected request ${method}`); + }); + const {actions} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + isStudio: true, + requestMock, + }); + + const fees = await actions.estimateTransactionFees({priceCapHeadroomBps: 10_000n}); + + expect(fees.distribution.maxPriceGenPerTimeUnit).toBe(10n); + expect(fees.distribution.storageFeeMaxGasPrice).toBe(20n); + expect(fees.distribution.receiptFeeMaxGasPrice).toBe(30n); + expect(fees.distribution.executionBudgetPerRound).toBe(9_185_760n); + expect(fees.feeValue).toBe(9_196_760n); + }); + + it("prefers Studio's exposed message fee budget floor over local fallback math", async () => { + const requestMock = vi.fn().mockImplementation(async ({method}: {method: string}) => { + if (method === "sim_getFeeConfig") { + return { + enabled: true, + policy: { + genPerTimeUnit: "10", + storageUnitPrice: "20", + receiptGasPrice: "30", + fixedProposeReceiptGas: "1", + messageFeeParamsBudgetFloor: "700000", + }, + }; + } + if (method === "eth_gasPrice") return "0x1"; + throw new Error(`unexpected request ${method}`); + }); + const {actions} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + isStudio: true, + requestMock, + }); + + const fees = await actions.estimateTransactionFees({priceCapHeadroomBps: 10_000n}); + + expect(fees.policy.executionBudgetFloor).toBe(700_000n); + expect(fees.distribution.executionBudgetPerRound).toBe(700_000n); + expect(fees.feeValue).toBe(711_000n); + }); + + it("builds a Studio trusted fee preset from a simulation fee report", async () => { + const requestMock = vi.fn().mockImplementation(async ({method}: {method: string}) => { + if (method === "sim_getFeeConfig") { + return { + enabled: true, + policy: { + genPerTimeUnit: "10", + storageUnitPrice: "20", + receiptGasPrice: "30", + messageFeeParamsBudgetFloor: "400000", + }, + }; + } + if (method === "eth_gasPrice") return "0x1"; + throw new Error(`unexpected request ${method}`); + }); + const {actions} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + isStudio: true, + requestMock, + }); + + const fees = await actions.estimateTransactionFeesFromSimulation({ + simulation: { + feeAccounting: { + execution_fee_consumed: "100", + genvm_message_fee_consumed: "5", + message_fee_budget: "10", + message_fee_consumed: "5", + message_fee_refunded: "0", + external_message_fee_reserved: "0", + external_message_fee_reimbursed: "0", + external_message_fee_remainder: "0", + execution_fee_report: { + receiptGasPrice: "30", + proposalReceipt: { + eqBlocksOutputsLength: "10", + receiptBytes: "1034", + estimatedGas: "314544", + fee: "314544", + }, + messageReveal: { + messageBytes: "320", + messageCount: "1", + estimatedGas: "187120", + fee: "187120", + consensusAdditionalGas: "87120", + consensusAdditionalFee: "87120", + studioFixedOverheadGas: "100000", + studioFixedOverheadFee: "100000", + messages: [ + { + messageFeeMode: "mode1", + messageType: "Internal", + recipient: RECIPIENT_ADDRESS, + value: "0", + dataBytes: "2", + onAcceptance: true, + saltNonce: "0", + feeParams: "0x1234", + feeParamsDecoded: null, + feeParamsBytes: "2", + declaredBudget: "5", + allocationSubtree: "0x", + allocationSubtreeBytes: "0", + callKey: `0x${"12".repeat(32)}`, + }, + ], + }, + chargeableExecution: { + receiptAndNondetOutput: "501664", + storage: "0", + message: "0", + totalExecution: "501664", + totalWithMessage: "501664", + executionBudgetPerRound: "600000", + executionBudgetRemaining: "98336", + executionBudgetOverrun: "0", + executionBudgetExceeded: false, + }, + genvmBuckets: { + receiptAndNondetOutput: "100", + storage: "0", + message: "5", + totalExecution: "100", + totalWithMessage: "105", + executionBudgetPerRound: "600000", + executionBudgetRemaining: "599900", + executionBudgetOverrun: "0", + executionBudgetExceeded: false, + buckets: [ + {index: "0", name: "receiptAndNondetOutput", consumed: "100"}, + {index: "1", name: "storage", consumed: "0"}, + {index: "2", name: "message", consumed: "5"}, + ], + }, + executionMetering: { + chargeableExecutionFee: "501664", + genvmReportedExecution: "100", + genvmDeltaFromChargeable: "-501564", + }, + messageFees: { + budget: "10", + declaredConsumed: "5", + genvmMeteredConsumed: "5", + declaredRefunded: "0", + remaining: "5", + meteringDelta: "0", + reportedTotal: "5", + }, + totalEstimatedFee: "501664", + totalStudioMeteredFee: "688784", + }, + }, + }, + priceCapHeadroomBps: 10_000n, + }); + + expect(fees.observed).toEqual({ + executionFeeConsumed: 100n, + executionFeeReportTotal: 501_664n, + recommendedExecutionBudgetPerRound: 602_117n, + genvmMessageFeeConsumed: 5n, + messageFeeBudget: 10n, + messageFeeConsumed: 5n, + messageFeeRefunded: 0n, + internalDeclaredBudget: 5n, + externalMessageReserved: 0n, + externalMessageReimbursed: 0n, + externalMessageRemainder: 0n, + recommendedTotalMessageFees: 6n, + }); + expect(fees.distribution.executionBudgetPerRound).toBe(602_117n); + expect(fees.distribution.totalMessageFees).toBe(6n); + expect(fees.feeValue).toBe(613_123n); + }); + + it("builds a Studio trusted fee preset for a target write in one call", async () => { + const feeParams = encodeInternalMessageFeeParams({ + leaderTimeunitsAllocation: 5n, + validatorTimeunitsAllocation: 10n, + }); + const requestMock = vi.fn().mockImplementation(async ({method}: {method: string}) => { + if (method === "sim_getFeeConfig") { + return { + enabled: true, + policy: { + genPerTimeUnit: "10", + storageUnitPrice: "20", + receiptGasPrice: "30", + messageFeeParamsBudgetFloor: "400000", + }, + }; + } + if (method === "sim_estimateTransactionFees") { + return { + feeAccounting: { + execution_fee_consumed: "100", + message_fee_consumed: "50", + message_fee_budget: "110", + message_allocations: [ + { + messageType: MessageType.Internal, + onAcceptance: true, + parentIndex: ((1n << 256n) - 1n).toString(), + recipient: RECIPIENT_ADDRESS, + callKey: `0x${"00".repeat(32)}`, + budget: "110", + feeParams, + }, + ], + execution_fee_report: { + totalEstimatedFee: "501664", + }, + }, + feeReport: { + totalEstimatedFee: "501664", + }, + recommendedPreset: { + distribution: { + leaderTimeunitsAllocation: "100", + validatorTimeunitsAllocation: "200", + appealRounds: "0", + executionBudgetPerRound: "700000", + executionConsumed: "0", + totalMessageFees: "110", + rotations: ["0"], + maxPriceGenPerTimeUnit: "10", + storageFeeMaxGasPrice: "20", + receiptFeeMaxGasPrice: "30", + }, + messageAllocations: [ + { + messageType: MessageType.Internal, + onAcceptance: true, + parentIndex: ((1n << 256n) - 1n).toString(), + recipient: RECIPIENT_ADDRESS, + callKey: `0x${"00".repeat(32)}`, + budget: "110", + feeParams, + }, + ], + feeValue: "711110", + }, + }; + } + throw new Error(`unexpected request ${method}`); + }); + const {actions} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + isStudio: true, + requestMock, + }); + + const fees = await actions.estimateTransactionFeesForWrite({ + address: RECIPIENT_ADDRESS, + functionName: "update_storage", + args: ["after"], + value: 7n, + priceCapHeadroomBps: 10_000n, + messageAllocations: [ + { + messageType: MessageType.Internal, + recipient: RECIPIENT_ADDRESS, + budget: 110n, + feeParams, + }, + ], + }); + + const simCall = requestMock.mock.calls.find(([call]) => call.method === "sim_estimateTransactionFees")?.[0]; + expect(simCall).toBeDefined(); + expect(simCall.params[0].value).toBe("0x7"); + expect(simCall.params[0].fees.feeValue).toBe("511110"); + expect(simCall.params[0].fees.distribution.totalMessageFees).toBe("110"); + expect(simCall.params[0].fees.messageAllocations[0].budget).toBe("110"); + expect(fees.observed?.recommendedExecutionBudgetPerRound).toBe(602_117n); + expect(fees.observed?.messageFeeBudget).toBe(110n); + expect(fees.observed?.messageFeeConsumed).toBe(50n); + expect(fees.distribution.executionBudgetPerRound).toBe(700_000n); + expect(fees.distribution.totalMessageFees).toBe(110n); + expect(fees.messageAllocations?.[0].budget).toBe(110n); + expect(fees.feeValue).toBe(711_110n); + }); + + it("preserves mode-2 message allocations from simulation fee accounting", async () => { + const feeParams = encodeInternalMessageFeeParams({ + leaderTimeunitsAllocation: 5n, + validatorTimeunitsAllocation: 10n, + }); + const requestMock = vi.fn().mockImplementation(async ({method}: {method: string}) => { + if (method === "sim_getFeeConfig") { + return { + enabled: true, + policy: { + genPerTimeUnit: "10", + storageUnitPrice: "20", + receiptGasPrice: "30", + messageFeeParamsBudgetFloor: "400000", + }, + }; + } + if (method === "eth_gasPrice") return "0x1"; + throw new Error(`unexpected request ${method}`); + }); + const {actions} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + isStudio: true, + requestMock, + }); + + const fees = await actions.estimateTransactionFeesFromSimulation({ + simulation: { + feeAccounting: { + message_fee_consumed: "20", + message_allocations: [ + { + messageType: MessageType.Internal, + onAcceptance: false, + parentIndex: ((1n << 256n) - 1n).toString(), + recipient: RECIPIENT_ADDRESS, + callKey: `0x${"00".repeat(32)}`, + budget: "50", + feeParams, + }, + ], + }, + }, + priceCapHeadroomBps: 10_000n, + }); + + expect(fees.messageAllocations).toHaveLength(1); + expect(fees.messageAllocations?.[0].budget).toBe(50n); + expect(fees.messageAllocations?.[0].feeParams).toBe(feeParams); + expect(fees.distribution.totalMessageFees).toBe(50n); + expect(fees.feeValue).toBe(511_050n); + }); + + it("keeps Studio fee estimation gasless when sim_getFeeConfig is disabled", async () => { + const requestMock = vi.fn().mockImplementation(async ({method}: {method: string}) => { + if (method === "sim_getFeeConfig") { + return { + enabled: false, + policy: { + genPerTimeUnit: "0", + storageUnitPrice: "0", + receiptGasPrice: "0", + }, + }; + } + if (method === "eth_gasPrice") return "0x1"; + throw new Error(`unexpected request ${method}`); + }); + const {actions} = setupWriteContractHarness({ + initialAbi: ADD_TRANSACTION_ABI_WITH_FEES, + isStudio: true, + requestMock, + }); + + const fees = await actions.estimateTransactionFees(); + + expect(fees.policy.enabled).toBe(false); + expect(fees.distribution.leaderTimeunitsAllocation).toBe(0n); + expect(fees.distribution.validatorTimeunitsAllocation).toBe(0n); + expect(fees.distribution.executionBudgetPerRound).toBe(0n); + expect(fees.distribution.maxPriceGenPerTimeUnit).toBe(0n); + expect(fees.distribution.storageFeeMaxGasPrice).toBe(0n); + expect(fees.distribution.receiptFeeMaxGasPrice).toBe(0n); + expect(fees.feeValue).toBe(0n); + }); + it("retries with v6 signature when v5 signature fails with ABI mismatch", async () => { const signTransaction = vi .fn() @@ -307,7 +1296,7 @@ describe("contractActions addTransaction ABI compatibility", () => { from: SENDER_ADDRESS, to: MAIN_CONTRACT_ADDRESS, value: "0x0", - gas: "0x5208", + gas: "0xa410", nonce: "0x0", type: "0x0", chainId: "0xeec7", @@ -471,6 +1460,29 @@ const FINALIZE_TX_ABI = [ }, ]; +const FEE_MANAGEMENT_ABI = [ + { + type: "function" as const, + name: "topUpFees", + stateMutability: "payable" as const, + inputs: [ + {name: "_txId", type: "bytes32"}, + {name: "_feesDistribution", type: "tuple", components: FEES_DISTRIBUTION_COMPONENTS}, + ], + outputs: [], + }, + { + type: "function" as const, + name: "topUpAndSubmitAppeal", + stateMutability: "payable" as const, + inputs: [ + {name: "_txId", type: "bytes32"}, + {name: "_feesDistribution", type: "tuple", components: FEES_DISTRIBUTION_COMPONENTS}, + ], + outputs: [], + }, +] as const; + const finalizeTransactionSelector = encodeFunctionData({ abi: FINALIZE_TX_ABI as any, functionName: "finalizeTransaction", @@ -483,6 +1495,46 @@ const finalizeIdlenessSelector = encodeFunctionData({ args: [[MOCK_GENLAYER_TX_ID]], }).slice(0, 10); +const topUpFeesSelector = encodeFunctionData({ + abi: FEE_MANAGEMENT_ABI as any, + functionName: "topUpFees", + args: [ + MOCK_GENLAYER_TX_ID, + { + leaderTimeunitsAllocation: 0n, + validatorTimeunitsAllocation: 0n, + appealRounds: 0n, + executionBudgetPerRound: 0n, + executionConsumed: 0n, + totalMessageFees: 0n, + rotations: [0n], + maxPriceGenPerTimeUnit: 0n, + storageFeeMaxGasPrice: 0n, + receiptFeeMaxGasPrice: 0n, + }, + ], +}).slice(0, 10); + +const topUpAndSubmitAppealSelector = encodeFunctionData({ + abi: FEE_MANAGEMENT_ABI as any, + functionName: "topUpAndSubmitAppeal", + args: [ + MOCK_GENLAYER_TX_ID, + { + leaderTimeunitsAllocation: 0n, + validatorTimeunitsAllocation: 0n, + appealRounds: 0n, + executionBudgetPerRound: 0n, + executionConsumed: 0n, + totalMessageFees: 0n, + rotations: [0n], + maxPriceGenPerTimeUnit: 0n, + storageFeeMaxGasPrice: 0n, + receiptFeeMaxGasPrice: 0n, + }, + ], +}).slice(0, 10); + const setupFinalizeHarness = ({receiptStatus = "success"}: {receiptStatus?: string} = {}) => { const signTransaction = vi.fn().mockResolvedValue("0xsigned"); const sendRawTransaction = vi.fn().mockResolvedValue(MOCK_EVM_TX_HASH); @@ -518,6 +1570,48 @@ const setupFinalizeHarness = ({receiptStatus = "success"}: {receiptStatus?: stri return {actions, signTransaction, sendRawTransaction, waitForTransactionReceipt, estimateTransactionGas, client}; }; +const setupFeeManagementHarness = ({ + receiptStatus = "success", + isStudio = false, +}: { + receiptStatus?: string; + isStudio?: boolean; +} = {}) => { + const signTransaction = vi.fn().mockResolvedValue("0xsigned"); + const sendRawTransaction = vi.fn().mockResolvedValue(MOCK_EVM_TX_HASH); + const waitForTransactionReceipt = vi.fn().mockResolvedValue({status: receiptStatus, logs: []}); + const estimateTransactionGas = vi.fn().mockResolvedValue(21_000n); + + const client = { + chain: { + id: 61_127, + isStudio, + consensusMainContract: { + address: MAIN_CONTRACT_ADDRESS, + abi: FEE_MANAGEMENT_ABI, + bytecode: "0x", + }, + }, + account: { + address: SENDER_ADDRESS, + type: "local", + signTransaction, + }, + getCurrentNonce: vi.fn().mockResolvedValue(0n), + estimateTransactionGas, + sendRawTransaction, + request: vi.fn().mockImplementation(async ({method}: {method: string}) => { + if (method === "eth_gasPrice") return "0x1"; + throw new Error(`Unexpected RPC method: ${method}`); + }), + }; + + const publicClient = {waitForTransactionReceipt}; + const actions = contractActions(client as any, publicClient as any); + + return {actions, signTransaction, sendRawTransaction, waitForTransactionReceipt, estimateTransactionGas, client}; +}; + describe("contractActions getContractCode", () => { const SOURCE = '# v0.1.0\n# { "Depends": "py-genlayer:test" }\n\nfrom genlayer import *\n'; const SOURCE_B64 = Buffer.from(SOURCE, "utf-8").toString("base64"); @@ -648,6 +1742,145 @@ describe("contractActions getContractSchemaForCode", () => { }); }); +describe("contractActions fee management", () => { + it("encodes topUpFees(bytes32, FeesDistribution) and returns the EVM tx hash", async () => { + const {actions, signTransaction, sendRawTransaction} = setupFeeManagementHarness(); + + const evmHash = await actions.topUpFees({ + txId: MOCK_GENLAYER_TX_ID, + value: 999n, + distribution: { + leaderTimeunitsAllocation: 100n, + validatorTimeunitsAllocation: 200n, + appealRounds: 1n, + executionBudgetPerRound: 500_000n, + totalMessageFees: 30n, + rotations: [0n, 2n], + maxPriceGenPerTimeUnit: 12n, + storageFeeMaxGasPrice: 24n, + receiptFeeMaxGasPrice: 36n, + }, + }); + + expect(evmHash).toBe(MOCK_EVM_TX_HASH); + expect(sendRawTransaction).toHaveBeenCalledWith({serializedTransaction: "0xsigned"}); + const txRequest = signTransaction.mock.calls[0][0]; + expect(txRequest.to).toBe(MAIN_CONTRACT_ADDRESS); + expect(txRequest.value).toBe(999n); + expect(txRequest.data.slice(0, 10)).toBe(topUpFeesSelector); + + const decoded = decodeFunctionData({ + abi: FEE_MANAGEMENT_ABI as any, + data: txRequest.data, + }); + const [txId, distribution] = decoded.args as any[]; + expect(txId).toBe(MOCK_GENLAYER_TX_ID); + expect(distribution.leaderTimeunitsAllocation).toBe(100n); + expect(distribution.validatorTimeunitsAllocation).toBe(200n); + expect(distribution.appealRounds).toBe(1n); + expect(distribution.executionBudgetPerRound).toBe(500_000n); + expect(distribution.totalMessageFees).toBe(30n); + expect(distribution.rotations).toEqual([0n, 2n]); + expect(distribution.maxPriceGenPerTimeUnit).toBe(12n); + expect(distribution.storageFeeMaxGasPrice).toBe(24n); + expect(distribution.receiptFeeMaxGasPrice).toBe(36n); + }); + + it("encodes topUpAndSubmitAppeal(bytes32, FeesDistribution) and returns the GenLayer tx id", async () => { + const {actions, signTransaction, sendRawTransaction} = setupFeeManagementHarness(); + + const txId = await actions.topUpAndSubmitAppeal({ + txId: MOCK_GENLAYER_TX_ID, + value: 1234n, + distribution: { + appealRounds: 1n, + rotations: [0n, 1n], + }, + }); + + expect(txId).toBe(MOCK_GENLAYER_TX_ID); + expect(sendRawTransaction).toHaveBeenCalledWith({serializedTransaction: "0xsigned"}); + const txRequest = signTransaction.mock.calls[0][0]; + expect(txRequest.to).toBe(MAIN_CONTRACT_ADDRESS); + expect(txRequest.value).toBe(1234n); + expect(txRequest.data.slice(0, 10)).toBe(topUpAndSubmitAppealSelector); + + const decoded = decodeFunctionData({ + abi: FEE_MANAGEMENT_ABI as any, + data: txRequest.data, + }); + const [decodedTxId, distribution] = decoded.args as any[]; + expect(decodedTxId).toBe(MOCK_GENLAYER_TX_ID); + expect(distribution.appealRounds).toBe(1n); + expect(distribution.rotations).toEqual([0n, 1n]); + }); + + it("throws when a fee management consensus call is reverted", async () => { + const {actions} = setupFeeManagementHarness({receiptStatus: "reverted"}); + + await expect( + actions.topUpFees({ + txId: MOCK_GENLAYER_TX_ID, + value: 1n, + distribution: {}, + }), + ).rejects.toThrow(/Top up fees reverted/); + }); + + it("returns the Studio RPC hash for fee management calls without waiting for an EVM receipt", async () => { + const {actions, waitForTransactionReceipt} = setupFeeManagementHarness({isStudio: true}); + + const hash = await actions.topUpFees({ + txId: MOCK_GENLAYER_TX_ID, + value: 1n, + distribution: {}, + }); + + expect(hash).toBe(MOCK_EVM_TX_HASH); + expect(waitForTransactionReceipt).not.toHaveBeenCalled(); + }); + + it("returns the Studio RPC hash for external-wallet fee management calls without waiting for an EVM receipt", async () => { + const request = vi.fn().mockImplementation(async ({method}: {method: string}) => { + if (method === "eth_gasPrice") return "0x1"; + if (method === "eth_sendTransaction") return MOCK_EVM_TX_HASH; + throw new Error(`Unexpected RPC method: ${method}`); + }); + const waitForTransactionReceipt = vi.fn(); + const client = { + chain: { + id: 61_127, + isStudio: true, + consensusMainContract: { + address: MAIN_CONTRACT_ADDRESS, + abi: FEE_MANAGEMENT_ABI, + bytecode: "0x", + }, + }, + account: { + address: SENDER_ADDRESS, + type: "json-rpc", + }, + getCurrentNonce: vi.fn().mockResolvedValue(0n), + estimateTransactionGas: vi.fn().mockResolvedValue(21_000n), + request, + }; + const actions = contractActions(client as any, {waitForTransactionReceipt} as any); + + const hash = await actions.topUpFees({ + txId: MOCK_GENLAYER_TX_ID, + value: 1n, + distribution: {}, + }); + + expect(hash).toBe(MOCK_EVM_TX_HASH); + expect(request).toHaveBeenCalledWith(expect.objectContaining({ + method: "eth_sendTransaction", + })); + expect(waitForTransactionReceipt).not.toHaveBeenCalled(); + }); +}); + describe("contractActions finalizeTransaction", () => { it("encodes finalizeTransaction(bytes32) and returns EVM tx hash", async () => { const {actions, signTransaction, sendRawTransaction} = setupFinalizeHarness(); From 2c712c78a6cdc115add463a7a10cbe825e5fb158 Mon Sep 17 00:00:00 2001 From: Edgars Date: Thu, 4 Jun 2026 03:26:17 +0100 Subject: [PATCH 12/14] fix: handle studio raw transaction hashes --- src/contracts/actions.ts | 24 +++++++++++++++++++++--- tests/contracts-actions.test.ts | 6 +++--- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/contracts/actions.ts b/src/contracts/actions.ts index 5c61747..508925d 100644 --- a/src/contracts/actions.ts +++ b/src/contracts/actions.ts @@ -1025,6 +1025,7 @@ const DEFAULT_GAS_PER_CHANGED_SLOT = 1_000n; const DEFAULT_CALLDATA_GAS_PER_BYTE = 16n; const DEFAULT_FIXED_PROPOSE_RECEIPT_GAS = 210_000n; const TRANSACTION_GAS_HEADROOM_BPS = 20_000n; +const DEFAULT_PARENT_MESSAGE_RECEIPT_HEADROOM = 10_000n; const VALIDATORS_PER_ROUND = [ 5n, 7n, @@ -1186,10 +1187,13 @@ const buildEstimatedFeesDistribution = ( "priceCapHeadroomBps", DEFAULT_PRICE_CAP_HEADROOM_BPS, ); - const executionBudgetDefault = defaultExecutionBudgetPerRound(policy); + const baseExecutionBudgetDefault = defaultExecutionBudgetPerRound(policy); + const messageAllocations = options?.messageAllocations + ? normalizeMessageFeeAllocations(options.messageAllocations) + : undefined; const totalMessageFees = options?.totalMessageFees ?? ( - options?.messageAllocations - ? normalizeMessageFeeAllocations(options.messageAllocations).reduce( + messageAllocations + ? messageAllocations.reduce( (sum, allocation) => { if ( allocation.messageType === MessageType.External || @@ -1203,6 +1207,12 @@ const buildEstimatedFeesDistribution = ( ) : undefined ); + const emitsMessages = (messageAllocations?.length ?? 0) > 0 || ( + totalMessageFees !== undefined && toUInt(totalMessageFees, "totalMessageFees") > 0n + ); + const executionBudgetDefault = emitsMessages + ? baseExecutionBudgetDefault + (policy.receiptGasPrice * DEFAULT_PARENT_MESSAGE_RECEIPT_HEADROOM) + : baseExecutionBudgetDefault; return createFeesDistribution({ leaderTimeunitsAllocation: options?.leaderTimeunitsAllocation ?? ( @@ -2036,6 +2046,14 @@ const _sendTransaction = async ({ const serializedTransaction = await validatedSenderAccount.signTransaction(transactionRequest); const txHash = await client.sendRawTransaction({serializedTransaction: serializedTransaction}); + + if (client.chain.isStudio) { + // Studio RPCs process eth_sendRawTransaction internally. The returned + // hash is already the GenLayer tx hash; there is no separate EVM + // receipt to wait for or consensus event to extract. + return txHash; + } + const receipt = await publicClient.waitForTransactionReceipt({hash: txHash}); if (receipt.status === "reverted") { diff --git a/tests/contracts-actions.test.ts b/tests/contracts-actions.test.ts index 572b1fe..2eb1c19 100644 --- a/tests/contracts-actions.test.ts +++ b/tests/contracts-actions.test.ts @@ -719,7 +719,7 @@ describe("contractActions addTransaction ABI compatibility", () => { expect(fees.distribution.maxPriceGenPerTimeUnit).toBe(12n); expect(fees.distribution.storageFeeMaxGasPrice).toBe(24n); expect(fees.distribution.receiptFeeMaxGasPrice).toBe(36n); - expect(fees.distribution.executionBudgetPerRound).toBe(500_000n); + expect(fees.distribution.executionBudgetPerRound).toBe(800_000n); expect(fees.feeValue).toBe(82n); }); @@ -1061,7 +1061,7 @@ describe("contractActions addTransaction ABI compatibility", () => { const simCall = requestMock.mock.calls.find(([call]) => call.method === "sim_estimateTransactionFees")?.[0]; expect(simCall).toBeDefined(); expect(simCall.params[0].value).toBe("0x7"); - expect(simCall.params[0].fees.feeValue).toBe("511110"); + expect(simCall.params[0].fees.feeValue).toBe("811110"); expect(simCall.params[0].fees.distribution.totalMessageFees).toBe("110"); expect(simCall.params[0].fees.messageAllocations[0].budget).toBe("110"); expect(fees.observed?.recommendedExecutionBudgetPerRound).toBe(602_117n); @@ -1123,7 +1123,7 @@ describe("contractActions addTransaction ABI compatibility", () => { expect(fees.messageAllocations?.[0].budget).toBe(50n); expect(fees.messageAllocations?.[0].feeParams).toBe(feeParams); expect(fees.distribution.totalMessageFees).toBe(50n); - expect(fees.feeValue).toBe(511_050n); + expect(fees.feeValue).toBe(811_050n); }); it("keeps Studio fee estimation gasless when sim_getFeeConfig is disabled", async () => { From ef7af12db46f8dc19357db3cbc0bd164a71772e8 Mon Sep 17 00:00:00 2001 From: Edgars Date: Thu, 4 Jun 2026 06:03:53 +0100 Subject: [PATCH 13/14] fix: align studio fee floor fallback --- src/contracts/actions.ts | 17 ++++++++++++++--- tests/contracts-actions.test.ts | 4 ++-- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/contracts/actions.ts b/src/contracts/actions.ts index 508925d..0b58edf 100644 --- a/src/contracts/actions.ts +++ b/src/contracts/actions.ts @@ -1017,13 +1017,15 @@ const DEFAULT_PRICE_CAP_HEADROOM_BPS = 12_000n; const DEFAULT_LEADER_TIMEUNITS_ALLOCATION = 100n; const DEFAULT_VALIDATOR_TIMEUNITS_ALLOCATION = 200n; const DEFAULT_TRANSACTION_EXECUTION_BUDGET_PER_ROUND = 500_000n; -const MIN_RECEIPT_BYTES = 512n; const DEFAULT_RECEIPT_SLOTS_CHANGED = 7n; const DEFAULT_INTRINSIC_GAS = 21_000n; const DEFAULT_BOOTLOADER_OVERHEAD = 60_000n; const DEFAULT_GAS_PER_CHANGED_SLOT = 1_000n; const DEFAULT_CALLDATA_GAS_PER_BYTE = 16n; const DEFAULT_FIXED_PROPOSE_RECEIPT_GAS = 210_000n; +const DEFAULT_FIXED_MESSAGE_REVEAL_GAS = 100_000n; +const DEFAULT_MESSAGE_REVEAL_LENGTH_SLOTS = 32n; +const DEFAULT_NONDET_OUTPUT_LENGTH_BYTES = 32n; const TRANSACTION_GAS_HEADROOM_BPS = 20_000n; const DEFAULT_PARENT_MESSAGE_RECEIPT_HEADROOM = 10_000n; const VALIDATORS_PER_ROUND = [ @@ -1105,13 +1107,22 @@ const extractStudioFeePolicy = (config: unknown): FeePolicyQuote => { "policy.fixedProposeReceiptGas", DEFAULT_FIXED_PROPOSE_RECEIPT_GAS, ); + const fixedMessageRevealGas = bigintFromUnknown( + policyRecord.fixedMessageRevealGas, + "policy.fixedMessageRevealGas", + DEFAULT_FIXED_MESSAGE_REVEAL_GAS, + ); const executionBudgetFloor = policyRecord.messageFeeParamsBudgetFloor == null ? receiptGasPrice * ( fixedProposeReceiptGas + intrinsicGas + bootloaderOverhead + - (MIN_RECEIPT_BYTES * calldataGasPerByte) + - (DEFAULT_RECEIPT_SLOTS_CHANGED * gasPerChangedSlot) + (DEFAULT_RECEIPT_SLOTS_CHANGED * gasPerChangedSlot) + + fixedMessageRevealGas + + intrinsicGas + + bootloaderOverhead + + (DEFAULT_MESSAGE_REVEAL_LENGTH_SLOTS * gasPerChangedSlot) + + (DEFAULT_NONDET_OUTPUT_LENGTH_BYTES * calldataGasPerByte) ) : bigintFromUnknown( policyRecord.messageFeeParamsBudgetFloor, diff --git a/tests/contracts-actions.test.ts b/tests/contracts-actions.test.ts index 2eb1c19..239711a 100644 --- a/tests/contracts-actions.test.ts +++ b/tests/contracts-actions.test.ts @@ -794,8 +794,8 @@ describe("contractActions addTransaction ABI compatibility", () => { expect(fees.distribution.maxPriceGenPerTimeUnit).toBe(10n); expect(fees.distribution.storageFeeMaxGasPrice).toBe(20n); expect(fees.distribution.receiptFeeMaxGasPrice).toBe(30n); - expect(fees.distribution.executionBudgetPerRound).toBe(9_185_760n); - expect(fees.feeValue).toBe(9_196_760n); + expect(fees.distribution.executionBudgetPerRound).toBe(15_345_360n); + expect(fees.feeValue).toBe(15_356_360n); }); it("prefers Studio's exposed message fee budget floor over local fallback math", async () => { From 660b1b59a3d59cd8a7a6210fb431141a8a9d216c Mon Sep 17 00:00:00 2001 From: Edgars Date: Thu, 4 Jun 2026 14:18:45 +0100 Subject: [PATCH 14/14] fix: satisfy fee estimate typecheck --- src/contracts/actions.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/contracts/actions.ts b/src/contracts/actions.ts index 0b58edf..dc36299 100644 --- a/src/contracts/actions.ts +++ b/src/contracts/actions.ts @@ -1219,7 +1219,7 @@ const buildEstimatedFeesDistribution = ( : undefined ); const emitsMessages = (messageAllocations?.length ?? 0) > 0 || ( - totalMessageFees !== undefined && toUInt(totalMessageFees, "totalMessageFees") > 0n + totalMessageFees !== undefined && toUInt(totalMessageFees, "totalMessageFees", 0n) > 0n ); const executionBudgetDefault = emitsMessages ? baseExecutionBudgetDefault + (policy.receiptGasPrice * DEFAULT_PARENT_MESSAGE_RECEIPT_HEADROOM)