diff --git a/.github/workflows/upgrade-checks.yml b/.github/workflows/upgrade-checks.yml new file mode 100644 index 000000000..da94087b6 --- /dev/null +++ b/.github/workflows/upgrade-checks.yml @@ -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 diff --git a/.gitignore b/.gitignore index 361c0615d..d5104dd06 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,6 @@ lighthouse-*.json playwright-report/ test-results/ .zed + +# Upgrade checks +upgrade-checks-result.json diff --git a/e2e/rpc.ts b/e2e/rpc.ts index def6f37b8..63609def1 100644 --- a/e2e/rpc.ts +++ b/e2e/rpc.ts @@ -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 `. */ +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( @@ -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(), diff --git a/package.json b/package.json index 7ff777feb..30e5de7fb 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/scripts/upgrade-checks/client.ts b/scripts/upgrade-checks/client.ts new file mode 100644 index 000000000..d0a799dd0 --- /dev/null +++ b/scripts/upgrade-checks/client.ts @@ -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['client'] diff --git a/scripts/upgrade-checks/run.ts b/scripts/upgrade-checks/run.ts new file mode 100644 index 000000000..979816cf6 --- /dev/null +++ b/scripts/upgrade-checks/run.ts @@ -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 ] + * + * - `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 = { t14 } + +const chains: Record = { testnet: tempoModerato, mainnet: tempo } + +/** AlphaUSD on testnet, which the faucet sends. pathUSD on mainnet. */ +const defaultTokens: Record = { + 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 { + 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 | undefined + try { + return await Promise.race([ + item.run(ctx), + new Promise((_, 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 = { 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) +} diff --git a/scripts/upgrade-checks/t14.ts b/scripts/upgrade-checks/t14.ts new file mode 100644 index 000000000..544a97893 --- /dev/null +++ b/scripts/upgrade-checks/t14.ts @@ -0,0 +1,630 @@ +/** + * T14 feature checks: configurable accounts (TIP-1107, TIP-1113), configurable access keys + * (TIP-1111), and admin access key removal (TIP-1137). Each case follows the Accounts docs and + * demos, such as `src/components/guides/account-sandbox-testnet.ts`. + */ +import { + type Address, + erc20Abi, + formatUnits, + type Hex, + isAddressEqual, + keccak256, + parseUnits, + toHex, + zeroHash, +} from 'viem' +import { generatePrivateKey, privateKeyToAddress } from 'viem/accounts' +import { Abis, Account, AccountConfig, Actions, Addresses, Expiry, P256 } from 'viem/tempo' +import type { Client } from './client' +import type { Case, CaseOutcome, Context, Tx, Upgrade } from './types' + +type RootAccount = ReturnType +type AccessKeyAccount = ReturnType + +/** A configurable account and the keys of its signers, as an app would keep them. */ +type Team = { + address: Address + config: AccountConfig.Config + keys: Record +} + +const usd = (value: string) => parseUnits(value, 6) +const newKey = () => Account.fromSecp256k1(generatePrivateKey()) +const randomAddress = () => privateKeyToAddress(generatePrivateKey()) +const tx = (label: string, hash: Hex): Tx => ({ label, hash }) +const pass = (detail: string, txs?: Tx[]): CaseOutcome => ({ status: 'pass', detail, txs }) +const fail = (detail: string, txs?: Tx[]): CaseOutcome => ({ status: 'fail', detail, txs }) + +/** Rebuild the account from its saved configuration with `approvers` attached, as the docs' `openAccount` does. */ +function open(team: Team, approvers: readonly RootAccount[]) { + const { config } = team + const owners = config.owners.map(({ owner, weight }) => ({ + owner: approvers.find((key) => isAddressEqual(key.address, owner)) ?? owner, + weight, + })) + if (config.version === 0n) + return Account.fromConfig({ + address: 'infer', + owners, + salt: config.salt, + threshold: config.threshold, + }) + return Account.fromConfig({ + address: team.address, + owners, + salt: config.salt, + threshold: config.threshold, + version: config.version, + }) +} + +/** Errors that mean the check couldn't reach the chain, not that the chain rejected it. */ +const transportError = + /fetch failed|HTTP request failed|timed? ?out|ECONNRESET|socket hang up|429|rate limit/i + +/** Precompile errors Viem reports only by selector. */ +const errorSelectors: Record = { + '0xaa4bc69a': 'UnknownFunctionSelector', +} + +/** Wrapper messages that say a call failed without saying why. */ +const genericError = + /^(Missing or invalid parameters|Invalid parameters were provided|Transaction creation failed|An internal error|RPC Request failed|Execution reverted for an unknown reason|Encoded error signature|The contract function "\w+" reverted\.|execution reverted$)/i + +/** The messages along an error's cause chain, outermost first. */ +function errorParts(error: unknown) { + const parts: string[] = [] + const seen = new Set() + let cause = error + while (cause instanceof Error && !seen.has(cause)) { + seen.add(cause) + const { shortMessage, details } = cause as Error & { shortMessage?: string; details?: string } + for (const part of [shortMessage, details]) + if (part && !parts.includes(part)) parts.push(part.replace(/\s+/g, ' ')) + cause = cause.cause + } + if (parts.length === 0) parts.push(String(error)) + return parts +} + +function errorText(error: unknown) { + return errorParts(error).join(' · ') +} + +/** The most specific reason for a rejection, for a report. */ +function reason(error: unknown) { + const parts = errorParts(error) + const text = parts.join(' · ') + const selector = Object.keys(errorSelectors).find((item) => text.includes(item)) + if (selector) return `${errorSelectors[selector]} (${selector})` + // A node's error details name the rule, such as "multisig signature weight below threshold". + const specific = parts.find((part) => !genericError.test(part)) + return (specific ?? parts[0] ?? '').slice(0, 240) +} + +/** + * Runs `send` and reports whether Tempo rejected it. A transport failure rethrows, so it fails the + * case instead of counting as a rejection. With `pattern`, only a matching rejection counts. + */ +async function rejection(send: () => Promise, pattern?: RegExp) { + try { + const value = await send() + return { rejected: false as const, value } + } catch (error) { + const text = errorText(error) + if (process.env.UPGRADE_CHECKS_DEBUG) console.log(` rejected: ${text}`) + if (transportError.test(text) && !pattern?.test(text)) throw error + return { rejected: true as const, matched: pattern ? pattern.test(text) : true, text, error } + } +} + +async function commitmentOf(client: Client, account: Address) { + return (await client.accounts.getConfigCommitment({ account })).toLowerCase() +} + +/** The balance in base units. */ +async function balanceOf(ctx: Context, account: Address) { + return ctx.client.readContract({ + address: ctx.token, + abi: erc20Abi, + functionName: 'balanceOf', + args: [account], + }) +} + +/** + * Prepares a 0.01 payment from the account with no keys attached, so signers can approve it on + * separate devices ([Signing Thresholds](/docs/accounts/policies/signing-thresholds)). + */ +async function prepareTransfer(ctx: Context, team: Team, recipient: Address) { + // Viem's types don't accept `calls` with a configurable account here, though the request works. + const request = await ctx.client.prepareTransactionRequest({ + account: open(team, []), + calls: [Actions.token.transfer.call({ amount: usd('0.01'), to: recipient, token: ctx.token })], + } as never) + return request as Record +} + +/** Funds an address and returns the funding transaction for the report. */ +async function funded(ctx: Context, address: Address, txs: Tx[]) { + const funding = await ctx.fund(address) + if (funding) txs.push(funding) + if ((await balanceOf(ctx, address)) === 0n) throw new Error(`Funding left ${address} empty.`) +} + +const cases: Case[] = [ + { + id: 'chain-head', + name: 'Chain head is past activation', + area: 'network', + needsFunds: false, + async run(ctx) { + const [chainId, block] = await Promise.all([ctx.client.getChainId(), ctx.client.getBlock()]) + if (chainId !== ctx.chain.id) + return fail(`RPC answers chain ${chainId}, not ${ctx.chain.id}.`) + const seconds = Number(block.timestamp) - ctx.activation + const when = `Block ${block.number} at ${new Date(Number(block.timestamp) * 1000).toISOString()}` + const offset = `${Math.round(Math.abs(seconds) / 60)} min ${seconds >= 0 ? 'after' : 'before'} activation (${ctx.activation})` + if (ctx.mode === 'post') + return seconds >= 0 + ? pass(`${when}, ${offset}.`) + : fail(`${when} is ${offset}. Run post checks after activation.`) + return seconds < 0 + ? pass(`${when}, ${offset}.`) + : fail(`${when} is ${offset}. Pre checks expect a chain before activation.`) + }, + }, + { + id: 'precompiles', + name: 'Account precompiles answer', + area: 'configurable accounts', + needsFunds: false, + async run(ctx) { + const targets = { + configurableAccount: Addresses.configurableAccount, + signatureVerifier: Addresses.signatureVerifier, + accountKeychain: Addresses.accountKeychain, + } + const codes = await Promise.all( + (Object.entries(targets) as [string, Address][]).map(async ([name, address]) => { + const code = await ctx.client.getCode({ address }) + return [name, Boolean(code && code !== '0x')] as const + }), + ) + const detail = codes + .map(([name, has]) => `${name} ${has ? 'has code' : 'no code'}`) + .join(', ') + // The configurable account precompile answers getConfigCommitment only once T14 is active. + const call = await rejection(() => + ctx.client.readContract({ + address: Addresses.configurableAccount, + abi: Abis.configurableAccount, + functionName: 'getConfigCommitment', + args: [randomAddress()], + }), + ) + const answers = !call.rejected && call.value === zeroHash + const summary = `${detail}. getConfigCommitment ${answers ? 'answers' : `doesn't answer (${call.rejected ? reason(call.error) : String(call.value)})`}.` + if (ctx.mode === 'post') return answers ? pass(summary) : fail(summary) + return answers ? fail(`${summary} Expected no answer before activation.`) : pass(summary) + }, + }, + { + id: 'verify-signature', + name: 'Signature verifier checks a 2-of-3 approval', + area: 'configurable accounts', + needsFunds: false, + async run(ctx) { + // An account that hasn't sent a transaction yet verifies against its first signers. + const [a, b, c] = [newKey(), newKey(), newKey()] + const account = Account.fromConfig({ + address: 'infer', + owners: [ + { owner: a, weight: 1 }, + { owner: b, weight: 1 }, + { owner: c.address, weight: 1 }, + ], + threshold: 2, + }) + const hash = keccak256(toHex(`tempo upgrade checks ${Date.now()}`)) + const signature = await account.sign({ hash }) + const verify = (address: Address) => + rejection(() => ctx.client.accounts.verifyHash({ account: address, hash, signature })) + const own = await verify(account.address) + if (ctx.mode === 'pre') + return own.rejected + ? pass(`verifyConfigurableAccount is unavailable: ${reason(own.error)}`) + : fail(`verifyConfigurableAccount answered ${own.value} before activation.`) + if (own.rejected) return fail(`verifyConfigurableAccount reverted: ${reason(own.error)}`) + if (own.value !== true) + return fail('verifyConfigurableAccount returned false for its own signers.') + const other = await verify( + Account.fromConfig({ address: 'infer', owners: [newKey()], threshold: 1 }).address, + ) + if (!other.rejected && other.value === true) + return fail('verifyConfigurableAccount accepted the approval for another account.') + return pass( + `Returns true for ${account.address} (2 of 3 approvals) and ${other.rejected ? 'reverts' : 'false'} for another account.`, + ) + }, + }, + { + id: 'create-2of3', + name: 'Create and register a 2-of-3 configurable account', + area: 'configurable accounts', + needsFunds: true, + async run(ctx) { + const [a, b, c] = [newKey(), newKey(), newKey()] + const initial = Account.fromConfig({ + address: 'infer', + owners: [a, b, c].map((key) => ({ owner: key.address, weight: 1 })), + threshold: 2, + }) + const team: Team = { address: initial.address, config: initial.config, keys: { a, b, c } } + const txs: Tx[] = [] + await funded(ctx, team.address, txs) + const recipient = randomAddress() + // The first transaction registers the account. Signers A and B approve it. + const send = await rejection(() => + ctx.client.token.transferSync({ + account: open(team, [a, b]), + amount: usd('0.01'), + to: recipient, + token: ctx.token, + }), + ) + if (ctx.mode === 'pre') + return send.rejected + ? pass( + `Tempo rejected the configurable account's first transaction: ${reason(send.error)}`, + txs, + ) + : fail('A configurable account transaction succeeded before activation.', [ + ...txs, + tx('Payment', send.value.receipt.transactionHash), + ]) + if (send.rejected) return fail(`First payment failed: ${reason(send.error)}`, txs) + txs.push(tx('Register and pay (A + B)', send.value.receipt.transactionHash)) + const commitment = await commitmentOf(ctx.client, team.address) + if (commitment !== AccountConfig.getCommitment(team.config).toLowerCase()) + return fail( + `Stored commitment ${commitment} doesn't match the account's configuration.`, + txs, + ) + ctx.state.set('team', team) + return pass( + `Registered ${team.address} (3 signers, threshold 2). Its commitment matches the configuration.`, + txs, + ) + }, + }, + { + id: 'approve-2-of-2', + name: 'Payment approved by 2 signers on separate devices succeeds', + area: 'configurable accounts', + needsFunds: true, + modes: ['post'], + dependsOn: ['create-2of3'], + async run(ctx) { + const team = ctx.state.get('team') as Team + const { b, c } = team.keys + const recipient = randomAddress() + // The app prepares the payment with no keys attached. B and C approve it separately. + const request = await prepareTransfer(ctx, team, recipient) + const approvals = [ + await ctx.client.signTransaction({ ...request, account: b } as never), + await ctx.client.signTransaction({ ...request, account: c } as never), + ] + const receipt = await ctx.client.sendTransactionSync({ + ...request, + signatures: approvals, + } as never) + const balance = await balanceOf(ctx, recipient) + if (balance !== usd('0.01')) return fail(`Recipient holds ${balance} base units, not 10000.`) + return pass('B and C approved on separate devices. The recipient got 0.01.', [ + tx('Payment (B + C)', receipt.transactionHash), + ]) + }, + }, + { + id: 'below-threshold', + name: 'One approval below the threshold is rejected', + area: 'configurable accounts', + needsFunds: true, + modes: ['post'], + dependsOn: ['create-2of3'], + async run(ctx) { + const team = ctx.state.get('team') as Team + const recipient = randomAddress() + const request = await prepareTransfer(ctx, team, recipient) + const approval = await ctx.client.signTransaction({ + ...request, + account: team.keys.a, + } as never) + const send = await rejection( + () => ctx.client.sendTransactionSync({ ...request, signatures: [approval] } as never), + // Testnet's RPC reports it as "invalid transaction signature"; the B + C case shows the same + // flow passes with enough approvals. + /below threshold|weight|invalid transaction signature/i, + ) + if (!send.rejected) + return fail('Tempo accepted a payment with 1 of 2 approvals.', [ + tx('Payment (A only)', (send.value as { transactionHash: Hex }).transactionHash), + ]) + if (!send.matched) return fail(`Rejected for another reason: ${reason(send.error)}`) + if ((await balanceOf(ctx, recipient)) !== 0n) return fail('The recipient received funds.') + return pass(`Tempo rejected 1 of 2 approvals: ${reason(send.error)}`) + }, + }, + { + id: 'replace-signer', + name: 'Replace a signer at the same address', + area: 'configurable accounts', + needsFunds: true, + modes: ['post'], + dependsOn: ['create-2of3'], + async run(ctx) { + const team = ctx.state.get('team') as Team + const { a, b, c } = team.keys + const d = newKey() + const nextConfig = { + owners: team.config.owners.map((entry) => + isAddressEqual(entry.owner, c.address) + ? { owner: d.address, weight: entry.weight } + : entry, + ), + threshold: team.config.threshold, + } + const receipt = await ctx.client.writeContractSync({ + account: open(team, [a, b]), + ...Actions.accounts.updateConfig.call({ currentConfig: team.config, nextConfig }), + throwOnReceiptRevert: true, + } as never) + const txs = [tx('Replace C with D (A + B)', receipt.transactionHash)] + const updated: Team = { + address: team.address, + config: AccountConfig.update(team.config, nextConfig), + keys: { a, b, d }, + } + const commitment = await commitmentOf(ctx.client, team.address) + if (commitment !== AccountConfig.getCommitment(updated.config).toLowerCase()) + return fail(`Stored commitment ${commitment} doesn't match the updated configuration.`, txs) + const pay = await ctx.client.token.transferSync({ + account: open(updated, [a, d]), + amount: usd('0.01'), + to: randomAddress(), + token: ctx.token, + }) + if (!isAddressEqual(pay.receipt.from, team.address)) + return fail(`The payment came from ${pay.receipt.from}, not the same address.`, txs) + txs.push(tx('Payment (A + new signer D)', pay.receipt.transactionHash)) + // The replaced signer, with the configuration from before the update, can't approve any more. + const stale = await rejection(() => + ctx.client.token.transferSync({ + account: open(team, [a, c]), + amount: usd('0.01'), + to: randomAddress(), + token: ctx.token, + }), + ) + if (!stale.rejected) { + txs.push(tx('Payment (A + removed C)', stale.value.receipt.transactionHash)) + return fail('The removed signer still approved a payment.', txs) + } + ctx.state.set('team', updated) + return pass( + `D replaced C at ${team.address} (version ${updated.config.version}). A + D paid. A + removed C was rejected: ${reason(stale.error)}`, + txs, + ) + }, + }, + { + id: 'upgrade-in-place', + name: 'Upgrade a single-key account in place', + area: 'account upgrade', + needsFunds: true, + async run(ctx) { + const original = newKey() + const backup = randomAddress() + const txs: Tx[] = [] + await funded(ctx, original.address, txs) + const owners = [ + { owner: original.address, weight: 1 }, + { owner: backup, weight: 1 }, + ] + // A Tempo transaction with a fee token: without one the upgrade reverts with PrimitiveRootRequired. + const receipt = await ctx.client.writeContractSync({ + account: original, + ...Actions.accounts.upgrade.call({ owners, threshold: 1 }), + feeToken: ctx.token, + throwOnReceiptRevert: true, + } as never) + txs.push(tx('upgradeAccount', receipt.transactionHash)) + const expected = AccountConfig.fromUpgrade(original.address, { owners, threshold: 1 }) + const commitment = await commitmentOf(ctx.client, original.address) + const direct = await rejection( + () => + ctx.client.token.transferSync({ + account: original, + amount: usd('0.01'), + to: randomAddress(), + token: ctx.token, + }), + /RootKeyRetired|root key retired|root key of 0x[0-9a-f]+ is retired/i, + ) + if (!direct.rejected) + txs.push(tx('Payment (original key)', direct.value.receipt.transactionHash)) + if (ctx.mode === 'pre') { + if (BigInt(commitment) !== 0n) + return fail('The upgrade recorded a configuration before activation.', txs) + if (direct.rejected) return fail(`The original key can't pay: ${reason(direct.error)}`, txs) + return pass( + 'The upgrade transaction left the account unchanged. The original key still pays.', + txs, + ) + } + if (commitment !== AccountConfig.getCommitment(expected).toLowerCase()) + return fail(`Stored commitment ${commitment} doesn't match the upgrade configuration.`, txs) + if (!direct.rejected) + return fail('The original key still signs directly after the upgrade.', txs) + if (!direct.matched) + return fail(`Original key rejected for another reason: ${reason(direct.error)}`, txs) + const upgraded = Account.fromConfig({ + address: original.address, + owners: [original, backup], + salt: expected.salt, + threshold: 1, + version: expected.version, + }) + const pay = await ctx.client.token.transferSync({ + account: upgraded, + amount: usd('0.01'), + to: randomAddress(), + token: ctx.token, + }) + txs.push(tx('Payment (as configurable account)', pay.receipt.transactionHash)) + return pass( + `${original.address} upgraded in place. The original key alone was rejected (${reason(direct.error)}). The same key approving as a signer paid.`, + txs, + ) + }, + }, + { + id: 'access-key-within-limit', + name: 'Authorize a scoped access key and spend within its limit', + area: 'access keys', + needsFunds: true, + modes: ['post'], + dependsOn: ['replace-signer'], + async run(ctx) { + const team = ctx.state.get('team') as Team + const account = open(team, [team.keys.a, team.keys.b]) + const accessKey = Account.fromP256(P256.randomPrivateKey(), { access: account }) + const recipient = randomAddress() + // The configurable account's signers authorize the key. Its first payment carries the authorization. + const keyAuthorization = await ctx.client.accessKey.signAuthorization({ + account, + accessKey, + expiry: Expiry.hours(1), + limits: [{ token: ctx.token, limit: usd('0.05'), period: 0 }], + scopes: [ + { address: ctx.token, recipients: [recipient], selector: 'transfer(address,uint256)' }, + ], + } as never) + const { receipt } = await ctx.client.token.transferSync({ + account: accessKey, + amount: usd('0.02'), + keyAuthorization, + to: recipient, + token: ctx.token, + } as never) + const txs = [tx('Authorize key and pay 0.02', receipt.transactionHash)] + const { remaining } = await ctx.client.accessKey.getRemainingLimit({ + account: team.address, + accessKey, + token: ctx.token, + }) + // The key pays its network fee in the same stablecoin, which also counts against the limit. + const fee = usd('0.03') - remaining + if (fee < 0n || fee > usd('0.01')) + return fail(`Remaining limit is ${remaining} base units, expected 0.03 less the fee.`, txs) + if ((await balanceOf(ctx, recipient)) !== usd('0.02')) + return fail('The recipient did not receive 0.02.', txs) + ctx.state.set('accessKey', { accessKey, recipient, remaining }) + return pass( + `The key paid 0.02 of its 0.05 limit to its allowed recipient. ${formatUnits(remaining, 6)} remains after its ${formatUnits(fee, 6)} fee.`, + txs, + ) + }, + }, + { + id: 'access-key-over-limit', + name: 'Access key spend above its limit is rejected', + area: 'access keys', + needsFunds: true, + modes: ['post'], + dependsOn: ['access-key-within-limit'], + async run(ctx) { + const team = ctx.state.get('team') as Team + const { + accessKey, + recipient, + remaining: before, + } = ctx.state.get('accessKey') as { + accessKey: AccessKeyAccount + recipient: Address + remaining: bigint + } + const send = await rejection( + () => + ctx.client.token.transferSync({ + account: accessKey, + amount: usd('0.04'), + to: recipient, + token: ctx.token, + }), + /SpendingLimitExceeded|spending limit/i, + ) + if (!send.rejected) + return fail(`The key spent 0.04 with ${formatUnits(before, 6)} left.`, [ + tx('Payment over limit', send.value.receipt.transactionHash), + ]) + if (!send.matched) return fail(`Rejected for another reason: ${reason(send.error)}`) + const { remaining } = await ctx.client.accessKey.getRemainingLimit({ + account: team.address, + accessKey, + token: ctx.token, + }) + if (remaining !== before) + return fail(`Remaining limit changed from ${before} to ${remaining}.`) + return pass(`Tempo rejected 0.04 with ${formatUnits(before, 6)} left: ${reason(send.error)}`) + }, + }, + { + id: 'admin-key-rejected', + name: 'New admin access key is rejected', + area: 'admin access keys', + needsFunds: true, + async run(ctx) { + const owner = newKey() + const keyId = randomAddress() + const txs: Tx[] = [] + await funded(ctx, owner.address, txs) + const send = await rejection(() => + ctx.client.writeContractSync({ + account: owner, + address: Addresses.accountKeychain, + abi: Abis.accountKeychain, + functionName: 'authorizeAdminKey', + args: [keyId, 0, zeroHash], + throwOnReceiptRevert: true, + } as never), + ) + if (!send.rejected) + txs.push(tx('authorizeAdminKey', (send.value as { transactionHash: Hex }).transactionHash)) + const isAdmin = await ctx.client.readContract({ + address: Addresses.accountKeychain, + abi: Abis.accountKeychain, + functionName: 'isAdminKey', + args: [owner.address, keyId], + }) + if (ctx.mode === 'pre') + return !send.rejected && isAdmin + ? pass('authorizeAdminKey still works before activation.', txs) + : fail( + `authorizeAdminKey failed before activation: ${send.rejected ? reason(send.error) : 'not recorded'}`, + txs, + ) + if (!send.rejected) return fail('Tempo accepted a new admin access key.', txs) + if (isAdmin) return fail('isAdminKey reports the key as an admin key.', txs) + return pass(`Tempo rejected authorizeAdminKey: ${reason(send.error)}`, txs) + }, + }, +] + +export const t14: Upgrade = { + name: 'T14', + activation: { testnet: 1_795_532_400, mainnet: 1_796_742_000 }, + cases, +} diff --git a/scripts/upgrade-checks/types.ts b/scripts/upgrade-checks/types.ts new file mode 100644 index 000000000..5c75d5e4f --- /dev/null +++ b/scripts/upgrade-checks/types.ts @@ -0,0 +1,51 @@ +import type { Address, Chain, Hex } from 'viem' +import type { Client } from './client' + +export type Network = 'testnet' | 'mainnet' +/** `pre` runs before activation and expects the new behavior to be rejected. `post` expects it to work. */ +export type Mode = 'pre' | 'post' +export type Status = 'pass' | 'fail' | 'blocked' + +export type { Client } + +/** A transaction a case sent, with the explorer link the runner adds. */ +export type Tx = { label: string; hash: Hex; url?: string } + +export type CaseOutcome = { status: Status; detail: string; txs?: Tx[] } + +export type Context = { + network: Network + mode: Mode + chain: Chain + client: Client + /** The stablecoin that pays fees and test payments. */ + token: Address + /** The upgrade's activation time on this network, in Unix seconds. */ + activation: number + /** Sends `address` enough of `token` for a few test payments and their fees. */ + fund(address: Address): Promise + /** Values one case leaves for the cases that depend on it. */ + state: Map + log(message: string): void +} + +export type Case = { + id: string + name: string + /** The feature the case covers, such as `configurable accounts` or `access keys`. */ + area: string + /** Whether the case sends transactions, so it needs a funded account. */ + needsFunds: boolean + /** Modes the case runs in. Defaults to both. */ + modes?: readonly Mode[] + /** Cases that must pass first, such as the one that registers the account this case uses. */ + dependsOn?: readonly string[] + run(ctx: Context): Promise +} + +export type Upgrade = { + name: string + /** Activation time per network, in Unix seconds. */ + activation: Record + cases: readonly Case[] +} diff --git a/tsconfig.node.json b/tsconfig.node.json index a3bbc21f4..b3190419e 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -21,5 +21,5 @@ "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true }, - "include": ["vite.config.ts", "vitest.config.ts"] + "include": ["vite.config.ts", "vitest.config.ts", "scripts/upgrade-checks"] }