Audience: Contributors writing or running tests.
Status: every layer below exists: the signing core's unit tests, each adapter's tests in its package, the network hook's integration tests, the deploy tests with hardhat-viem, hardhat-ethers and Ignition, the task tests, and the live tests on Sepolia with their transaction matrix.
Tests form a pyramid. The lower layers are fast and pure; the upper layers exercise real SDKs and real chains.
- Unit tests for pure crypto:
- Vectors for SPKI DER/PEM, JWK with stripped zeros, the wrong curve, and DER strictness.
- fast-check properties: high-S and low-S DER both normalise and recover to the address; parsing random bytes never succeeds silently; JWK and SPKI encodings convert back and forth without loss.
- CRC32C vectors.
- The vendored EIP-712 code checked against the package's
verifyTyped.
- Unit tests for the signer and adapters:
- Injected fake SDK clients sign with a local key and return the exact wire formats: AWS SPKI + DER; GCP PEM + DER + CRC (including corrupted CRCs); Azure JWK + r‖s.
- Assertions on request parameters:
MessageType: DIGEST, the ARN taken fromGetPublicKey,ES256Kwith the versioned id, the GCP call options. - A fake adapter that returns a signature from the wrong key, and an address-pin mismatch.
- The adapter's
signTransaction(packages/hardhat-kms/test/unit/signer/sign-transaction.test.ts,packages/hardhat-kms/test/unit/viem/sign-transaction-method.test.ts), with the fake inpackages/hardhat-kms/test/helpers/fake-tx-adapter.ts, which hashes the unsigned bytes it receives as a parsing service does. For types 0, 1, 2 and 4, through the RPC path and the library account, it gets the core's unsigned bytes, their digest, the type number and the chain id, neversignDigest, and the result equals Hardhat's and viem's bytes. A hostile one that signs another body (the same transaction withvalueraised by one), signs with another key, returns an out-of-ranger, or signs bytes it overwrote is refused after the fresh attempt, which also goes throughsignTransaction, and no nonce is noted; a high-S one is normalized; one that overwrites its copies after signing changes nothing. An adapter without the method signs the same transactions throughsignDigest. - An AbortSignal timeout, driven by an injected clock. The system timers' cancel is checked with Node's mock timers, so no test waits on the clock for it.
- The signer's debug lines (
packages/hardhat-kms/test/unit/signer/debug-log.test.ts): each provider call with its request id and duration, the derived address, the reason for asking for a fresh signature, the adapter method each signature goes to, and the cache's close. A logger readsDEBUGwhen it is created, so the test sets it before it imports the signer modules. The core's debug-log tests read their lines withtest/helpers/debug-lines.ts, which drops the time since the previous line that the logger adds at the end (+12ms, or+-13mswhen the clock steps back), so a test never compares it (#525). - The signer cache (
packages/hardhat-kms/test/unit/signer/key-cache.test.ts): one signer per key, copies of an AWS, Google Cloud or Azure key sharing one signer, a separate signer for keys that differ only in the key id,profile(also for an ARN),region,endpoint,address,timeoutMs,displayId, name, provider, Azure key or vault, and for two configuration variables that hold the same value, one variable name with a differentformatordefault, or a Google Cloud key whose parts differ in one part'sformat, one signer for copies of a variable with the sameformatanddefault, a variable'sdefaultabsent from the identifier's printed and serialized forms, per-object signers for third-party keys, no identifier read before the provider plugin's error, an unreadable identifier read once by the adapter and again on the next request, a signer created after the last connection closed still closed once by the idle timer, a shared signer kept open until the last connection closes and then closed once, failures not kept, an adapter closed when the signer refuses it, status messages sent to the display it was given, the idle close after the last connection and re-creation on next use, driven by injected timers.packages/hardhat-kms/test/integration/kms-hook-contract.test.tschecks that an adapter refused by the contract check is closed too. - Bounded GCP CRC retries, and the Azure managed identity timeout.
- The AWS adapter's tests are in
packages/hardhat-kms-aws/test/unit/adapter.test.ts, with the fake SDK inpackages/hardhat-kms-aws/test/helpers/fake-aws-kms.ts. - The Azure adapter's tests are in
packages/hardhat-kms-azure/test/unit/adapter.test.ts, with the fake SDK inpackages/hardhat-kms-azure/test/helpers/fake-key-vault.ts. They coverECandEC-HSMJWKs, coordinates without leading zeros, wrong key types and curves, disabled, expired and not-yet-valid keys, a lookup or sign response whosekidnames another vault, key or version, a signature of the wrong length, and the errors for 401, 403, 404 and a missing credential.packages/hardhat-kms-azure/test/unit/credential.test.tschecks the credential chain's order, the managed identity timeouts, the managed identity left out where it refuses a client id, and the token sharing, with a fake@azure/identity.packages/hardhat-kms-azure/test/integration/managed-identity-exit.test.tsruns the real chain in a child process with noazorazdonPATHandAZURE_POD_IDENTITY_AUTHORITY_HOSTpointing at a local endpoint that accepts connections and never answers, and fails unless the process exits on its own within 25 seconds.packages/hardhat-kms-azure/test/unit/history.test.tschecks thekms historyreader against a fake query call, withKeySignrows recorded from a real workspace and every id replaced (packages/hardhat-kms-azure/test/fixtures/log-analytics-rows.ts). It covers the mapping of each field; a refused request that Key Vault logs withResultTypeSuccessand HTTP 400; the principal of a user, a user with only an object id and an application, told apart byidtyporscp; a row whoseIdis empty; the exact KQL query; a range filter; truncation counted from the rows returned; the refusals for a missing or malformedkms.audit.azure.workspaceId, Managed HSM and other clouds; the answers for a missing table, 400, 401, 403, 404, 429, 5xx and a partial result; unreadable answers; credential and network errors; and the signal. For KQL injection, it builds the reader on hostile key ids (quotes, backslashes,|, newlines, percent-encoding, ports, user info, other hosts and paths) and checks that each fails before any query, and, for the key ids it accepts, that the query'sh"…"literals are exactly the checked host and key name and that the rest of the query is fixed. - The Google Cloud adapter's tests are in
packages/hardhat-kms-gcp/test/unit/adapter.test.ts, with the fake SDK inpackages/hardhat-kms-gcp/test/helpers/fake-gcp-kms.ts. Like Cloud KMS, the fake confirmsverifiedDigestCrc32conly when thedigestCrc32cit receives matches the digest. The tests corrupt or drop each ofpemCrc32c,verifiedDigestCrc32candsignatureCrc32c: two bad answers are retried and pass, a persistent fault fails after four attempts, and an aborted call stops retrying. They also cover a response for another key version, for a version that has the configured one as a prefix, or with an empty or noname(no retry), a digest refused with INVALID_ARGUMENT, UNAVAILABLE with and without a network cause (retried after a pause that an abort ends), a wrong algorithm, the gaxtimeoutwithretry: null, the client'sfallback: trueand itsgoogle-gax, and the message for each gRPC status, which never repeats the server's text.packages/hardhat-kms-gcp/test/unit/wire.test.tscovers theInt64Valueforms and status codes. Thekms historyreader's tests are inpackages/hardhat-kms-gcp/test/unit/history.test.ts, with masked Cloud Audit Logs entries recorded from a live project inpackages/hardhat-kms-gcp/test/fixtures/logging-entries.ts: the mapping of each field, the digest forms, the filter and its escaping, a project named by its number, paging, truncation, the scan budget on a fake clock, throttling, refused reads and the signal.packages/hardhat-kms-gcp/test/integration/history.test.tsrunskms historythrough the plugin, with the real google-auth-library call against a local Cloud Logging endpoint (test/helpers/logging-server.ts), and checks an abort before the request body is sent, which crashes the process unless the body stream has an error listener. Itssdk-loading.test.tsalso checks thatkms addresson a Google Cloud key loads neither the history reader nor its Cloud Logging call.
- Byte equivalence:
- A deterministic fake backend (RFC6979 with Hardhat's test key) must produce raw transactions and signatures byte-identical to Hardhat's
local-accounts.tsvectors: legacy, 2930, 1559, 7702, eth_sign, personal_sign, 712. - Differential checks against viem
signTransactionand ethersWallet.signTransaction. - The differential fill test described under Transaction filling, run against the Hardhat floor and
latest.pnpm run test:hardhat-versions(scripts/test-hardhat-versions.ts) runs two test files,transaction-filler.test.tsandnetwork-hook.test.ts, on the floor of thehardhatpeer range and on the newest 3.x release that is at least a day old (or older thanminimumReleaseAge, if the project sets one). The one-day hold is deliberate: pnpm's built-in default would install a younger release and add it tominimumReleaseAgeExclude, which this repository never does, so a younger release is held back and tested by the next weekly run. For each version the script sets thehardhatcatalog entry inpnpm-workspace.yaml, installs, checks that hardhat-kms resolves it, builds, typechecks and runs the tests, then restorespnpm-workspace.yamland the lockfile, also on Ctrl-C. A failure names the Hardhat version and the stage that failed (install, build, typecheck or tests); a failing fill test names the fill step. Thehardhat-versions.ymlworkflow runs it weekly, on demand, and on pull requests that change the paths listed in that workflow; it is not a required check. - The core's own Hardhat libraries at their floors.
pnpm run test:library-floors(scripts/test-library-floors.ts) reads the ranges of@nomicfoundation/hardhat-utils,hardhat-errorsandhardhat-zod-utilsin the core'spackage.json, with one floor per major (floorsOfinscripts/version-range.ts:^4.3.0 || ^5.0.0gives 4.3.0 and 5.0.0). The first run installs every library's first floor; each further floor gets its own run, with the other libraries at their first floor. A run adds the floors to the core only, as exact versions, so Hardhat and other plugins keep their own copies, as in a user's project. It checks that the core resolves each floor, builds, typechecks the core and its tests, and runs its unit and integration tests, the differential test included, then restores the core'spackage.jsonand the lockfile, also on Ctrl-C. Thelibrary-floorsjob ofsdk-floors.ymlruns it on the workflow's paths, which include the manifests and the lockfile but not the core's source, since nearly every core directory imports these libraries; the release gate requires every job of that workflow on the tagged commit, and dispatches it there when no run exists, so a source change that breaks a floor is caught before the release. If a floor fails, raise it in the same pull request to a version that passes;hardhat-zod-utilsstarts at 3.0.7: earlier releases have notypein the request schema thatkms sign-txand the filler read. A run adds the floors to the core only, so thehardhat-utilscopy thathardhat-zod-utilsandhardhat-errorsresolve comes from the lockfile; withhardhat-zod-utils3.0.7 that copy ishardhat-utils4, which reads"0x"as one zero byte, and the core decodes request data itself for that reason (#614).
- A deterministic fake backend (RFC6979 with Hardhat's test key) must produce raw transactions and signatures byte-identical to Hardhat's
- Integration tests on a real HRE with
edr-simulatedand a fake adapter registered through thekmshook:-
The network hook (
packages/hardhat-kms/test/integration/network-hook.test.ts), on anedr-simulatednetwork and an unreachable http network: account listing (own accounts first, pinned addresses without a KMS call, duplicates listed once, KMS addresses only when the downstream call fails);personal_sign,eth_signandeth_signTypedData_v4matching Hardhat's local-account vectors; pass-through for other addresses and methods; strict hex and malformed typed data refused before any KMS call; transactions from KMS accounts refused; adapter-creation errors reduced to the error class; two keys for the same account refused; thedefault-network warning printed once; networks without KMS keys left alone. -
Override connections (
packages/hardhat-kms/test/integration/override-connection.test.ts), with a fake AWS adapter that countsgetPublicKey: a plain connection and anoverride: { timeout }connection to one network get new key objects from Hardhat, sign with one adapter and onegetPublicKeycall; an override that changes the key'sprofilegets its own adapter; a key whose configuration variable is unset fails with the same error as creating its adapter directly, and works on the next request once the variable is set. -
Unknown accounts (
packages/hardhat-kms/test/integration/unknown-account.test.ts):eth_sendTransaction,personal_signandeth_signfrom an address that is neither a KMS account nor a local account fail with the KMS address appended, on anedr-simulatednetwork (ProviderError, -32000), on an http network with local accounts (Hardhat's HHE716, whoseformattedMessagecarries the list for the CLI), on an http network without them (the node's error answer, including Geth'sunknown account) and on a network whosefromis unknown. The error keeps its class, code and data, shows through viem and ethers, and names no key. A local account's errors, and errors not about the account, stay exactly as on a network without KMS keys. 10, 11 and 12 KMS accounts list all 10, then "and 1 more" and "and 2 more". A plugin listed before hardhat-kms throws a frozen error, partly writable errors and the same error twice: the error comes back as it came, or with the list once.packages/hardhat-kms/test/unit/rpc/unknown-account.test.tscovers which errors match, including Reth's and Anvil's -32602 answers, and the sentence itself. -
On-chain verification (
packages/hardhat-kms/test/integration/ecrecover.test.ts): the fixture projectpackages/hardhat-kms/test/fixture-projects/ecrecovercompilesRecover.sol, which recovers a signer withecrecoverand refuses high-S signatures, as OpenZeppelin's ECDSA does. Through@nomicfoundation/hardhat-viemand@nomicfoundation/hardhat-ethers, messages and typed data signed by a KMS account whose fake KMS returns only high-S signatures must recover to that account on chain, with one KMS signature per request, so a retry cannot hide a signature the plugin failed to normalize. Typed data for another chain is refused. -
An adapter with
signTransaction(packages/hardhat-kms/test/integration/sign-transaction-method.test.ts), on a Pragueedr-simulatednetwork:eth_sendTransactionof types 0, 1, 2 and 4, sends and deploys with hardhat-viem, hardhat-ethers and a library account, andkms sign-tx, all throughsignTransaction;personal_signthroughsignMessageand the library account's authorization throughsignDigest. An adapter that signs another body or with another key sends nothing through any of them: the block number and the nonce do not move, andkms sign-txprints nothing.packages/hardhat-kms/test/integration/kms-hook-contract.test.tsrefuses asignTransactionthat is not a function and an adapter whose only signing method issignTransaction. -
Deploys (
packages/hardhat-kms/test/integration/deploy.test.ts): the fixture projectpackages/hardhat-kms/test/fixture-projects/deploycompilesCounter.sol, whose constructor takes arguments and records the deployer as owner, and whoseaddonly the owner can call, so a successful call shows which account sent it. The project'signition/modules/Counter.tsdeploys it and callsadd. The KMS keys are not EDR's default accounts, so EDR cannot sign for them; one fake KMS returns only high-S DER signatures and another low-S compact ones, and each test checks the number of KMS signatures, one per transaction.kms.simulatedBalancefunds the KMS accounts. The tests cover:- hardhat-viem:
sendDeploymentTransactionanddeployContractwith a KMS wallet client, a write, the state read back, andfromon the receipts. - hardhat-ethers: the same through
ethers.getSigner(kmsAddress). - Ignition, through
@nomicfoundation/hardhat-ignition-viem:ignition.deploywith a KMSdefaultSenderon a network that also has local accounts; a module that picks the KMS account withm.getAccount(index)next to a contract from the local default sender; the first KMS account as default sender on a network withaccounts: []; and theignition deploytask withdefaultSender. - Local and KMS accounts on one network:
eth_accountsandethers.getSigners()list EDR's 20 accounts first, then the KMS accounts; one script deploys and writes from a local account and from a KMS account, and the local account cannot write to the KMS account's contract. --kms: a runtime created with{ kms: "aws", network }andAWS_KMS_KEY_IDset, a fake adapter for that key, the key funded bykms.simulatedBalance, and a deploy and write through viem from it.
- hardhat-viem:
-
Other signing plugins (
packages/hardhat-kms/test/integration/ledger.test.ts): hardhat-kms and hardhat-ledger in bothpluginsorders. The tests check the account lists, that the KMS account'spersonal_signandeth_sendTransactionare signed by hardhat-kms, that the Ledger account's requests reach hardhat-ledger's connect step without a device, and that a transaction withoutfromsucceeds only with hardhat-ledger listed first (Other signing plugins). -
hardhat-viem and hardhat-ethers flows: deploy, every transaction type, and
signMessage/signTypedDataverified on chain withecrecover. -
Sends (
packages/hardhat-kms/test/integration/send-lock.test.ts): 10 parallel sends from each of two KMS accounts on anedr-simulatednetwork, with aneth_signTransactionamong them, are all mined with nonces 0 to 9 per account, under a 60 s guard against a deadlock. Over HTTP to the recording node, whose pending count never moves, sends get consecutive nonces; a broadcast that times out under hardhat-viem reaches the node once and fails with -32000; a retried request after a broadcast without an answer sends the same bytes, without a new KMS signature, and returns the same hash; a node's refusal comes back unchanged. On a simulated network, a reverted send throws Hardhat'sSolidityErrorwith its revert data and transaction hash. A network hook that sends from the same KMS account during the fill gets the re-entrancy error at once, while a send from the other account works and the outer send is mined.packages/hardhat-kms/test/unit/rpc/send-guard.test.tscovers the three limits of the lock with a fake clock: the re-entrant send, also after anawaitand inside a timer; the 120 s wait without progress, and a queue whose holders take 100 s each that never trips it; and the 1025th waiter. Each case checks that no lock is left behind. It also covers the retry cache and the high-water mark (ConnectionSends); the sent records with the mark off after the pending count falls (#489: the falls it sees, each record looked up once per fall, a failed lookup kept as held, a gone record looked up again before its nonce is taken, a reservation that outlives the fall, every hash kept at a nonce, and the 256-hash bound); the nonce reservations of library accounts (clock expiry with no timer, the order in whichresetends them, with a failed one first, and close); library holds (the lock kept until the broadcast, the 60 s limit, owed resets, close, a failed nonce choice, and a secondendthat leaves a newer hold alone); the 5 s wait warning (at most once per hold and per waiting send, none behind a plugin send, under 5 s or after close) and the 60 s warning; and a test that keeps the order 5 s < 60 s < 120 s. With timers whose cancel does nothing, it checks that a waiter's limit firing after the waiter got the lock leaves the queue alone; with timers that throw, that the send fails and leaves no waiter in the queue; and that closing a send state ends its library holds at once. It checks the exact textcanonicalJsonwrites for each type, and that a replaced retry entry becomes the newest without dropping another. Each library hold test runs on its own chain id, so a test that fails with a hold still open fails the file at once instead of leaving the next test waiting.packages/hardhat-kms/test/unit/rpc/send-lock.test.tscovers the same rules through the network hook with a fake node and fake timers, as Transactions describes.packages/hardhat-kms/test/integration/nonce-fall.test.tsruns the falls of #489 on a real EDR node: afterhardhat_dropTransactionbelow a reservation, the next send takes the dropped nonce and the queued transaction above it stays; afterevm_revertto a snapshot that holds a queued transaction, no send takes its nonce; afterevm_revertwith an own-transport reservation that outlives it, plugin sends below the reservation are mined with no gap; and afterevm_revertrestores a transaction whose nonce a second send (after a drop) or a caller-nonce replacement took, no send takes that nonce. -
The nonce model (
packages/hardhat-kms/test/unit/rpc/nonce-model.test.ts): fast-check runs sequences of up to 10 steps over the fake node insend-harness.ts, with one account, two connections and bothhttpandedr-simulatednetworks. Steps cover plugin sends; library sends through either connection or with their own transport (consume, sign, broadcast, reset); accepted, refused and unanswered broadcasts; delayed KMS signatures; the 60 s hold limit; connection close;unansweredPair(an unanswered plugin send, then an unansweredreplace, as one step);replace(a send with the caller's nonce replaces the node's transaction unless the node refuses it, on both network types and with any node answer; when accepted, only while no library send holds a nonce, since an accepted caller nonce ends the reservations up to it); and, onedr-simulatedonly, the falls of #489:drop(a transaction leaves the node: below the pending count, the count falls and the ones above it stay; above it, a queued one goes) andsnapshotthenrevert(the node gets back exactly the transactions of the snapshot, a queued one included).replace,drop,snapshotandrevertare skipped while a request is in flight, since that send chose its nonce before. Invalid self-authorizations exercise #435's refusal after nonce selection. Every key's fake adapter hassignTransactionOutlivesAbort(#537), and two steps act on one KMS signature after its request was sent:outstandingSend(a plugin send) andlibrarySignOutstanding(a library send's sign, which alibraryResetmay follow). Each takes an outcome:senthangs until the key's 1 s timeout passes,failsthrows at once, as an activity that needs approval does, andrefusedthrows afterctx.requestRefused, which alone frees the nonce. Every signature that completes holds its nonce on its connection until a transaction with it is recorded there, at once after an answered broadcast, or when a lookup finds an unanswered one, since the fake adapters keep a copy, as Turnkey does.signOnly(connection, outcome?)sendseth_signTransaction, whose nonce is checked as a send's (it runs under the send lock). A copy the node accepted counts as recorded even when the node already had another transaction at that nonce, so theoutstandingkind concerns only copies that were never broadcast and accepted. Another transaction at a held nonce does not end the hold onedr-simulated: the plugin ends it only once the nonce is mined. The model's node has a mined count, which theminestep raises to the pending count, andlatestFailsmakes its read fail;droptakes only pool transactions, at or above the mined count, andrevertrestores the mined count of the snapshot. A hold below the mined count is no longer checked, since the plugin ends it at its next nonce choice; a revert can bring that nonce back, a known limit on local networks. Theoutstandingkind fails when a send on an open connection signs a nonce held there before a transaction with it was recorded on that connection.After each step, the model checks nonce ownership, reservations, hold limits and broadcasts after close. Once requests settle, it also checks that an open connection remembers acknowledged broadcasts despite a lagging HTTP pending count.
inspectUncertainconsumes a nonce through the public library account, with the same lag, and checks the chosen nonce and transaction-hash lookup on that connection. This consumes a modelled reservation; it does not inspect private send state. Its lag stops above the highest counted nonce the connection did not record, since the connection cannot know that one. Simulated networks retain their actual pending count. They record every send, and the nonce choice uses the records only while a reservation lives. After a fall, a nonce below a recorded one is the right choice, so only the recorded nonce itself is a violation. Thegap-489kind checks that, after a fall onedr-simulated, a plugin send signs no nonce above the lowest one at or above the pending count that the node lacks and that no library send was given, taking the highest such bound between the send's start and its broadcast. Their read-only probe waits until there is no library hold: a nonce read ignores a hold, whereas a send must wait for it. Closing intentionally clears a connection's records. Reservations on another connection and own-transport broadcasts are outside the connection's knowledge by design.Each property tries thirty-four fixed sequences before 200 random sequences with seed 445. The nightly run in
ci-all-os.ymluses 1000 sequences and a random seed (NONCE_MODEL_RUNS,NONCE_MODEL_SEED=random). To replay a failure, runNONCE_MODEL_SEED=<seed> NONCE_MODEL_PATH=<path> NONCE_MODEL_REPLAY_PATH=<replayPath> node --test --test-name-pattern='<property name>' test/unit/rpc/nonce-model.test.tsinpackages/hardhat-kms. OmitNONCE_MODEL_REPLAY_PATHfor a fixed example, whose counterexample prints an ordinary step array. Two additional fixed cases check that a library broadcast through a second connection is recorded on both connections, with and without an answer. The orderings fixed by #434 have separate violation kinds and fixed regression cases. The two falls from the QA of #488 (a dropped transaction below a reservation, and a revert to a snapshot that holds a queued transaction) a reservation that outlives a revert, and two reverts that restore a transaction whose nonce a later one took (after a queued drop, and after a caller-nonce replacement; the QA of #503) are fixed sequences too, checked for duplicates andgap-489. So are three for #506: an unanswered send, then an unanswered caller-nonce send at another nonce, then a send or aconsumewhile the node's pending count is below the first send's nonce (lagged, or stopped at a reservation's gap). Random sequences of single steps rarely reach that order, so the composite stepunansweredPair(no-answer mode, a plugin send, thenreplace) makes it reachable: without the fixed sequences, 3000 random runs find the bug at the code before #506. Seventeen fixed sequences for #537 put an outstanding signature before plugin sends andconsume(on a lagging HTTP node and past the gap onedr-simulated), behind a library hold and its limit, before a held or own-transport library send's reset, and before a replacement and a fall, with a failure that is not a timeout for a plugin send and a held library send, a refused send next to a held one,eth_signTransaction(thesignOnlystep) after held nonces, a broadcast the node refuses, two unanswered signatures at one nonce that the node drops, aneth_signTransactionwhile a send's signature is paused and two at once (both fail without the send lock), QA's seed 4242001 counterexample, where a copy the node accepted and then dropped no longer holds its nonce, a stand-in at a held nonce that the node drops, which leaves the nonce held, and one that is mined while the mined count read fails; each has its own test too, and each fails when the hold is removed. The close step checks that closing a connection ends its library hold; teardown advances all limits and checks that no request, hold or lock remains. -
Chain-id guards.
-
Config errors reported at the exact path.
-
Tasks (
packages/hardhat-kms/test/integration/tasks.test.ts), run withhre.tasks.getTask(["kms", <name>]).run(...)(kms signthrough its action with an injected terminal) against fakemyvaultadapters, with standard output captured:kms addressprints the EIP-55 address andkms public-keythe 65-byte0x04key, for a key inkms.keys, an inlinekmsAccountskey and a--kmskey. The tests also cover a pin that matches and one that does not (both addresses in the error), an unknown name (the known names, no key ids), no keys at all, a name that akms.keyskey and a--kmskey share, an address-only adapter with and without a pin, an adapter that reports no identity (the pin is printed with a note on standard error), a name that differs only in case, and adapter status messages, which must reach standard error and leave standard output with the result alone. Each run's adapters must be closed once, also after an error, and stay apart from the network hook's.kms signsignatures must equal Hardhat'spersonal_signand EIP-712 vectors or viem's signature with the same key, and recover to the key with viem. Its tests cover0xinput as bytes,--no-hash(exactly 32 bytes; the question, driven through an injected terminal, withy,yes,n, an empty line and closed input;--yeswith and withoutallowRawDigests; each refusal without a terminal, a--kmskey, and the digest of a known EIP-7702 authorization whose tuple recovers), typed data from a JSON string or a file, the chain check against--chain, the--networkconfig'schainId, the node'seth_chainIdor nothing, and a signer stubbed to return another key's signature, which must not be printed.kms sign-authhas its own file,packages/hardhat-kms/test/integration/tasks-sign-auth.test.ts. Its tuples must equal viem'ssignAuthorizationwith the same key, recover with viem'srecoverAuthorizationAddress, and pass Hardhat'srpcAuthorizationListschema. It covers each refused flag combination, chain 0 with and without--force, the nonce read from a node (withpending, plus one with--self-broadcast), a malformed node answer, the summary line and the no-code warning on standard error, and stubbed signers that return another key's or a high-S signature. On a Pragueedr-simulatednetwork, the printed tuple goes into aneth_sendTransactionfrom the same key, from another KMS key and from a Hardhat account, and the authority's code must become0xef0100followed by the delegate; without--self-broadcast, the same key's transaction must leave the code empty.packages/hardhat-kms/test/integration/tasks-cli.test.tsruns the same tasks through the Hardhat CLI with an adapter that holds an open timer until it is closed: the command must print its result and exit by itself within the helper's 100-second run limit, also when it fails on a pin mismatch after the adapter opened, and a status message must go to standard error. The project lives under the package's gitignored.tmp/, as for the--kmsCLI test. A new task adds its cases to both files.kms verifykeeps its runtime cases intasks-verify.test.ts: a match and a mismatch for a message, hex bytes, UTF-8 text and typed data inline or from a file;--addresswith no adapter opened;--keywith only an identity call and a closed adapter, an address-only adapter asked for the address, and an adapter with no identity checked against the pin with a note;vof 0, 1 and EIP-155 values; a high-S signature accepted with a note; and each malformed signature, message, address and typed-data input. Its CLI cases check exit code 0 on a match and 1 on a mismatch or invalid input, and a message after--.kms accountshas its own file,packages/hardhat-kms/test/integration/tasks-accounts.test.ts: the table and the JSON shape; a failing adapter, an unclaimed key and an unset configuration variable, each shown next to its key with a failed result; a pin mismatch with both addresses; an unchecked pin; masked key ids, and--show-idswith its warning; merging without--network, with analso:line and a pin line for every merged config entry, and none with it, where a repeated--kmskey gets a note; AWS rows with the same id told apart by region, profile or endpoint, the endpoint shown only with--show-ids; an unknown network; no keys; at most 8 KMS calls at once; and every adapter closed once. For--balances: refused without--networkbefore any key opens;kms.simulatedBalanceshown for each key of anedr-simulatednetwork, in the table in ether and in the JSON in wei; a node answer that is not a hex quantity, which fails only that row; a network that cannot be reached; and a connection that fails to open, which fails every row's balance and still checks the keys; and the connection the task opens for the balances closed once, in a passing and a failing run, with a close that throws leaving the result as it was. For--check-sign: one signature per key and no public key read beyond the listing's; the signed message,hardhat-kms check-signand 64 hex digits, new on each run; neither thernor thesthe adapter returned, nor any 130-hex-digit run, the size of a signature, on standard output, standard error or in the report; a key that refuses to sign, or signs with another key, failing only its row with a failed result; a pin that was not checked becoming a match once the key signs, and failing when the signature recovers to another address; and-in both columns for a key that failed first. The JSON gainsbalanceandsignCheckonly with their options, and keepsversion: 1. A failure whose message spans lines shows on one line under its row, and keeps its newlines in the JSON.tasks-cli.test.tschecks that the CLI exits 1 when a key fails, 0 with--jsonwhen every key works, 0 with--balances --check-signon a simulated network with no signature in the output, and 1 for--balanceswithout--network.packages/hardhat-kms/test/unit/tasks/account-checks.test.tschecks the message, the balance parser and the ether formatting.packages/hardhat-kms/test/unit/config/key-identity.test.tschecks that one AWS alias looked up with a different region, profile or endpoint, an alias and its ARN, two Google Cloud key versions, two Azure keys, and two providers with the same identifier all get different identities, and that an ARN ignores the lookup settings. ItslistBypassIdentitycases check the looser match of the--kmslist-bypass check (#589): one AWS key id or alias matches across regions, profiles, endpoints, case and ARN forms, but not a key id against an alias; one Azure key matches across case, a trailing slash and a missing version, but not two versions; Google Cloud and Turnkey keys compare askeyIdentitydoes. -
kms sign-tx(packages/hardhat-kms/test/integration/tasks-sign-tx.test.ts) runs over HTTP against the recording node (test/helpers/recording-node.ts). For legacy, EIP-2930, EIP-1559 with automatic fees, a contract creation and EIP-7702 with a pre-signed tuple, the task must print to standard output only the byteseth_signTransactionreturns for the same request on a network that has the key as a KMS account, and their keccak-256 hash to standard error. The same holds on a network without the key, withoutfrom, with atypethat matches the fields, with lowercase, uppercase and checksummed addresses, and with achainIdand anoncein the file, which are signed as given. A file withouttogets the contract-creation note on standard error. The node must never receiveeth_sendRawTransactionoreth_sendTransaction. The refusals must leave the KMS without a signature: no--network, achainIdor a network for another chain, afromthat is not the key (no node request either, and a--kmskey named by its variable, never by its id), the four ways to ask for a blob transaction, atypethe fields do not give or that is not supported, unknown fields with thegasanddatahints, a mixed-case address with a wrong checksum into,from, the access list or the authorization list (no key opened, no node request), a quantity that is not0xhex (no node request), and a file that is missing, not JSON or not one object. On a simulated network, the task's bytes equaleth_signTransaction's, and a new connection accepts the transaction. Each connection to a simulated network is a new chain, so that test cannot show that the task leaves the nonce alone; the recording-node tests, which see every request, show that nothing is sent. A last test pins the task's field list to the keys of Hardhat's runtime request schema, which hastypesince hardhat-zod-utils 3.0.7.tasks-cli.test.tsruns the task through the CLI on thedefaultnetwork, where standard output must hold only the raw transaction and standard error the hash, and without--network. -
hardhat runexits (covered for now by the AWS exit test in layer 5). Thekmstasks exit by themselves (tasks-cli.test.ts). -
A test that runs the Hardhat CLI in a child process calls
runHardhatfrompackages/hardhat-kms/test/helpers/hardhat-cli.ts, notspawnSync. The run does not block the test process, so a node in that process can answer it. Hardhat takes 3 s to start on an idle machine and over 40 s on a loaded one, so the helper times the startup apart from the work. A script that prints a READY line gets a startup limit until that line and a separate work limit after it, as inlibrary-send-cli.test.ts. A run with no such line, such as akmstask or a script copied from the docs, gets one limit of 100 s, under the 120 s per-test limit of Node 24 and later (see Test time limits). Runs started in parallel in one project must not build: concurrenthardhat runcalls race on Hardhat's compile cache, so pass--no-compileor run them one after another. The helper kills the child at a limit, at a stderr line the test names, or when the test's signal aborts. On Node 22,--test-timeoutlimits each test file, not each test, and ends a file that runs past it with SIGTERM; the helper's SIGTERM handler then kills the running children, andendWithTestProcessadds a child the test starts itself, such ashardhat node. Itsreportholds the reason, an exit-13 note when the code is 13, and stdout and stderr, for failure messages. -
A provider package's test imports the helper by relative path, as
packages/hardhat-kms-gcp/test/integration/credentials-cli.test.tsdoes with../../../hardhat-kms/test/helpers/hardhat-cli.ts. The import crosses into the core's TypeScript project, so the provider'stsconfig.jsonadds a reference to../hardhat-kmsbeside the one to../hardhat-kms/tsconfig.build.json, and changes two options:rewriteRelativeImportExtensions: false, because an import path into another project cannot be rewritten, and thenemitDeclarationOnly: true, becauseallowImportingTsExtensionsin the base config is only allowed when imports are rewritten or nothing but declarations is emitted (TS5096). Itstsconfig.build.jsonsets both back, so the publisheddist/src/does not change. The same pattern servestsconfig.live.json. The helper runs the core package's copy of Hardhat, which is the workspace catalog's version, the same one the providers get.test/scripts/hardhat-cli-spawns.test.tsparses every integration test and failspnpm testwhen one starts the CLI withspawnSync,execFileSyncorexecSync. -
Error messages never contain the injected fake secrets.
-
- Provider packages with their real SDK against a local endpoint:
packages/hardhat-kms-aws/test/integration/plugin.test.tsloads@hardhat-kms/awsin an HRE and signs through the real@aws-sdk/client-kms. The SDK talks to a local HTTP server that speaks the KMS JSON 1.1 protocol (packages/hardhat-kms-aws/test/helpers/kms-server.ts). The test checks theX-Amz-Targetof each request, thatSignuses the key ARN fromGetPublicKeywithMessageType: DIGEST, and the region in the SigV4 credential scope. It also checks that the handler passes keys of other providers on, and that listinghardhatKmsandhardhatKmsAwstogether works.packages/hardhat-kms-aws/test/integration/network.test.tsopens a connection withhre.network.createto a network whosekmsAccountskey points at the same local server. It checks thateth_accountslists the key's address, thatpersonal_signreturns the signature from Hardhat's own local-accounts tests, and that the server saw oneGetPublicKeyand oneSign. It also runspackages/hardhat-kms-aws/test/fixtures/sign-and-exit.tsin a child process, which signs without closing the connection, and fails unless the process exits by itself.packages/hardhat-kms-aws/test/integration/sdk-loading.test.tschecks that loading a config loads no AWS SDK module and no task action, thatkms address,kms public-keyandkms sign-txon another provider's key load no AWS SDK module (kms sign-txmust reach the key's adapter, so its file and--networkchecks passed), and that creating an AWS adapter does (see SDK loading). The Azure and Google Cloud packages'sdk-loading.test.tsmake the same task checks.packages/hardhat-kms-azure/test/integration/plugin.test.tsruns the real@azure/keyvault-keyswith a fakeHttpClient(packages/hardhat-kms-azure/test/helpers/key-vault-http.ts) that answers the Key Vault REST API in process, including its challenge-based authentication. Key Vault hosts must end in an Azure vault suffix, so the SDK cannot be pointed at a local server; the fakeHttpClientis the seam instead. The test checks the request paths, thatsignusesES256Kagainst the version pinned from the first read, and that the adapter reads thekidof the real response.network.test.tsruns Hardhat'spersonal_signandeth_signTransactionvectors through the network hook with a fake SDK, including high-S signatures and a signature of the wrong length, and runstest/fixtures/sign-and-exit.tswith the real SDK to check that the process exits by itself.sdk-loading.test.tschecks that no module under@azure/,@azure-rest/or@typespec/loads before an Azure key is used, thatkms historyon another provider's key loads none of them nor the history reader's modules, and thatkms historyon an Azure key loads the reader and@azure/core-rest-pipelinebut not@azure/keyvault-keys.history.test.tsrunskms historythrough the plugin with the real@azure/core-rest-pipelinequery and a fakeHttpClient(packages/hardhat-kms-azure/test/helpers/log-analytics-http.ts). It checks the request URL, the bearer token and its scope, the user agent,Prefer: wait=100and the query; masking without--show-idsand the ids with it; the table; truncation; the empty-history note; a 429 retried afterRetry-Afterand one that stays throttled; a refused read; a missing table; a missing or malformed workspace setting; another provider's key; the version check; and an abort during the query.packages/hardhat-kms-gcp/test/integration/does the same for Google Cloud, with the real@google-cloud/kmsover its REST transport. There is no Cloud KMS emulator, sopackages/hardhat-kms-gcp/test/helpers/kms-server.tsservesGetPublicKeyandAsymmetricSignover HTTP, checksdigestCrc32cas Cloud KMS does, and returns high-S signatures. The SDK reaches it throughkmsHandlers(version, sdk), registered at run time, with a client subclass that sets the endpoint and a throwaway service account whose self-signed tokens need no network. The tests check the request paths, the base64 digest and its checksum, a retried corruptedsignatureCrc32cand a retried refuseddigestCrc32c,could not reach Google Cloud KMS (ECONNREFUSED)without the host, that no request follows an abort, the--kms gcpkey's resource path, the messages for NOT_FOUND, FAILED_PRECONDITION and PERMISSION_DENIED, the key version state named from each form of Cloud KMS's FAILED_PRECONDITION message, a proxy's HTML or empty 4xx page reported by its HTTP status rather than as FAILED_PRECONDITION,personal_signandeth_signTransactionagainst Hardhat's vectors (so the high S is folded), a signature that is not strict DER, and thatpackages/hardhat-kms-gcp/test/fixtures/sign-and-exit.tsexits by itself.- These tests run the SDK version in
pnpm-lock.yaml.pnpm run test:sdk-floors(scripts/test-sdk-floors.ts) runs each provider package's tests again with the lowest version of each cloud SDK its range allows,google-gaxincluded: it reads the floor from the range inpackage.json(the version of its first caret;scripts/version-range.tslists the forms it accepts and rejects a range that allows another major), installs that exact version, checks the package resolves it, typechecks the package and its tests against it, and restorespackage.json,pnpm-workspace.yamland the lockfile afterwards, also on Ctrl-C. Thesdk-floors.ymlworkflow runs it when a provider package, a manifest, the lockfile,pnpm-workspace.yamlor the script changes; it is not a required check. It also tests the core's optionalviempeer dependency at the floor of its range: it installs that version as a workspace override, typechecks the core and its tests against it, and runs the library-account tests listed inPEER_FLOOR_TESTSin the script (the viem unit tests,get-account.test.ts,raw-send.test.tsandlibrary-send-cli.test.ts). Then, whether or not the floor tests passed, it installs viem 2.55.11, the release below the floor (PEER_BELOW_FLOOR), and runstest/floors/viem-below-floor.test.ts, which checks thatgetAccountrefuses it before any KMS call. If a floor fails, raise it in the same pull request to a version that passes. The changeset states the new floor; the reason goes in the pull request. - Out-of-range installs:
pnpm run test:peer-installs(scripts/test-peer-installs.ts) packs hardhat-kms and@hardhat-kms/awsand installs them into scratch projects with npm (with and without--legacy-peer-deps), pnpm, Yarn 1 and Yarn 4 (nodeLinker: node-modules, both through corepack). The cases are viem 2.55.11, viem~2.54.0, hardhat-kms one patch release ahead of the provider package, a control with everything in range, and an existing project with only hardhat and viem, viem^2.47.6(the range Hardhat's viem template uses) and 2.52.2 in its lockfile, to which the add command of each package manager adds the plugin packages. For that last case the script rewrites the viem specifier inpackage.jsonand the lockfile; Yarn 4 resolves a hand-edited entry again, so for Yarn 4 it runsyarn set resolutioninstead. For each it records the install's exit code, the viem that hardhat-kms resolves and whatgetAccountreports, and compares them withEXPECTEDin the script; it fails when an install's exit code, the viem that hardhat-kms resolves or whatgetAccountreports changes, and does not check the warnings, which come from manual runs of the same installs. The AWS key points at a local HTTP server that answers with an error and the environment has fake AWS credentials, so nothing reaches a cloud; the control passes when that server gets theGetPublicKeyrequest. It also checks that pnpm withoutallowBuildsstops on the install scripts of esbuild and protobufjs. When it fails because a package manager changed, updateEXPECTED, the table in Library accounts and the causes ofcore.account.viem-too-oldandcore.provider.version-mismatch. Thepeer-installs.ymlworkflow runs it on Linux when the two checks, a published manifest, the rootpackage.json,pnpm-workspace.yamlor the script change, and monthly; it is not a required check. - Registry mode:
promote.ymlruns the same checks on what users install from npm.--from-registry <version>onscripts/check-packages.ts,scripts/consumer-typecheck.tsandscripts/test-peer-installs.tsreplaces the packed tarballs with each published package at that version,hardhat-kms@<version>,@hardhat-kms/aws@<version>and so on (scripts/registry.ts, from the list inscripts/release-packages.ts), skips the build and the pack, and fails after any install whose project resolves anotherhardhat-kmsversion.check-packages.tsdownloads each tarball withnpm pack, which checks it against the registry's integrity hash, and runs publint and attw on it.test-peer-installs.tsskipsprovider-mismatch, which needs a core repacked one patch ahead, and says so in its table.scripts/check-registry-release.ts <version>is the workflow's first registry check, after the live rule, for what no other script covers: the version is stable (no-), published for every package, at theirbetadist-tag and not belowlatest(equal is allowed: a first publish lands on both; a deprecated name placeholder onlatestpasses unless the package publishes a stable version above the one checked), the published core'sgitHeadis the commit of tagv<version>, andnpm audit signaturesin a scratch project with the packages installed verifies a provenance attestation for each. The examples test readsHARDHAT_KMS_EXAMPLES_VERSION: it copiesexamples/to a temporary directory with the exact version written into the two plugin dependencies (packages/hardhat-kms-aws/test/helpers/examples-copy.ts), runsnpm installin each copy, and runs the build, typecheck and deploy checks there with npm; the lint stays with the workspace run, which has the same sources.--registry <url>(HARDHAT_KMS_EXAMPLES_REGISTRYfor the examples) points every install at another registry.pnpm run test:registry-mode(test/scripts/registry-mode.test.ts, theRegistry mode (verdaccio)job ofregistry-mode.yml) exercises the mode without the public registry: it builds and packs the published packages, publishes them to a verdaccio started on a free port with a throwaway user (a first publish lands onlatestandbetaat once, as on npm), and runs each script and the examples test against it.test-peer-installs.tsruns there with npm and with Yarn 4. verdaccio records each version's publish time, so Yarn 4's age gate applies to the fresh publish: a project without thenpmPreapprovedPackagesline stops withYN0016, and the script's projects, which have it, install. verdaccio serves no signing keys, socheck-registry-release.tswith--registryruns the scratch install against it and skips onlynpm audit signatures, and ends with "passed the checks that run against" the registry rather than "ready to promote"; no tagv<version>exists for the workspace version, so that run stops at the tag check with its message. The promotion workflow does not pass--registry. Unit tests cover the guards, on recordednpm viewandnpm audit signaturesoutput (test/scripts/registry-release.test.ts), the option parsing, the installed-version check and the Yarn 4.yarnrc.yml, which in registry mode exempts the published packages from Yarn's age gate (test/scripts/registry.test.ts), and the copy (packages/hardhat-kms-aws/test/unit/examples-copy.test.ts).
- Emulated AWS:
packages/hardhat-kms-aws/test/localstack/aws-kms.test.tsstarts LocalStack4.14.0, pinned by digest and bound to a random port on 127.0.0.1, and runs the real@aws-sdk/client-kmsthrough the plugin against keys it creates. Each of 32 signatures must verify and recover to the key; about half come back high-S, and the test fails unless it saw both kinds. An alias moved to another key after the first lookup must keep signing with the first key, a key ARN without a configured region must work, and P-256 and symmetric keys are refused. Real KMS always echoes the key ARN and algorithm and never offers secp256k1 keys for encryption, so the checks on those response fields are covered by the unit tests only. Run it withpnpm run test:localstack, which needs Docker. In CI it runs on Ubuntu only, in thelocalstackjob.- The examples:
packages/hardhat-kms-aws/test/examples/examples.test.tsruns every project inexamples/against the same pinned LocalStack image. It creates oneECC_SECG_P256K1key and computes its address from the public key with@noble/curvesand@noble/hashes, independently of the plugin. It runs each example unchanged, through pnpm in the example's folder, withAWS_ENDPOINT_URL_KMS,AWS_REGIONand test credentials pointing the AWS SDK at LocalStack andAWS_KMS_KEY_IDnaming the key. For each example it runshardhat build,tsc -p .against the example's own stricttsconfig.json, oxlint withexamples/oxlint.json(the root rules, type-aware, withno-consoleoff), andpnpm run deploy --network rehearsal, anedr-simulatednetwork withaccounts: []whose only account is the KMS account, funded bykms.simulatedBalance. The deploy script printsDeployer:,Counter:,Owner:andCount:lines; the test requires the deployer and the contract'sowner()to be the key's address and the count read back to be 12. For each Ignition module under an example'signition/modules/, it also startshardhat nodeon port 8545, funds the key's address withhardhat_setBalance, runshardhat ignition deployon the built-inlocalhostnetwork with--kms awsand the key's address as--default-sender, and readsowner()andcount()back from the node witheth_call. A simulated network keeps no state once the task exits, which is why this step uses a node. Each example's deploy script also runs against ahardhat nodestarted with--chain-id 11155111, which manages Hardhat's 20 default accounts, as anvil or a fork does (#663): onlocalhost, which lists no KMS key, the script must fail withis not an account of the localhost networkand the node's block number must not move; onsepolia, withSEPOLIA_RPC_URLpointing at the node, the deployer and theowner()read back from the node must be the key's address, not the node's first account. A new example must print the same four lines, and pick its sender by the key's address. Run it withpnpm run test:examples, which needs Docker; in CI it runs in theexamplesjob. - The examples are pnpm workspace members. Their
package.jsonasks forhardhat-kmsand@hardhat-kms/awswith the caret range of the current version, as a project installing from npm would, andlinkWorkspacePackages: trueinpnpm-workspace.yamllinks those ranges to the workspace packages.changeset versionrewrites the ranges when it bumps the packages, so a copied example never containsworkspace:orcatalog:. The new ranges change the lockfile too, so version the packages withpnpm run version-packages, which runschangeset versionand thenpnpm install --lockfile-only --ignore-scripts; the version pull request then carries a lockfile thatpnpm install --frozen-lockfileaccepts. Each example also lists its other dependencies with plain version ranges.
- The examples:
- Live tests use real cloud keys. Today the AWS, Azure and Google Cloud smoke tests exist.
packages/hardhat-kms-gcp/test/live/gcp-kms.live.test.ts, run withpnpm run test:live:gcp, is skipped unlessHARDHAT_KMS_LIVE_GCP_KEYholds the full name of anEC_SIGN_SECP256K1_SHA256key version. It uses the developer's Application Default Credentials, creates nothing, redacts the project, key ring and key names from failures, signs 16 digests with the name and once with the components form, and checks that a missing version fails with a clear message.test:live:gcpalso runspackages/hardhat-kms-gcp/test/live/gcp-history.live.test.ts, which needs Data Access audit logs on for Cloud KMS in the key's project androles/logging.privateLogViewerfor the developer. It signs one random digest through the plugin, then runskms history --jsonevery 10 seconds, for up to 3 minutes, until anAsymmetricSignentry with that digest appears, and checks its version, itshardhat-kms/user agent, and that no key id reaches the output outside principals. A second test signs nothing and is skipped unlessHARDHAT_KMS_LIVE_GCP_PROJECT_NUMBERholds the key's project number (gcloud projects describe <project> --format='value(projectNumber)'). It reads the last 7 days of history with the key named by its project id and by its project number, and checks that both reads list the same entries. The Azure one,packages/hardhat-kms-azure/test/live/azure-key-vault.live.test.ts, run withpnpm run test:live:azure, is skipped unlessHARDHAT_KMS_LIVE_AZURE_KEY_IDholds the versioned URL of the current version of aP-256Kkey. It signs through the plugin's credential chain (az loginis enough), creates nothing, redacts the vault, key name and version from failures, and checks that the versioned id, the unversioned id and the components give the same key, and that a version that does not exist fails with 404. The AWS one:packages/hardhat-kms-aws/test/live/aws-kms.live.test.ts, run withpnpm run test:live:aws, is skipped unlessHARDHAT_KMS_LIVE_AWS_KEY_IDnames anECC_SECG_P256K1key with an alias. It uses the developer's own credentials and region, creates nothing, redacts the key id, ARNs and account ids from every failure it reports, and signs through the plugin with the key id, an alias of the key, and the key ARN withAWS_REGIONset to another region, where the bare key id must fail withNotFoundException. Beyond the guide's policy, the identity needskms:DescribeKeyon the key andkms:ListAliases, which only accepts the resource*.packages/hardhat-kms-aws/test/live/history.live.test.ts, in the same script, also needsHARDHAT_KMS_LIVE_AWS_HISTORY=1, because it waits up to 15 minutes for CloudTrail, andcloudtrail:LookupEvents. It signs once through the plugin and once with the AWS SDK and the alias, then pollskms history --jsonfor the bare key id every 30 seconds until both events appear: one with thehardhat-kms/user agent, and one whoserequestIdis the SDK's$metadata.requestId. It prints only how long that took.packages/hardhat-kms-azure/test/live/history.live.test.ts, intest:live:azure, also needsHARDHAT_KMS_LIVE_AZURE_WORKSPACE_ID, the workspace that the vault's diagnostic setting sends audit events to, and read access to it. It signs once through the plugin and once with the Key Vault SDK, keeping that call'sx-ms-request-id, then pollskms history --jsonevery 30 seconds, up to 12 minutes, until bothKeySignrows appear: one with thehardhat-kms/user agent, and one whoserequestIdis thatx-ms-request-id. No row'srequestIdmay be the client'sx-ms-client-request-id. The first run (#100) used an administrator identity and the default key policy; checking the guide's least-privilege policy against real KMS is part of #43. The live suite below also runs in GitHub Actions, signed in over OIDC: see Live tests in GitHub Actions. The Turnkey smoke test,packages/hardhat-kms-turnkey/test/live/turnkey.live.test.ts, run withpnpm run test:live:turnkey, has its own section: Turnkey smoke test.-
The live suite:
test/live/sepolia.live.test.tsat the repository root, run withpnpm run test:live, reads the same three key variables and runs once for each provider whose variable is set. It runs on a local fork of Sepolia by default, or on Sepolia itself withHARDHAT_KMS_LIVE_NETWORK=sepolia; the two modes are described after the list of checks. Providers without one are reported as skipped. A developer runs it locally with their ownaws,gcloudandazlogins, or a maintainer runs it in GitHub Actions; it creates no cloud resources and nothing is stored in the repository. The configured providers run in parallel, each with its own network connection, so the plugin's send lock orders each account's sends. Through hardhat-viem on an http network whosekmsAccountsholds the key, it runs the cases of the transaction matrix in order: it buildstest/live/fixture-projectand deploysLiveCheck.sol, then sends transfers, deploys, calls with value, reverts, replacements and EIP-7702 delegations across the transaction types, and checks apersonal_sign, aneth_signand aneth_signTypedData_v4signature on chain. Only the deployer can callLiveCheck.add, so each write that succeeds came from the KMS account. The checks each case makes:- Transfers of 1 wei to a fresh random address: its balance at the receipt's block must grow by 1. Self-sends of 1 wei must be mined.
- A 3-byte contract (
PUSH0 PUSH0 RETURN) deployed as a legacy and as an EIP-2930 transaction: the receipt'scontractAddressmust hold exactly that code. add(1)with 1 wei, which is payable, as a legacy transaction whosevmust carry chain id 11155111 (EIP-155), as an EIP-2930 transaction whose access list names thecountslot, and as an EIP-1559 transaction. The count andLiveCheck's balance must each grow by 1.- Reverts: 4 bytes of an unknown selector to
LiveCheck, which has no fallback, with an explicit gas limit, since an estimate would fail. The receipt must have status 0. The next transaction whose nonce the plugin fills must carry the account's transaction count at the revert's block; the test reads that nonce from the node before waiting for the receipt, so a wrong one fails with both numbers instead of a timeout. On Sepolia that transaction is the legacyadd(1), and a run in which no such check happened fails. - EIP-7702: the account sends a transaction to itself with an explicit nonce, carrying an authorization that delegates it to
LiveCheckwith that nonce + 1, and callingadd(1)with 1 wei on itself, which runs only if the delegation took effect. The account's code must then be the delegation designator forLiveCheck. The transactions go through viem'ssendTransactionwithauthorizationList. The test signs the account's authorizations through the public library account,connection.kms.getAccount(address).signAuthorization, on the provider's connection. Each one names chain id 11155111; the suite never signs an authorization for chain 0, which would be valid on every chain. - Sponsoring another key: the account sends 1 wei to the fresh address carrying an authorization from a throwaway key, generated in memory for the run and never printed. The throwaway's code must become the designator for
LiveCheck. A second transaction from the account carries the throwaway's authorization of the zero address, and the throwaway must end with no code. The throwaway holds no ETH; the account pays for both. - Signatures:
LiveCheckrebuilds the EIP-191 digest forpersonal_signand foreth_sign, which in Hardhat signs the same digest, and the EIP-712 digest, the typed data's domain withblock.chainidand the contract's address, and recovers the signer withecrecover, refusing high-S signatures. - The last case clears the delegation, also after a failure and also when an earlier run left one: an EIP-7702 transaction from the account to itself with 1 wei, whose authorization names the zero address with the transaction's nonce + 1. The account must then have no code. Slot 0 of the account's storage keeps the count the delegated
addwrote; clearing the delegation does not reset storage.
Each transaction's
valueis read back from the node and must equal what the case sent: 1 wei for the transfers, self-sends, calls, the type 4 call, the sponsored transfer and the clear, and 0 for the others. After the last case, every cell the mode runs must have a receipt from its case with the case's status, sender and type, and each signature its own check (missingCellsintest/live/matrix.ts); a missing one fails the run.If clearing a delegation fails, for example because a transaction stuck under a rising base fee holds the nonce, the failure says which account may still be delegated and how to clear it with
kms sign-auth --self-broadcast. The throwaway key cannot be cleared afterwards, since it existed only in memory; it holds no ETH, and only the KMS account can calladdon it.Two modes, chosen by
HARDHAT_KMS_LIVE_NETWORK(test/live/helpers/mode.ts; any value other thanforkorsepoliafails the run at load):- Fork mode, the default (unset or
fork). Needs anvil, found onPATHor in~/.foundry/bin. The suite startsanvil --fork-url <proxy> --hardfork prague --no-storage-cachingon a free port on 127.0.0.1 (test/live/helpers/anvil.ts) and points every provider's http network at it. Before signing anything, each test checks thatweb3_clientVersionstarts withanvil/and gives its account 10 ETH withanvil_setBalance. Fork mode runs the live cases and the fork-only cases of the matrix. Only anvil accepts that method, so the run cannot fund or send on a node that is not the fork. The live cases make the same checks as on Sepolia, with the same KMS keys, the same plugin path over http, Sepolia's chain id and each account's real nonce, and the run costs nothing. It proves that each key signs every transaction type, that the EIP-7702 delegation and clear work under the Prague rules, and that the pinned reads and the retry still work against a node that never lags. The 20 gwei cap is not applied, since the fork's ETH is minted. A receipt is awaited for 60 seconds, not 300. If a transaction is still pending after 15 seconds, the test mines one block withevm_mineand says so in a diagnostic: once, under three providers sending at the same time, anvil left a valid transaction pending with no later send to trigger a block. A transaction that is not valid stays out of that block and still fails the test. - Sepolia mode (
HARDHAT_KMS_LIVE_NETWORK=sepolia). The same checks on the public network, spending real Sepolia ETH. It proves what a single local node cannot: that real nodes accept and mine what the plugin sends. Run it before a release and after any change to signing or sending. The live runs so far caught a legacy transaction priced under a rising base fee and a stale read from a load-balanced RPC; a fork, with one node and its own blocks, reproduces neither. Some bugs also show only on a real client: geth refuses an authorization whoserorsis sent as 32 bytes with a leading zero, while anvil and EDR accept both forms (#140, found by reading geth'shexutil.U256decoding, not by a live run). It runs only the live cases. Only this mode writestest/live/proof.json, and only when every configured provider passed;pnpm run docs:live-proof(test/live/render-proof.ts) renders Live proof from it.
No transaction from a fork run reaches Sepolia. Anvil never sends a transaction to its
--fork-url, and in this suite that URL is a local proxy (test/live/helpers/rpc-proxy.ts) in front of the Sepolia RPC, as a second line of defence. The proxy forwards only an allow-list of the reads that anvil's fork backend (crates/anvil/src/eth/backend/fork.rsin Foundry) can issue: state, block, transaction, receipt and log reads,eth_call,eth_estimateGas,eth_createAccessList,eth_simulateV1, and thetrace_*anddebug_*reads that take a hash or a block. Any other method is answered with an error and not forwarded, includingeth_sendRawTransaction,eth_callBundle,mev_simBundle,trace_rawTransaction,personal_sendTransactionandwallet_sendCalls. It also refuses a request that holds a hex string of 65 bytes or more, which is the size of a signature, and a body that is not JSON-RPC, including one with a key other thanjsonrpc,id,methodandparams, such asMethod, which Go's case-insensitive JSON decoding would read as the method. A batch with one refused request is refused whole. What it forwards is rebuilt from the parsed request, never the text received, so a duplicatemethodkey cannot reach the upstream. The last test of a fork run fails if the proxy refused anything, or if any KMS account's state was not read through it (eth_getAccountInfo,eth_getAccount,eth_getBalanceoreth_getTransactionCount), which shows the fork the suite sent through is the one behind the proxy. It prints the forwarded methods and how manyevm_minenudges the run needed. The proxy also records, for eacheth_feeHistoryit forwards, the upstream's HTTP status and either the JSON-RPC error code or the result's shape (array lengths and value types), and each forward whose upstream fetch failed, by its methods and the error's name and cause code. It keeps no value and no message from an answer, since a message can name the RPC URL. When a provider's fork case fails, the suite prints that record, so a fee read that went wrong upstream shows in the failure (#395). Anvil ends with the test process: on a normal exit and on SIGINT, SIGTERM or SIGHUP the suite kills it, so it cannot outlive the run with the fork's signed transactions; only a SIGKILL of the test process leaves it running.close()sends SIGTERM, then SIGKILL after 5 seconds. A fork run also prints no raw transaction or authorization: both carry Sepolia's chain id and the account's real nonce, so a copy could be broadcast on Sepolia. The suite reports only hashes, and the redaction below removes signed data from failures. A fork run writes no proof, since its hashes exist on no public chain.test/live/mode.test.tschecks the mode switch and the anvil lookup,test/live/rpc-proxy.test.tschecks the proxy against a fake upstream, andtest/live/anvil.test.tskills a parent process holding a stand-in for anvil and checks the stand-in dies too; all three run inpnpm test.Two package sources, chosen by
HARDHAT_KMS_LIVE_SOURCE(liveSourceintest/live/helpers/mode.ts; any value other thansourceorregistry:<exact version>fails the run at load, so a range such asregistry:^1.0.0or a tag such asregistry:latestis refused):-
Source, the default (unset or
source). The three live files import the provider plugins from the checkout'ssrc. -
Registry (
HARDHAT_KMS_LIVE_SOURCE=registry:<version>). Each live file copiestest/live/fixture-projectto a newhardhat-kms-live-registry-*directory under the system temp directory, writeshardhat-kms,@hardhat-kms/aws,@hardhat-kms/gcpand@hardhat-kms/azureat that exact version into itspackage.json, runsnpm install --ignore-scripts --legacy-peer-depsthere, and fails unless each of the four packages (Turnkey is not in the live gate), and the core each provider loads, resolves to that version (test/live/helpers/packages.ts). It then imports the providers by package name and uses the copy as the Hardhat project root.A resolve hook (
module.registerHooks, from Node 22.15; on an older Node the run fails before the install and says so) sends an import of one of the four packages from outside the copy to the copy'snode_modules, and an import of their peer dependencies (hardhat,viem) from inside the copy to the workspace's, so Hardhat and viem load once, as in a project that installs them once. The hook records every module it resolves under the checkout'spackages/. Each live file ends withregistry: ran the published packages and nothing from packages/, which fails if any was loaded, the plugins' hook handlers included, or if a package resolved to another version.The copy is removed when the process exits, by a function that refuses any directory the process did not create. npm reads its usual config, so
npm_config_registrypoints the install at another registry andnpm_config_offline=trueinstalls from npm's cache only. A Sepolia run in registry mode writes no proof: a proof names the commit it ran, and this run tested a version from npm, not a commit.promote.ymlruns fork mode in registry mode when itslive-runinput isfork(Live tests in GitHub Actions). For example,HARDHAT_KMS_LIVE_SOURCE=registry:0.9.0 pnpm run test:liveruns the fork against 0.9.0 from npm.
In both sources the EIP-7702 authorizations are signed through
connection.kms.getAccount, so no live file importssrc/internal/.test/live/mode.test.tschecks the source switch, andtest/live/packages.test.tschecks the hook against a stand-in scratch project (skipped on Node 22.13, the published floor), the refusal to remove a directory, and that no file intest/live/imports frompackages/or aninternal/path, except the threesrc/index.tsimports of the loader's source mode; both run inpnpm test.Every receipt must have the status, sender, transaction type and value its case expects. The RPC URL comes from the
HARDHAT_KMS_LIVE_SEPOLIA_RPC_URLconfig variable; without it the suite useshttps://ethereum-sepolia-rpc.publicnode.com, which needs no API key. The legacy and EIP-2930 transactions pay agasPriceof twice the latest base fee or the node'seth_gasPrice, whichever is higher, rounded up to a whole gwei, so a rising base fee cannot strand them; the EIP-1559 and EIP-7702 transactions take the plugin's fees. Before anything is sent, each account must hold the run's floor and, on Sepolia, that gas price must be at most 20 gwei; otherwise its test fails and says which limit it hit. The floor comes from the case table: the sum of thegasbudgets of the cases the mode runs, times that gas price (balanceFloorintest/live/matrix.ts). On Sepolia, a receipt that does not arrive within 300 seconds fails the test with the transaction's hash and nonce and the account's mined transaction count, so the transaction can be replaced. Public RPCs balance requests across nodes, and a node behind the others can answer a read with state from before the last write. So every read that checks state after a write (count(), balances, code, the account's slot 0, the signature checks, and the nonce for the explicit-nonce transactions) asks for the block of the latest receipt. A lagging node then answers "block not found" or "header not found" instead of stale state, andtest/live/helpers/retry.tstries the read again, up to 10 times, 2 seconds apart. Waiting for a receipt needs no such pin: viem polls until a node returns the receipt. A lagging node also still counts the latest receipt's transaction as pending, and geth refuses a send from a delegated account that has another pending transaction (in-flight transaction limit reached for delegated accounts), and a send carrying an authorization whose authority has one (authority already reserved). The node broadcast nothing and the plugin keeps no nonce for a refused send, so every send of the suite goes through the same file'sretryPoolRefusal, which sends again up to 10 times, 6 seconds apart, and writes a diagnostic for each retry (#685). A run clears its delegations at the end, also after a failure; when a failed clean-up leaves an account delegated anyway, the next run clears it before its first transaction:test/live/helpers/delegation.tssends the account's authorization of the zero address in a transaction to itself, outside the proof, and thegetAccountsuite does the same before its self-transfer. The cost of a Sepolia run is under Cost per run. Failures go throughtest/live/helpers/redact.ts, which removes each key variable and its parts (the AWS key id split on:and/, the GCP project, key ring and key, the Azure vault, key and version), the RPC URL, ARNs, aliases, UUIDs, 12-digit account ids, Azure'skey vault '<name>;location=…'form, GCP project numbers, any URL and any/v2/path. It also removes signed data: any hex string of 65 bytes or more, with or without0x(raw transactions and signatures), the value of anrorsfield, with or without0x, and 32-byte values in an argument list such as viem'sargs: (…)orrecoverPersonal(…). Transaction hashes and addresses elsewhere stay.test/live/redact.test.tschecks it with made-up identifiers of each kind,test/live/gas.test.tsthe gas price,test/live/retry.test.tsboth retries,test/live/delegation.test.tsthe clean-up of a leftover delegation, andtest/live/lock.test.tsthe lock that keeps a replacement case away from other providers' sends; all five run inpnpm test.LiveCheckhas areceivefunction, so a plain transfer to the account works even if a delegation were left behind. The transactions of the latest Sepolia run are listed in Live proof. -
test/live/accounts.live.test.ts, whichpnpm run test:liveruns after the matrix, reads the same key variables and mode.test:liveruns the live files one at a time (--test-concurrency=1), because each fork reads Sepolia through the same public RPC; run together, the forks slowed it until the matrix's requests timed out. For each configured provider it runskms accounts --jsonon an http network whosekmsAccountsholds the key, once plainly for the address, then with--balances --check-sign. It expects the address,signCheck: "ok", nobalanceorsignCheckfield in the plain run, and no signature in standard output, standard error or the report. In fork mode it starts its own anvil fork behind the recording proxy, checksweb3_clientVersion, gives the account 12.345678901234567891 ETH withanvil_setBalanceand expects exactly that balance, then fails if the proxy refused anything. In Sepolia mode it expects a decimal balance, since the matrix may be spending from the account at the same time. It sends no transaction and spends nothing in either mode. -
test/live/get-account.live.test.tschecksconnection.kms.getAccountwith the same key variables and mode. On the fork it funds the account and a throwaway sponsor withanvil_setBalance, recovers a message and typed data the account signs, sends an EIP-1559 transfer through a viem wallet client built with the account, and has the sponsor send the EIP-7702 authorization the account signed, then checks the account's delegation code. On Sepolia it sends one EIP-1559 transaction of 0 wei from each account to itself.
-
- Mutation testing: Stryker changes the code one small edit at a time (a mutant) and reports each edit that no test catches.
- What runs: StrykerJS 10 with
@stryker-mutator/tap-runnermutatespackages/hardhat-kms/src/internal/crypto/,src/internal/signer/(notsigner/types.ts),src/internal/viem/(notviem/types.ts),src/internal/alchemy/and five files ofsrc/internal/rpc/:send-guard.ts,dispatcher.ts,transaction-filler.ts,transactions.tsandrpc-data.ts. It runs the core's unit tests against each mutant, each test file in its ownnodeprocess with Node's type stripping (no tsx, no build). The config ispackages/hardhat-kms/stryker.config.json. In the baseline, 57 of the 655 caught mutants were caught bytest/unit/tasks/keys.test.tsandtest/unit/rpc/transactions.test.ts, outsidetest/unit/cryptoandtest/unit/signer, so the run uses every unit test file but one:error-types.test.tsrunstscon a fixture through paths outside the package, which do not exist in Stryker's sandbox, and runs no code fromcrypto/orsigner/. Integration tests are not part of the run. - Command:
pnpm run test:mutation. It is incremental: it readspackages/hardhat-kms/reports/stryker-incremental.jsonand re-tests only the mutants in changed source files and the mutants covered by changed test files. A change outside those files is not seen: a dependency update, or a change to unmutated source that the mutated code imports, such aserrors.ts,error-catalog.ts,rpc/chain-id.tsorrpc/typed-data.ts. Such a change shows only in a full run;pnpm --filter hardhat-kms exec stryker run --forcetests every mutant. The HTML report ispackages/hardhat-kms/reports/mutation/mutation.html; the clear-text output lists each surviving mutant with its diff, then a score table per file.reports/and.stryker-tmp/are gitignored. - Three settings in the config need a reason, which sits next to each as a
_commentkey.tsconfigFilenames a file that does not exist: Stryker rewritestsconfig.jsonin its sandbox with thetypescriptpackage'sparseConfigFileTextToJson, which TypeScript 7 does not export, so the run fails. The rewrite only serves Stryker's TypeScript checker, which this setup does not use.pluginsnames the tap runner: Stryker's default plugin glob only searches the folder next to its own install, where pnpm does not put the runner. Named explicitly, it is imported by package name and resolves through pnpm's hidden hoist (node_modules/.pnpm/node_modules).tap.testFilesleaves outerror-types.test.ts, as above. - Schedule:
.github/workflows/mutation.yml, on Linux only. Aplanjob readsmutatefrom the Stryker config and makes one shard per entry that names a single file, called after its directory and file, and one per directory undersrc/internal/for the other entries:crypto,signer,viem,alchemy,rpc_send_guard,rpc_dispatcher,rpc_transaction_filler,rpc_transactionsandrpc_rpc_data. An exclusion (!) goes to every shard of its directory, and a directory shard leaves out the files that have shards of their own, so no mutant is tested twice. A file entry with other characters in its name than lowercase letters, digits and-runs in its directory's shard. An entry outsidesrc/internal/<directory>/fails the plan, so a new entry cannot fall outside every shard. Each shard is a job on its own runner that passes its entries tostryker run --mutate, so the slowest shard sets the wall time instead of the sum of all nine. Each shard checks its own score againstbreak, and ascorejob adds up the shards' JSON reports and checks the total. Everything below applies per shard. Every run that reaches Stryker saves its incremental file in the Actions cache under a new key,stryker-<os>-<shard>-<hash>-<run id>-<attempt>-<pass|fail>, where the hash covers the core'ssrc/andtest/, the Stryker config,pnpm-lock.yamland the workflow file. Weekly, on Mondays at 03:17 UTC, it first looks up the newest entry for the current hash. If that run passed, it writes "skipped" to the job summary and stops before installing; after a failed run it runs again, so a failure repeats every week until it is fixed. Otherwise it restores the newest incremental file (for this hash, else any) and runs incrementally. GitHub evicts cache entries unused for 7 days, so most weekly runs find no incremental file and test every mutant. On the 1st of each month, and when dispatched withforce, it tests every mutant, and its results replace the incremental ones. When the 1st is a Monday, the weekly run skips itself and only the monthly full run tests. The workflow passes--concurrency 2, since the score depends on the worker count (below). Each shard uploads its HTML and JSON report as themutation-report-<shard>artifact, kept 14 days, and writes its score table to the job summary. Each shard job has a 120-minute limit, well above the slowest shard's expected time, since a shard cancelled at its limit saves no incremental file and would start from scratch the next week. It is not a required check and has nopull_requesttrigger, so the gate runs after merge: a pull request that leaves survivors does not fail its own checks, it turns the next weekly run red. Runpnpm run test:mutationbefore opening a pull request that changescrypto/,signer/,viem/or one of the five mutated files ofrpc/;--mutate <file>limits a run to one file. - Threshold:
thresholds.breakin the config. A score below it exits 1 and fails the scheduled run; the run's incremental file is still saved, markedfail, so the next night does not skip. It starts at the baseline rounded down, minus a margin that absorbs timeouts that depend on the machine:floor(score) − max(2, ceil(100 × timeouts / valid mutants)), where valid mutants exclude the ignored ones and the runtime errors. The margin is 2 points unless timeouts make up more than 2% of the mutants. To raise it, a pull request that raises the score setsbreakthe same way from the new CI score. Lowering it needs a reason in the pull request. - Equivalent mutants: a mutant that behaves like the original for every input the code can receive cannot be killed. An injectable seam, such as
Timersor an adapter, counts as an input within its contract (aTimersnever runs a callback insidesetTimeout, as real timers never do): a guard that only a misbehaving seam can reach, such as aTimerswhose cancel does nothing, is tested with such a seam, not marked. An equivalent mutant is marked in the source with// Stryker disable next-line <Mutator>: <reason>, and the reason says why the edit changes nothing, so a reader can check it, as for type escapes. Stryker reports the mutant as ignored, outside the score. The comment applies to every mutant of that mutator whose node starts on the next line. Babel places a&&or||expression at its first operand, so a redundant operand goes last, on its own line, with the comment above it: placed first, the comment would also skip the mutants of the whole condition, such as the one that turns a key comparison intotrue. Where the equivalent mutant and a killed one are on the same node, for examplen < 256changed ton <= 256or ton >= 256, the comment skips both, and the pull request lists the killed ones. An unreachable block is marked with// Stryker disable BlockStatement: <reason>before theifand// Stryker restore BlockStatementafter it, since its opening brace shares a line with the end of the condition. Anelseblock cannot take a line comment of its own, since a comment beforeelsebelongs to the block above it;signer-identity.tsputs the directive in a block comment betweenelseand its brace. Every mutant insrc/internal/crypto/,src/internal/signer/(#169)src/internal/viem/(#51)src/internal/rpc/send-guard.ts(#205) andsrc/internal/alchemy/(#495) is killed, marked, or a runtime error. The 2 runtime errors incrc32c.tsaren--andk--, which never end the table loops when the module loads; Stryker stops them with its hit count limit, an error rather than a test failure. The third, inviem/inputs.ts, empties the arrow function that builds the table of signed types when the module loads, so the module fails to load. The library account's refusals are tested with their exact messages (test/unit/viem/refusals.test.ts), since a pattern match lets the method name or the field path in a message change unseen. - Equivalent mutants in
rpc/dispatcher.ts,rpc/transaction-filler.tsandrpc/transactions.ts(#331) are listed here instead of marked in the source, so each counts as a survivor in its shard's score and no disable comment hides a mutant of the same node that a test kills. Every other mutant of the three files is killed. The three listed:dispatcher.ts,rawKmsTransaction:/^0x/ichanged to/0x/i. The string has already decoded as a transaction, so it is hex with an optional0xprefix, and both remove the same characters.transaction-filler.ts,QUANTITYwithout its^. It is only tested on values thatcanonicalAuthorizationSignatureswrote, which match either way, or left alone. A value left alone that ends in a quantity still holds anxafter the padding, so Hardhat's schema refuses it with the same message.transactions.ts,lintAuthorizations:yParity === 0 || yParity === 1changed totrue.buildUnsignedTransactionruns first and refuses any otheryParity, so the condition is always true there.
- Machine load changes the result. A mutant that makes a test run past Stryker's timeout counts as caught (
# timeout). On an overloaded machine, survivors turn into timeouts: on an 8-core laptop, Stryker's default of 7 workers reported 63 timeouts and 85.41%, against 7 timeouts and 82.54% with--concurrency 2. Compare scores from the CI job, which runs 2 workers (--concurrency 2) on 2 vCPUs. A mutant that leaves a promise unsettled is a timeout too, whatever the load:node:testwaits for each test's promise, so the file never ends and Stryker stops it. Most timeouts insend-guard.tsare of this kind, such as a lock that is never handed to the next send. Tests that share a lock key let one failing test leave the next one waiting, which turns a fast failure into a timeout, so each library hold test insend-guard.test.tsuses its own key. A mutant that a test catches only by waiting on a real timer, such as the 60 s limit of a library hold, survives or times out depending on load and on Stryker's per-mutant timeout. Check such an effect at once instead:send-guard.test.tschecks that closing a connection's send state ends its holds right away, rather than waiting for the hold's limit. - Baseline after #205 added
rpc/send-guard.tsand split the workflow into shards, 2026-10-03 ond5020ec, from a full CI run (run 37131684354) onubuntu-26.04with 2 workers per shard: 1897 mutants in 12 files; score 100%; 1793 killed, 44 timeouts, no survivors, none without coverage, 3 runtime errors, 57 ignored. The Stryker step took 14 minutes 10 seconds forcrypto, 12 minutes 35 seconds forrpc, 11 minutes 28 seconds forsignerand 9 minutes 37 seconds forviem; the run took 19 minutes 38 seconds from start to end, about 50 billable minutes. Of the 44 timeouts, 35 are insend-guard.ts, the same count in two local runs.breakis 97:floor(100) − max(2, ceil(100 × 44 / 1837)), with 1837 valid mutants, since the timeouts are 2.40% of them. Before the new tests and markers, a local run ofsend-guard.tsalone scored 92.68%: 312 killed, 68 timeouts, 29 survived, 1 without coverage. - Scores after #331 added the three rpc files, from a forced CI run (run 37668014643) on
ubuntu-26.04with 2 workers per shard: 99.91% over all seven shards (3179 of 3182).rpc_dispatcher99.88% (809 valid mutants: 779 killed, 29 timeouts, 1 survived),rpc_transaction_filler99.79% (478: 477 killed, 1 survived) andrpc_transactions98.04% (51: 50 killed, 1 survived); the other four 100%. Run times vary with the runners: that run took 35 minutes 56 seconds from start to end, with every shard slower than in the previous one,cryptoincluded (32 minutes 30 seconds, against 15 minutes 13 seconds, with no change to its code or tests). The previous run on the same rpc shards (run 37657034427) took 22 minutes 7 seconds, its slowest Stryker steprpc_dispatcherat 21 minutes 25 seconds. - Scores of the three files before #331, from a forced local run on
8e333dawith 4 workers on an 8-core laptop, 2026-10-07:dispatcher.ts66.09% (808 mutants: 479 killed, 55 timeouts, 123 survived, 151 without coverage),transaction-filler.ts87.13% (474: 413 killed, 46 survived, 15 without coverage) andtransactions.ts54.72% (53: 29 killed, 5 survived, 19 without coverage). Most of the new tests are intest/unit/rpc/dispatcher.test.ts,dispatcher-sends.test.tsanddebug-log.test.ts, which calldispatch()throughtest/helpers/dispatch-fixture.ts, a fake node whose every answer a test sets. - Reading the report: open
mutation.html(or download the artifact) and pick a file; each surviving mutant shows the edit no test caught. Kill it with a test that fails on that edit, or mark it as equivalent, as above.
- What runs: StrykerJS 10 with
Test code follows a few conventions:
- Each test opens a fresh connection with
hre.network.create()(connect()is deprecated since Hardhat 3.18;getOrCreate()reuses cached connections, so per-connection state must tolerate reuse). - HRE test files run with
concurrency:false. - Test globs are quoted in scripts, so the shell does not expand them.
- Helpers live in each package's own
test/helpers, becausehardhat-test-utilsis private. - The root
test,test:unitandcoveragescripts runpnpm run buildfirst, because provider packages import the core from its builtdist/. - Code that removes a directory with
rmSync(..., { recursive: true })stays out of the real temp directory, and so do its tests. A mutant that replaces the per-run directory withtmpdir()would make the test remove the real temp directory.scripts/pack.tsandtest/scripts/pack.test.tsare the model:- The code checks the path first and refuses anything outside the directories it created.
removePackDirectoryremoves only ahardhat-kms-pack-*directory directly underos.tmpdir(). - A test of such code runs it under a temp directory the test creates. In
beforeit setsTMPDIR,TEMPandTMPto that directory and asserts thatos.tmpdir()returns it; inafterit restores the three variables and removes the directory.TEMPandTMPare for Windows, whereos.tmpdir()readsTEMP, thenTMP, and ignoresTMPDIR. - A mutant you make by hand in such code (Stryker does not cover
scripts/) runs under the same sandbox: set the three variables in the shell beforenode --test, for exampleTMPDIR=$sandbox TEMP=$sandbox TMP=$sandbox node --test test/scripts/pack.test.ts.
- The code checks the path first and refuses anything outside the directories it created.
Coverage uses c8 on native TypeScript (Node 24), with a threshold of 95% for lines, branches, functions and statements across each package's src/, set in the package's .c8rc.json. Provider adapters are tested with fake SDK clients, so they are held to the same bar. types.ts and type-extensions.ts are excluded.
Deprecated APIs are checked in five places. pnpm run check lints our own code with typescript/no-deprecated. pnpm run docs:check lints the TypeScript snippets of the docs and READMEs with the same rule. pnpm run pkg:check fails on a deprecated package in a published package's production tree, as the lockfile records it. pnpm run test:fresh-install (scripts/check-fresh-install.ts) fails on one in a user's fresh install: it installs each provider package with the core into empty projects with npm and pnpm and empty caches, walks the production tree as Node resolves it, nested copies included, and asks the registry about each version; fresh-install.yml runs it weekly and on pull requests that change a published manifest, and the release workflow runs it in its own fresh-install job, which both publish jobs need. The Node 26.0.0 leg of the CI test job fails any Node process of the tests, Hardhat CLI runs included, that emits a DeprecationWarning not on its allowlist; worker threads are not covered (see Tooling). A test that calls a deprecated API on purpose fails that leg. Set process.noDeprecation around that one call, as the providers' test/helpers/import-recorder.mjs do for the module.register fallback that Node 22.13 needs, or, for a warning a dependency emits, add its code to ALLOWED_WARNINGS in scripts/deprecation-hook.ts with the reason and the upstream link. Each check has its tests in test/scripts/, with fixtures in test/scripts/fixtures/.
The test:unit and test:integration scripts of the published packages run node --test through scripts/node-test.ts, which chooses the --test-timeout value by Node major. The flag means two different things:
- On Node 24 and later it limits each test. A file may run as long as its tests need.
- On Node 22 it limits each test file and sets no limit per test. The runner ends a file that runs past the value with SIGTERM, even when every test in it passes.
Node changed the flag in nodejs/node#57672, first released in 24.0.0. The 22.x line does not have the change.
| Script | Node 24 and later: limit per test | Node 22: budget per file |
|---|---|---|
test:unit |
30 s | 300 s |
test:integration |
120 s | 600 s |
The file budget is sized to end a hung file, not to time a test: a file such as tasks-cli.test.ts starts the Hardhat CLI 37 times across its 33 tests and, on a loaded machine, can run for minutes with every test passing. So on Node 22 a hung test is reported as a cancelled file after up to 10 minutes (5 for a unit file), not as a failed test. The same tests run on Node 24 and 26, where the runner cancels the hung test by name at its limit. A test's own timeout option and the limits of the CLI helper apply on every version. In CI the job's 15-minute timeout stays the outer limit.
The localstack, examples and live scripts pass one --test-timeout value on every version, and coverage passes none. CI runs the localstack, examples and coverage jobs on Node 24, and live-tests.yml and the live job of promote.yml run test:live on Node 24; the live scripts also run locally, and on Node 22 their value limits each file. test/scripts/node-test.test.ts runs fixture files through the script with limits of a few seconds: a file whose passing tests together run longer than the per-test limit passes on every version, a slow test is cancelled at the per-test limit on Node 24 and later, and on Node 22 its file is cancelled at the budget.
When the Node floor moves to a release that has the change (24.0.0, or a later 22.x release if the 22.x line ever gets it), delete the file budgets and the script, and put --test-timeout back in the package scripts.
The published packages' Node.js floor is engines.node in packages/*/package.json (Supported Node.js versions). Developing in the clone needs Node >= 22.18.0 (root devEngines), because the scripts and hooks run .ts files with plain node, and 22.18.0 is the first 22.x release that strips types without a flag. So on the published floor, pnpm test stops with ERR_PNPM_BAD_RUNTIME_VERSION before it runs anything. To run the suite there anyway, for example to reproduce a failure of the CI Test (Linux, Node 22.13.0) job, set two variables:
nvm install 22.13.0 # installs it if needed and switches to it
pnpm_config_runtime_on_fail=ignore NODE_OPTIONS='--import tsx' pnpm test
nvm use # back to the Node in .nvmrcpnpm_config_runtime_on_fail=ignorestops pnpm from refusing the runtime. pnpm checksdevEngines.runtimeonpnpm runandpnpm exectoo, not only onpnpm install(runtimeOnFail). It has to be the environment variable: the root scripts callpnpm runandpnpm -r runagain, and the--runtime-on-fail=ignoreflag does not reach those nested calls, while every child process inherits the variable.NODE_OPTIONS='--import tsx'preloads tsx, a devDependency, into every Node process, so the.tsscripts and test files load on a Node that does not strip types. Without it the first script fails withERR_UNKNOWN_FILE_EXTENSION.
The CI 22.13.0 legs of .github/workflows/ci.yml and ci-all-os.yml run pnpm test with the same two settings. pnpm_config_runtime_on_fail=warn works too: it runs the suite and prints a [WARN] line at each pnpm call. Set either one for this run only; the development floor stays at 22.18.0.
The live suite's coverage is a table in test/live/matrix.ts: every action (a transfer, a deploy, a call, a revert, a replacement, an EIP-7702 delegation and so on) against every transaction type from 0 to 4, plus personal_sign, eth_signTypedData_v4 and eth_sign. Each cell has exactly one decision, and the same decision applies to each configured provider. A cell that one provider could not run would need its own decision and reason. pnpm run docs:live-proof renders Live proof from a Sepolia run: the table with the decision of each cell, then a transaction hash for each live cell and provider.
test/live/matrix.test.ts runs in pnpm test, with no keys and no network. It fails when:
- a cell has no decision, more than one, or a decision for a cell that does not exist;
- a
liveorforkdecision names a case that does not cover the cell, a case covers a cell whose decision does not name it, a case runs in another mode than its decision, or a case sends another type than its cells; - a
fork,refusedorn/adecision has no reason, or a reason that does not fit it: reasons (a), (d), (e) and (h) say why a cell cannot run on Sepolia and may only make itfork, (b), (c), (f) and (g) say why the protocol forbids it and may only make itn/a, and (r) onlyrefused; - a
unitorrefuseddecision, or the unit test aforkdecision also names, points to a file that does not exist or that has noit(ortest(call with that literal title. A title in a comment, init.skip(orit.todo(, or in a call with askiportodooption does not count.
It also tests the per-run check, the balance floor and the renderer on made-up runs. It also checks the committed proof: test/live/proof.json must be for Sepolia, list AWS, Google Cloud and Azure once each, and have a transaction hash for every live cell of each, and docs/live-proof.md must be the page rendered from it. Only a Sepolia run with all three providers configured, all passing, writes the file, so a run with fewer cannot overwrite a complete proof. The two checks are skipped only while the file is missing and docs/live-proof.md is still the hand-written page from before the matrix. The rendered page says it is rendered from test/live/proof.json, so once it is committed, a missing proof fails.
| Decision | Meaning |
|---|---|
live |
A case runs it on Sepolia and in fork mode. |
fork |
A case runs it only in fork mode. The reason says why it cannot run on Sepolia. |
unit |
Only a unit or integration test covers it. The decision names the file and the test. |
refused |
The plugin refuses it before any request, and a unit test checks the refusal. Blob transactions (type 3) are refused. |
n/a |
The protocol does not allow it. The reason quotes the EIP, for example the null destination that EIP-4844 and EIP-7702 forbid in deploys. |
The fork-only cases are the self-sends of types 0 and 1, the reverts of types 0, 1 and 4, the replacements of types 0, 1, 2 and 4, and a local account that sends the KMS key's authorization. A replacement turns automine off with evm_setAutomine, sends a 1 wei self-send, sends a second one with the same nonce and double the fees, mines one block, and checks that only the second was mined. Automine is a setting of the whole node, so a replacement case holds a lock that no other provider's case holds at the same time (test/live/helpers/lock.ts). The local sender is a key generated in memory and funded with anvil_setBalance; the KMS key signs its authorization with the account's current nonce, since another account sends it. The reverting type 4 case delegates the account back to LiveCheck from the 3-byte contract and checks the delegation stays applied, since EIP-7702 does not roll back processed authorizations when execution fails.
A Sepolia run sends 15 transactions per provider. In a fork run on 2026-10-02 the live cases used 1,133,870 gas per provider, of which LiveCheck's deploy is about 667,000. That is about 0.0011 ETH per provider at 1 gwei, and about 0.0034 ETH for the three providers. The legacy and EIP-2930 transactions pay at least twice the base fee, so a run costs more than the 1 gwei figure. The fork-only cases cost nothing.
- Add the case's id to
CASE_IDSand its entry toCASESintest/live/matrix.ts, in the place it should run: its mode, its type, the cells it covers, the status and sender its receipts must have, agasbudget above what its transactions use together, and a title for the docs. - Point each cell it covers at it in
DECISIONS, with a reason fromREASONSfor aforkdecision. - Add its step to
STEPSintest/live/cases.ts. The typecheck fails until every case has one. Send throughProviderRun.mined, which checks the receipt against the case and records it. - Run
pnpm testfor the completeness check, thenpnpm run test:livein fork mode with every provider. - A new live case changes the proof: run the suite on Sepolia, then
pnpm run docs:live-proof, and committest/live/proof.jsonwithdocs/live-proof.md.
.github/workflows/live-tests.yml runs pnpm run test:live on a GitHub-hosted runner with the AWS, Google Cloud and Azure test keys. The job signs in to the three clouds over OIDC, so the repository holds no cloud credential: no access key, no AZURE_CLIENT_SECRET, no service account key.
.github/workflows/promote.yml has a second job in the same environment, Live tests from npm (fork). It runs only when the workflow's live-run input is fork, after the verify job: it runs the suite in fork mode with HARDHAT_KMS_LIVE_SOURCE=registry:<version>, so it signs with the three test keys through the packages users install. It installs the packages once before the first cloud login, which fills npm's cache, and the suite then installs them again with npm_config_offline=true, so nothing is downloaded with credentials. Both release jobs of that workflow wait for it, and a failed or rejected live job stops the promotion. Releasing describes the workflow.
- Manual dispatch, from the Actions tab or with
gh workflow run live-tests.yml -f network=fork. Thenetworkinput isfork(the default: a local anvil fork of Sepolia, which spends nothing) orsepolia(spends Sepolia ETH and writestest/live/proof.json). - The label
ci:liveon a pull request whose branch is in this repository. Adding it runs that pull request's code, always in fork mode. A later push does not run the tests again: remove the label and add it again, which asks for a new approval of the new code. Any other label starts nothing. - On a pull request from a fork, the label runs nothing: GitHub gives such a run no OIDC token and no environment secrets, so a small job writes a notice in the run's summary instead. To test it, a maintainer pushes the reviewed commits to a branch of this repository and dispatches the workflow on that branch.
There is no schedule, and no push, plain pull_request or pull_request_target run.
The job runs in the live-tests environment, whose required reviewer is the owner. Every run, dispatched or labelled, waits for that approval before it starts, and so does the live job of a promote.yml run with live-run: fork. An approved run executes the code of its branch with the right to sign with the three test keys, so before approving a label run, read the pull request's diff, including any change to the workflow itself, to the test helpers and to the dependencies. A dependency update changes code the diff does not show, since its diff is mostly the lockfile. Then check the run itself:
- Its commit, on the run page, must be the pull request head you read. A run is pinned to the commit it was started on: if the branch moved after that, the page shows code the run will not execute. Reject such a run, then remove the label and add it again.
- It must be a
Live testsrun that you started, with the label or a dispatch, or theLive tests from npm (fork)job of aPromoterun that you dispatched frommainwithlive-run: fork. Any workflow on any branch that namesenvironment: live-testsasks for the same approval; reject every other request.
Approving the promote live job also runs the published packages' dependencies as npm resolves them that day, not the lockfile's. They run with the right to sign with the three test keys, as they would for a user.
Agents never dispatch the workflow, never add ci:live and never approve the environment.
In live-tests.yml only the live job has id-token: write; in promote.yml, live and latest do. Each workflow's default is permissions: {}. Each cloud trusts one token subject, the immutable form that names the environment: repo:aelmanaa@<owner id>/hardhat-kms@<repository id>:environment:live-tests.
| Cloud | Trusted identity | What it may do |
|---|---|---|
| AWS | An IAM role whose trust policy checks the audience sts.amazonaws.com and that subject |
kms:Sign and kms:GetPublicKey on the test key |
| Google Cloud | The subject itself, as a principal of a workload identity pool, with no service account | Sign with the test key and read its public key |
| Azure | A user-assigned managed identity with a federated credential for that subject | Read the test key and sign with it |
A run outside the environment gets a token with another subject, which the three clouds refuse. This holds even when a pull request removes environment: live-tests from the workflow: its run then needs no approval, but it gets no credentials either. The three test keys hold only Sepolia ETH. The azure/login step prints the token's subject in the public log; both ids in it are public (gh api repos/aelmanaa/hardhat-kms shows them) and the subject grants nothing by itself.
The live-tests environment stores identifiers, not credentials. Its secrets are LIVE_AWS_ROLE_ARN, LIVE_GCP_WORKLOAD_IDENTITY_PROVIDER, LIVE_AZURE_CLIENT_ID, LIVE_AZURE_TENANT_ID and the three key variables the suite reads (HARDHAT_KMS_LIVE_AWS_KEY_ID, HARDHAT_KMS_LIVE_GCP_KEY, HARDHAT_KMS_LIVE_AZURE_KEY_ID); its variable LIVE_AWS_REGION gives the AWS region. A HARDHAT_KMS_LIVE_SEPOLIA_RPC_URL secret is optional; without it the suite uses its public RPC. The key variables reach only the step that checks they are set, the balance check and the test step, and the suite's redaction removes them from every failure.
- Checks out the branch, installs with
pnpm install --frozen-lockfile --ignore-scriptsand builds, with no dependency cache. - In fork mode, installs anvil from Foundry v1.8.1 with
foundry-rs/foundry-toolchain. - Builds
test/live/fixture-project, which downloads Solidity 0.8.24 into Hardhat's compiler cache; the suite's own build then finds it there. Steps 1 to 3 are everything the run installs or downloads, and all of it happens before the first cloud login, so no install script and no download runs with credentials. - Fails unless the three key variables are set. The suite skips a provider whose key is empty and still passes, so without this check a missing secret would give a green run that tested fewer providers.
- Signs in with
aws-actions/configure-aws-credentials,google-github-actions/authandazure/login(withallow-no-subscriptions, since the identity has a role on one key and none on a subscription). - In Sepolia mode, checks the balances before anything is sent: each of the three accounts must hold the run's floor (
balanceFloorintest/live/matrix.ts) at the suite's legacy gas price, and that price must be at most 20 gwei. Otherwise the run fails, naming the provider, the address and how much ETH is missing. The suite checks each account again, but its providers run in parallel, so without this check two of them could spend ETH on a run that cannot write a proof. - Runs
pnpm run test:live. - In Sepolia mode, after a passing run, uploads
test/live/proof.jsonas thelive-proofartifact, kept 7 days. The workflow never commits it: download it totest/live/proof.json, runpnpm run docs:live-proofand commit both files in a pull request.
- The job's limit is 30 minutes in fork mode and 45 on Sepolia, counted from when the job starts, after the approval.
- One
live-tests.ymlrun at a time (concurrency grouplive-tests; a running job is never cancelled), so two Sepolia runs never race on the accounts' nonces. The fork job ofpromote.ymlis outside that group; a fork run sends nothing to Sepolia. GitHub keeps one more run pending in the group; a newer run replaces a pending one, never the one that runs. - Standard GitHub-hosted runners are free for public repositories. A fork run spends no ETH; a Sepolia run spends about 0.0034 ETH at 1 gwei, and up to about twenty times that at the 20 gwei cap (see Cost per run). Each run makes a few dozen signing calls per key: AWS KMS charges about $0.15 per 10,000 of them, so a run costs well under a cent there. The Google Cloud HSM and Azure prices per operation were not checked.
Turnkey has no sandbox or emulator, so the unit and integration tests replace it with a local stub (packages/hardhat-kms-turnkey/test/helpers/turnkey-stub.ts). Only a run against Turnkey's API shows that the stamp, the request shapes, the error mapping and the setup guide's policies work there. The Free plan includes 25 signatures a month, so this test spends few and runs only when dispatched. It is not in the transaction matrix, in test/live/proof.json or in promote.yml's live job (#513).
packages/hardhat-kms-turnkey/test/live/turnkey.live.test.ts, run with pnpm run test:live:turnkey, is skipped unless five variables are set:
| Variable | What it holds |
|---|---|
TURNKEY_API_PRIVATE_KEY |
The P-256 private key of a non-root API user of the test organization |
TURNKEY_ORGANIZATION_ID |
The test organization's id |
HARDHAT_KMS_LIVE_TURNKEY_ADDRESS |
An account that the setup guide's policies (step 4) let the API user sign with |
HARDHAT_KMS_LIVE_TURNKEY_DENIED_ADDRESS |
An account in the same organization that no policy covers |
HARDHAT_KMS_LIVE_TURNKEY_CONSENSUS_ADDRESS |
An account under a policy that needs 2 approvers |
HARDHAT_KMS_LIVE_TURNKEY_SEPOLIA=1 adds the optional Sepolia send below, through HARDHAT_KMS_LIVE_SEPOLIA_RPC_URL or https://ethereum-sepolia-rpc.publicnode.com.
The cases run in order through the plugin, in a Hardhat runtime with a local simulated network (chain 31337) and four keys on the same API key: the allowed account, the same account with transactionSigning: "digest", the denied account and the consensus account. Nothing is sent to a public chain except the optional Sepolia send.
| Case | Sign requests | Confirms |
|---|---|---|
create_api_keys for the API user itself, with a fresh P-256 public key |
0 | The guide's credential deny policy: Turnkey must answer 403 |
The same request with a timestampMs 2 hours old |
0 | A stale request fails as turnkey.service.timestamp |
personal_sign |
1 | Turnkey hashes the EIP-191 preimage, sent as hex without 0x, with HASH_FUNCTION_KECCAK256 to the digest the core expects |
eth_signTypedData_v4, with a nested type and a uint256 |
1 | Turnkey's EIP-712 hash (PAYLOAD_ENCODING_EIP712) equals the core's |
kms sign --no-hash of a random digest |
1 | The HASH_FUNCTION_NO_OP path |
kms sign-auth for chain 31337, nonce 0 |
1 | An EIP-7702 authorization |
kms sign-tx of types 2, 0 and 4, not sent |
3 | sign_transaction takes the unsigned transaction without 0x, returns it signed with the same fields, and writes a legacy v as EIP-155 |
kms sign-tx of type 2 with the transactionSigning: "digest" key |
1 | The transaction's digest as a NO_OP raw payload |
kms sign-tx with the denied account |
1 | turnkey.service.forbidden, from Turnkey's own HTTP 403 (never its message). The 403 carries no turnkeyErrorCode; the note records whether one came. A policy that allows only SIGN_RAW_PAYLOAD answering 403 to a transaction is not tested here: #533 covers it with the eth.tx policies |
kms sign --no-hash of a random digest with the consensus account |
1 | turnkey.activity.approval-needed with a UUID activity id; an approval later yields only a signature of random bytes |
| Optional: one EIP-1559 transaction of 0 wei from the allowed account to itself, on Sepolia | 1 | A transaction Turnkey signed is mined. Skipped unless asked for, when the account holds too little ETH, or above a 20 gwei fee |
The consensus case prints the first block of the pending activity's id: reject that activity in the Turnkey dashboard after each run (Reject the pending activity). If create_api_keys ends any other way than the expected answer (a clean 403, or turnkey.service.timestamp for the stale request), the key may exist, also when Turnkey added it and the answer was lost. The test then lists the API user's keys with get_api_keys, a query that policies do not restrict ("all users have implicit GET (read) permissions in their own Organization", Policies overview), deletes every key with the throwaway's name (hardhat-kms-smoke-deny-check) or public key, and fails with CREDENTIAL DENY POLICY DID NOT HOLD or CREDENTIAL CHECK INCONCLUSIVE, telling you to check the API user's keys in the dashboard and delete any you did not create. It never prints a key or a key id. Fix the deny policy before any other run.
The harness is packages/hardhat-kms-turnkey/test/live/smoke.ts:
- A
fetchwrapper counts each new body sent tosign_raw_payloadorsign_transactionas a signature, including denied and pending ones and the core's fresh attempts. A retry of the same body is not counted again: Turnkey answers it with the same activity. The run sends at most 11 (SIGNATURE_CAP); the 12th is refused before it leaves the process and the case fails with the count. Requests start at least 1.1 seconds apart, for the Free plan's rate limit of 1 a second. - A 429
SIGNING_QUOTA_EXCEEDED, reported by the plugin asturnkey.service.quota, ends the run as "quota used up": that case and every later one are skipped, not failed, and the run writes no record. - It records, without values: each request's path, HTTP status, Turnkey error code, activity status and latency; for each signature the length of
randsin hex characters, the form ofv, whether0xcame back, whetherswas high; for each signed transaction its type and, for a legacy one, whethervwas EIP-155; and one scrubbed answer per activity status and per error status, with keys and enum values only, to tighten the stub. The record is printed, appended to the job summary, and, when every case passed or was skipped on purpose, written totest/live/turnkey-smoke.json.pnpm run docs:live-prooftakes that file's date, commit and count for the Turnkey line of Live proof;proof.jsonand its check stay those of the three clouds. - Failures and the printed record go through
liveRedactor, which removes the API private key, the organization id and the derived API public key by value, in any case, the denied and consensus addresses with and without0x, every UUID (activity and user ids), and every run of 64 or more hex characters. The pinned account stays, since the plugin's errors name it.kmstasks run with their text output dropped, since it would hold signatures and signed transactions.
pnpm test runs the harness offline: packages/hardhat-kms-turnkey/test/unit/live-smoke.test.ts drives the real adapter through the wrapper against the stub (11 signatures pass, the 12th is never sent; a retried body counts once; a quota 429 gives "quota used up" and skips the next case; the redaction removes a planted 64-hex-character API key, a UUID organization id, an activity id and the other two accounts), and test/integration/live-smoke.test.ts runs every case against the stub, which answers for the policies, and expects them to pass with 10 signatures.
What the first run in GitHub Actions saw of Turnkey's API (2026-10-18, turnkey-live.yml), which the stub now copies:
- A 403 from a policy has no
turnkeyErrorCode: the top-level field is an empty string, and its onedetailsentry holds the policy evaluations (policyId,outcome), with no code. The plugin maps a 403 toturnkey.service.forbiddenfrom the status alone, so it never depended on a code. The stub'sturnkeyPolicyDenied()answers in this shape. - A request whose
timestampMsis 2 hours old gets HTTP 400, not 401, with emptydetailsand an emptyturnkeyErrorCode. The plugin reads the timestamp from the message, so it still reportsturnkey.service.timestamp.
.github/workflows/turnkey-live.yml runs the smoke test on a GitHub-hosted runner. It has a workflow_dispatch trigger only: no schedule, no pull request run, and promote.yml does not run it. Dispatch it from the Actions tab or with:
gh workflow run turnkey-live.yml --ref <branch or tag>
gh workflow run turnkey-live.yml --ref <branch or tag> -f sepolia-send=trueThe job runs in the turnkey-live environment, whose required reviewer is the owner, so every run waits for approval; approve only a run you dispatched, on a commit you read. Agents never dispatch it and never approve it. The environment holds:
- the secrets
TURNKEY_API_PRIVATE_KEYandTURNKEY_ORGANIZATION_ID; - the variables
TURNKEY_ADDRESS(the allowed account),TURNKEY_DENIED_ADDRESS(no policy) andTURNKEY_CONSENSUS_ADDRESS(the 2-approver policy).
A step fails the run when one of the five is empty, since the test would skip itself and pass. The secrets reach that step and the test step only. The job has contents: read and no OIDC token; everything is installed and built before a step gets the key. After a passing run, the job uploads test/live/turnkey-smoke.json as the turnkey-smoke artifact, kept 7 days. The workflow never commits it. Download it, render the page and commit both files in a pull request:
gh run download <run id> -n turnkey-smoke -D test/live
pnpm run docs:live-proofThe API key belongs to a non-root user whose policies allow signing with one test account and deny credential changes, in a test organization on its own email address, so its blast radius is that organization. Give it a 90-day expiry and rotate it as the setup guide shows.
Cost per run: 10 of the Free plan's 25 signatures a month, 11 with sepolia-send, if Turnkey counts the denied and pending requests; the count assumes it does. That leaves room for two runs a month. With sepolia-send, the transaction costs 21,000 gas, about 0.00002 ETH at 1 gwei. The runner is free for a public repository. One run at a time (concurrency group turnkey-live), with a 20-minute limit from the start of the job.