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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions .github/workflows/upgrade-checks.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
name: Upgrade checks

# Runs a network upgrade's feature checks against testnet or mainnet, such as 15 minutes after
# activation. The job fails when a case fails. Blocked cases, such as funded mainnet cases
# without UPGRADE_CHECKS_PRIVATE_KEY, don't fail it.
on:
workflow_dispatch:
inputs:
upgrade:
description: Network upgrade to check
required: true
default: t14
network:
description: Network to check
required: true
type: choice
options: [testnet, mainnet]
default: testnet
mode:
description: post expects the upgrade's behavior to work; pre expects it to be rejected
required: true
type: choice
options: [post, pre]
default: post

permissions: {}

# Funded mainnet cases send from one key, so runs on a network don't overlap.
concurrency:
group: upgrade-checks-${{ inputs.network }}
cancel-in-progress: false

jobs:
checks:
name: ${{ inputs.upgrade }} on ${{ inputs.network }} (${{ inputs.mode }})
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
id-token: write
steps:
- name: Secure runner
uses: tempoxyz/gh-actions/actions/secure-runner@35019557465e3c38ee3468be171771fd73577584 # 2026-10-20T06-22-38Z-35019557

- name: Clone repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false

- name: Setup pnpm
uses: tempoxyz/gh-actions/vendor/pnpm/action-setup@35019557465e3c38ee3468be171771fd73577584 # 2026-10-20T06-22-38Z-35019557
with:
run_install: false
version: 10.28.1

- name: Setup Node.js
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
with:
node-version: 24.22.3
cache: pnpm
cache-dependency-path: pnpm-lock.yaml

- name: Install dependencies
run: pnpm install --frozen-lockfile

- name: Run upgrade checks
env:
UPGRADE: ${{ inputs.upgrade }}
NETWORK: ${{ inputs.network }}
MODE: ${{ inputs.mode }}
# Sends RPC through the Tempo API as an authenticated client.
TEMPO_RPC_API_KEY: ${{ secrets.TEMPO_RPC_API_KEY }}
# Optional. Funds the mainnet cases that send transactions.
UPGRADE_CHECKS_PRIVATE_KEY: ${{ secrets.UPGRADE_CHECKS_PRIVATE_KEY }}
# Optional. The stablecoin that pays fees and test payments; defaults per network.
UPGRADE_CHECKS_TOKEN: ${{ vars.UPGRADE_CHECKS_TOKEN }}
run: pnpm upgrade-checks --upgrade "$UPGRADE" --network "$NETWORK" --mode "$MODE"

- name: Upload result
if: ${{ !cancelled() }}
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: upgrade-checks-${{ inputs.upgrade }}-${{ inputs.network }}-${{ inputs.mode }}
path: upgrade-checks-result.json
if-no-files-found: error
retention-days: 30
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,6 @@ lighthouse-*.json
playwright-report/
test-results/
.zed

# Upgrade checks
upgrade-checks-result.json
7 changes: 6 additions & 1 deletion e2e/rpc.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import type { BrowserContext } from '@playwright/test'
import { tempoModerato } from 'viem/chains'

/** The Tempo API's keyed RPC proxy for a chain. It takes `authorization: Bearer <TEMPO_RPC_API_KEY>`. */
export function tempoApiRpcUrl(chainId: number) {
return `https://api.tempo.xyz/rpc/${chainId}`
}

// The page keeps its public RPC URL. Only Node sees the key;
// Playwright's request client would record it in uploaded traces.
export async function installAuthenticatedRpc(
Expand All @@ -26,7 +31,7 @@ export async function installAuthenticatedRpc(
try {
// The Tempo API proxies keyed RPC to Moderato as an authenticated client,
// which the per-IP connection limit on anonymous traffic does not apply to.
const response = await fetch(`https://api.tempo.xyz/rpc/${tempoModerato.id}`, {
const response = await fetch(tempoApiRpcUrl(tempoModerato.id), {
method: 'POST',
headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
body: request.postData(),
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"og:probe": "node --experimental-strip-types scripts/probe-og.ts",
"og:goldens": "node scripts/og-goldens.mjs",
"og:goldens:check": "node scripts/og-goldens.mjs --check",
"check:styles": "node scripts/check-styles.mjs && oxlint src"
"check:styles": "node scripts/check-styles.mjs && oxlint src",
"upgrade-checks": "tsx scripts/upgrade-checks/run.ts"
},
"dependencies": {
"@iconify-json/lucide": "^1.2.114",
Expand Down
24 changes: 24 additions & 0 deletions scripts/upgrade-checks/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { type Address, type Chain, http } from 'viem'
import { createClient } from 'viem/tempo'
import { tempoApiRpcUrl } from '../../e2e/rpc'

/**
* A Tempo client for the checks. With `apiKey` (`TEMPO_RPC_API_KEY`), RPC goes through the Tempo
* API's keyed proxy, as the live E2E tests do. Only the header carries the key, so `url` is safe to log.
*/
export function createCheckClient(options: { chain: Chain; token: Address; apiKey?: string }) {
const { chain, token, apiKey } = options
const url = apiKey ? tempoApiRpcUrl(chain.id) : chain.rpcUrls.default.http[0]
const client = createClient({
chain,
feeToken: token,
transport: http(url, {
fetchOptions: apiKey ? { headers: { authorization: `Bearer ${apiKey}` } } : undefined,
retryCount: 2,
timeout: 30_000,
}),
})
return { client, url }
}

export type Client = ReturnType<typeof createCheckClient>['client']
226 changes: 226 additions & 0 deletions scripts/upgrade-checks/run.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
/**
* Runs a network upgrade's feature checks against testnet or mainnet and writes a machine-readable
* result, so a workflow can run them right after activation and report what works.
*
* pnpm upgrade-checks --upgrade t14 --network testnet [--mode post|pre] [--out <FILE>]
*
* - `post` (the default) expects the upgrade's behavior to work. `pre` runs before activation and
* expects it to be rejected.
* - Read-only cases always run. Cases that send transactions fund fresh accounts from the testnet
* faucet, or on mainnet from `UPGRADE_CHECKS_PRIVATE_KEY`. Without that key they report blocked.
* - `TEMPO_RPC_API_KEY` sends RPC through the Tempo API's keyed proxy, as the live E2E tests do.
* - Writes `upgrade-checks-result.json`, adds a Markdown table to `$GITHUB_STEP_SUMMARY` when set,
* and exits 1 when any case fails. Blocked cases don't fail the run.
*/
import { appendFileSync, writeFileSync } from 'node:fs'
import { parseArgs } from 'node:util'
import { type Address, type Chain, isAddress, parseUnits } from 'viem'
import { tempo, tempoModerato } from 'viem/chains'
import { Account, Addresses } from 'viem/tempo'
import { createCheckClient } from './client'
import { t14 } from './t14'
import type { Case, CaseOutcome, Context, Mode, Network, Status, Tx, Upgrade } from './types'

const upgrades: Record<string, Upgrade> = { t14 }

const chains: Record<Network, Chain> = { testnet: tempoModerato, mainnet: tempo }

/** AlphaUSD on testnet, which the faucet sends. pathUSD on mainnet. */
const defaultTokens: Record<Network, Address> = {
testnet: '0x20c0000000000000000000000000000000000001',
mainnet: Addresses.pathUsd,
}

const caseTimeoutMs = 180_000

type CaseResult = {
id: string
name: string
area: string
needsFunds: boolean
status: Status
detail: string
txs: Tx[]
durationMs: number
}

const { values } = parseArgs({
options: {
upgrade: { type: 'string', default: 't14' },
network: { type: 'string', default: 'testnet' },
mode: { type: 'string', default: 'post' },
out: { type: 'string', default: 'upgrade-checks-result.json' },
only: { type: 'string' },
},
})

const upgrade = upgrades[values.upgrade.toLowerCase()]
if (!upgrade)
fatal(`Unknown upgrade "${values.upgrade}". Known: ${Object.keys(upgrades).join(', ')}.`)
if (values.network !== 'testnet' && values.network !== 'mainnet')
fatal('--network must be testnet or mainnet.')
if (values.mode !== 'pre' && values.mode !== 'post') fatal('--mode must be pre or post.')

const network = values.network as Network
const mode = values.mode as Mode
const chain = chains[network]
const token = (process.env.UPGRADE_CHECKS_TOKEN || defaultTokens[network]) as Address
if (!isAddress(token)) fatal('UPGRADE_CHECKS_TOKEN must be a token address.')

const { client, url: rpcUrl } = createCheckClient({
chain,
token,
apiKey: process.env.TEMPO_RPC_API_KEY || undefined,
})

const explorer = chain.blockExplorers?.default.url
const txUrl = (tx: Tx): Tx => ({ ...tx, url: explorer ? `${explorer}/tx/${tx.hash}` : undefined })

const fund = fundingFor(network)
const ctx: Context = {
network,
mode,
chain,
client,
token,
activation: upgrade.activation[network],
fund: fund ?? (async () => undefined),
state: new Map(),
log: (message) => console.log(` ${message}`),
}

const startedAt = new Date().toISOString()
const block = await client.getBlockNumber().catch(() => undefined)
const only = values.only?.split(',')
const results: CaseResult[] = []

console.log(
`${upgrade.name} checks · ${network} (${chain.id}) · ${mode} · block ${block ?? 'unknown'} · ${rpcUrl}`,
)
for (const item of upgrade.cases) {
if (only && !only.includes(item.id)) continue
console.log(`\n${item.id}: ${item.name}`)
const started = Date.now()
const outcome = await runCase(item)
const result: CaseResult = {
id: item.id,
name: item.name,
area: item.area,
needsFunds: item.needsFunds,
status: outcome.status,
detail: outcome.detail,
txs: (outcome.txs ?? []).map(txUrl),
durationMs: Date.now() - started,
}
results.push(result)
console.log(` → ${result.status.toUpperCase()}: ${result.detail}`)
for (const tx of result.txs) console.log(` ${tx.label}: ${tx.url ?? tx.hash}`)
}

const summary = { pass: 0, fail: 0, blocked: 0 }
for (const result of results) summary[result.status]++
const report = {
upgrade: upgrade.name,
network,
chainId: chain.id,
mode,
rpc: rpcUrl,
block: block === undefined ? null : Number(block),
startedAt,
finishedAt: new Date().toISOString(),
cases: results,
summary,
}
writeFileSync(values.out, `${JSON.stringify(report, null, 2)}\n`)
console.log(
`\n${summary.pass} passed, ${summary.fail} failed, ${summary.blocked} blocked · wrote ${values.out}`,
)
if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, markdown())
process.exit(summary.fail > 0 ? 1 : 0)

async function runCase(item: Case): Promise<CaseOutcome> {
if (item.modes && !item.modes.includes(mode))
return { status: 'blocked', detail: `Runs in ${item.modes.join(' and ')} mode only.` }
if (item.needsFunds && !fund)
return { status: 'blocked', detail: 'No funded mainnet key: set UPGRADE_CHECKS_PRIVATE_KEY.' }
const missing = (item.dependsOn ?? []).filter(
(id) => results.find((result) => result.id === id)?.status !== 'pass',
)
if (missing.length > 0)
return { status: 'blocked', detail: `Needs ${missing.join(', ')} to pass.` }
let timer: ReturnType<typeof setTimeout> | undefined
try {
return await Promise.race([
item.run(ctx),
new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new Error(`Timed out after ${caseTimeoutMs / 1000}s.`)),
caseTimeoutMs,
)
}),
])
} catch (error) {
return { status: 'fail', detail: errorSummary(error) }
} finally {
clearTimeout(timer)
}
}

/** How funded cases get stablecoins: the testnet faucet, or a transfer from the mainnet key. */
function fundingFor(network: Network): Context['fund'] | undefined {
if (network === 'testnet')
return async (address) => {
const receipts = await client.faucet.fundSync({ account: address })
const receipt =
receipts.find((item) =>
item.logs.some((log) => log.address.toLowerCase() === token.toLowerCase()),
) ?? receipts[0]
return receipt ? { label: 'Faucet', hash: receipt.transactionHash } : undefined
}
const privateKey = process.env.UPGRADE_CHECKS_PRIVATE_KEY
if (!privateKey) return undefined
const funder = Account.fromSecp256k1(privateKey as `0x${string}`)
const amount = parseUnits(process.env.UPGRADE_CHECKS_FUND_AMOUNT || '0.2', 6)
return async (address) => {
const { receipt } = await client.token.transferSync({
account: funder,
amount,
to: address,
token,
})
return { label: 'Funding', hash: receipt.transactionHash }
}
}

function errorSummary(error: unknown) {
if (!(error instanceof Error)) return String(error).slice(0, 400)
const { shortMessage, details } = error as Error & { shortMessage?: string; details?: string }
const text = [shortMessage ?? error.message, details].filter(Boolean).join(' · ')
return text.replace(/\s+/g, ' ').slice(0, 400)
}

function markdown() {
const icon: Record<Status, string> = { pass: '✅', fail: '❌', blocked: '⏸️' }
const cell = (text: string) => text.replace(/\|/g, '\\|').replace(/\n/g, ' ')
const rows = results.map((result) => {
const links = result.txs
.map((tx) => (tx.url ? `[${tx.label}](${tx.url})` : tx.label))
.join(', ')
return `| ${icon[result.status]} ${result.status} | ${cell(result.name)} | ${result.area} | ${cell(result.detail)} | ${links} |`
})
return [
`## ${upgrade.name} checks on ${network} (${mode})`,
'',
`${summary.pass} passed, ${summary.fail} failed, ${summary.blocked} blocked at block ${block ?? 'unknown'}.`,
'',
'| Result | Case | Area | Detail | Transactions |',
'| --- | --- | --- | --- | --- |',
...rows,
'',
].join('\n')
}

function fatal(message: string): never {
console.error(message)
process.exit(2)
}
Loading
Loading