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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/ignition-close-network-connection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@nomicfoundation/hardhat-ignition": patch
---

Updated the `ignition deploy`, `ignition track-tx` and `ignition verify` tasks to close their network connection when they finish, so Hardhat exits after using `@nomicfoundation/hardhat-ledger`.
5 changes: 5 additions & 0 deletions .changeset/ledger-device-management-kit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@nomicfoundation/hardhat-ledger": major
---

Migrated the plugin from the deprecated LedgerJS packages to Ledger's Device Management Kit. EIP-7702 transactions are now supported. Hardhat no longer exits on its own after using the Ledger, so end scripts with `await connection.close()` and update `@nomicfoundation/hardhat-ignition` alongside.
6 changes: 6 additions & 0 deletions .changeset/ledger-verify-typed-data-signatures.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@nomicfoundation/hardhat-ledger": patch
"@nomicfoundation/hardhat-errors": patch
---

Added a check that every `eth_signTypedData_v4` signature matches the submitted typed data, rejecting malformed inputs the device would otherwise sign as a different message.
6 changes: 2 additions & 4 deletions .github/actions/setup-env/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,8 @@ runs:
with:
path: ${{ steps.pnpm.outputs.path }}
key: node-cache-${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
# Needed for node-hid, which is used by @ledgerhq/hw-transport-node-hid
# We need to install it because downloading the prebuilt binaries is not
# reliable, so the CI sometimes falls back to building it from source,
# which needs this package.
# node-hid (via @ledgerhq/device-transport-kit-node-hid): its Linux prebuilt
# binary links libusb-1.0 at runtime; a node-gyp fallback build needs both.
#
# `time` is GNU /usr/bin/time: bench:regression and the benchmark runner
# tests measure peak RSS with it.
Expand Down
1,720 changes: 1,720 additions & 0 deletions packages/example-project/scripts/ledger-2.ts

Large diffs are not rendered by default.

28 changes: 17 additions & 11 deletions packages/example-project/scripts/ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import assert from "node:assert";

const BALANCE_TO_SEND = 1000000000000000000n;

const { provider, ethers } = await hre.network.create("edrOp");
const connection = await hre.network.create("edrOp");
const { provider, ethers } = connection;

const signers = await ethers.getSigners();

Expand All @@ -13,21 +14,26 @@ const hardhatAddress = hardhatSigner.address;
const ledgerSigner = signers[signers.length - 1];
const ledgerAddress = ledgerSigner.address;

// Be sure that the ledger account has some ETH
await hardhatSigner.sendTransaction({
to: ledgerAddress,
value: BALANCE_TO_SEND,
});
try {
// Be sure that the ledger account has some ETH
await hardhatSigner.sendTransaction({
to: ledgerAddress,
value: BALANCE_TO_SEND,
});

// Uncomment the RPC method you want to test
// Uncomment the RPC method you want to test

await ethSendTransaction();
await ethSendTransaction();

// await ethSign();
// await ethSign();

// await personalSign();
// await personalSign();

// await ethSignTypedDataV4();
// await ethSignTypedDataV4();
} finally {
// The Ledger session keeps the process alive until the connection is closed
await connection.close();
}

async function ethSendTransaction() {
const txParams = {
Expand Down
29 changes: 28 additions & 1 deletion packages/hardhat-errors/src/descriptors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3373,7 +3373,7 @@ export default { lib1: "0x...", lib2: "0x...", ... };
},
CONNECTION_ERROR: {
number: 90002,
messageTemplate: `There was an error trying to establish a connection to the Ledger wallet: {error}.{transportId}
messageTemplate: `There was an error trying to establish a connection to the Ledger wallet: {error}.

Make sure your Ledger is connected and unlocked, and that the Ethereum app is open.`,
websiteTitle: "Ledger connection error",
Expand Down Expand Up @@ -3424,11 +3424,38 @@ Please check that you are sending a "data" parameter with a JSON string or objec
websiteDescription: `The ledger device is locked. Please unlock it and try again.`,
},
EIP_7702_TX_CURRENTLY_NOT_SUPPORTED: {
// [DEPRECATED]
number: 90009,
messageTemplate: `EIP-7702 transactions are currently not supported.`,
websiteTitle: `EIP-7702 transactions are currently not supported`,
websiteDescription: `EIP-7702 transactions are currently not supported.`,
},
ETH_SIGN_TYPED_DATA_V4_SIGNATURE_MISMATCH: {
number: 90010,
messageTemplate: `The Ledger device signed different typed data than requested, so the signature was discarded. Known causes: a field named only with digits (e.g. "123") or "__proto__". Rename those fields.`,
websiteTitle: `The Ledger device signed different typed data than requested`,
websiteDescription: `Before signing, the Ledger SDK re-encodes your EIP-712 typed data. For some inputs that encoding differs from the EIP-712 standard, so the device signs a different message than the one you sent. Hardhat detects this by recovering the signer from your original data and refuses to return the signature.

Known causes:
- A field whose name is only digits (e.g. "123"): the SDK moves it to the front of the struct.
- A field named "__proto__": the SDK drops it.

Rename those fields and try again. If none of your fields match, please open an issue with the typed data so we can document the cause.`,
},
CONNECTION_CLOSED: {
number: 90011,
messageTemplate: `The network connection was closed. Create a new connection to keep using the Ledger.`,
websiteTitle: "Ledger connection closed",
websiteDescription: `A request reached the Ledger after its network connection was closed.

Create a new connection to keep using the Ledger.`,
},
DEVICE_ACTION_FAILED: {
number: 90012,
messageTemplate: `The Ledger device did not complete the request: {message}`,
websiteTitle: "Ledger device action failed",
websiteDescription: `The Ledger device reported an error while signing, for example because the request was rejected on the device.`,
},
},
},
HARDHAT_FOUNDRY: {
Expand Down
25 changes: 20 additions & 5 deletions packages/hardhat-ignition/src/internal/tasks/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {
DeploymentResult,
} from "@nomicfoundation/ignition-core";
import type { HardhatRuntimeEnvironment } from "hardhat/types/hre";
import type { NetworkConnection } from "hardhat/types/network";
import type { NewTaskActionFunction } from "hardhat/types/tasks";

import path from "node:path";
Expand Down Expand Up @@ -42,6 +43,21 @@ interface TaskDeployArguments {
}

const taskDeploy: NewTaskActionFunction<TaskDeployArguments> = async (
args,
hre: HardhatRuntimeEnvironment,
): Promise<DeploymentResult | null> => {
const connection = await hre.network.create();

try {
return await deployWithConnection(args, hre, connection);
} finally {
// Plugins can hold resources open on the connection until it is closed,
// and Hardhat never closes connections on its own.
await connection.close();
}
};

async function deployWithConnection(
{
modulePath,
parameters: parametersInput,
Expand All @@ -51,11 +67,10 @@ const taskDeploy: NewTaskActionFunction<TaskDeployArguments> = async (
verify,
strategy: strategyName,
writeLocalhostDeployment,
},
}: TaskDeployArguments,
hre: HardhatRuntimeEnvironment,
): Promise<DeploymentResult | null> => {
const connection = await hre.network.create();

connection: NetworkConnection,
): Promise<DeploymentResult | null> {
const chainId = Number(
await connection.provider.request({
method: "eth_chainId",
Expand Down Expand Up @@ -263,7 +278,7 @@ const taskDeploy: NewTaskActionFunction<TaskDeployArguments> = async (
userInterruptionsHandlers,
);
}
};
}

async function resolveParametersFromModuleName(
moduleName: string,
Expand Down
28 changes: 17 additions & 11 deletions packages/hardhat-ignition/src/internal/tasks/track-tx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,25 @@ const taskTransactions: NewTaskActionFunction<TrackTxArguments> = async (

const connection = await hre.network.create();

const output = await trackTransaction(
deploymentDir,
txHash,
connection.provider,
hre.config.ignition.requiredConfirmations,
);

console.log(
output ??
`Thanks for providing the transaction hash, your deployment has been fixed.
try {
const output = await trackTransaction(
deploymentDir,
txHash,
connection.provider,
hre.config.ignition.requiredConfirmations,
);

console.log(
output ??
`Thanks for providing the transaction hash, your deployment has been fixed.

Now you can re-run Hardhat Ignition to continue with your deployment.`,
);
);
} finally {
// Plugins can hold resources open on the connection until it is closed,
// and Hardhat never closes connections on its own.
await connection.close();
}
};

export default taskTransactions;
66 changes: 36 additions & 30 deletions packages/hardhat-ignition/src/internal/tasks/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,42 +60,48 @@ export async function verify(

const connection = await hre.network.create();

for await (const contractInfo of getVerificationInformationFn(
deploymentDir,
)) {
if (typeof contractInfo === "string") {
console.log(
`Could not resolve contract artifacts for contract "${contractInfo}". Skipping verification.\n`,
);

continue;
}

console.log(
`\nVerifying contract "${contractInfo.contract}" for network ${connection.networkName}...`,
);

for (const provider of enabledProviders) {
try {
try {
for await (const contractInfo of getVerificationInformationFn(
deploymentDir,
)) {
if (typeof contractInfo === "string") {
console.log(
styleText(["cyan", "bold"], `\n=== ${capitalize(provider)} ===`),
`Could not resolve contract artifacts for contract "${contractInfo}". Skipping verification.\n`,
);

await verifyContractFn(
{
...contractInfo,
force,
provider,
},
hre,
);
} catch (error) {
ensureError(error);
continue;
}

console.log(
`\nVerifying contract "${contractInfo.contract}" for network ${connection.networkName}...`,
);

console.error(styleText("red", error.message));
process.exitCode = 1;
for (const provider of enabledProviders) {
try {
console.log(
styleText(["cyan", "bold"], `\n=== ${capitalize(provider)} ===`),
);

await verifyContractFn(
{
...contractInfo,
force,
provider,
},
hre,
);
} catch (error) {
ensureError(error);

console.error(styleText("red", error.message));
process.exitCode = 1;
}
}
}
} finally {
// Plugins can hold resources open on the connection until it is closed,
// and Hardhat never closes connections on its own.
await connection.close();
Comment thread
ChristopherDedominici marked this conversation as resolved.
Resolved
}
}

Expand Down
58 changes: 43 additions & 15 deletions packages/hardhat-ledger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

This plugin allows Hardhat to integrate seamlessly with a connected [Ledger wallet](https://www.ledger.com/).

> Note: Currently, `EIP-7702` is not supported, as the underlying Ledger library doesn't implement it. A [newer library](https://www.npmjs.com/package/@ledgerhq/device-management-kit?activeTab=readme) does support EIP-7702, and migration to that library is on our roadmap.
> Note: When signing a transaction or typed data, the Device Management Kit contacts Ledger's servers: it fetches the metadata the device uses to display what you are signing ("clear signing"), and it reports each signing event (chain id, target contract, signing method, device model, app and firmware versions, whether it was blind-signed, and a random id) to Ledger's analytics endpoint. These requests go to Ledger, not to the network you are connected to, and are the only requests the plugin makes that you did not ask for. In practice, clear signing shows the token and amount for ERC-20 and NFT transfers, the ENS name of a recipient, and the network name; contract calls and typed data are displayed as before.
Comment thread
ChristopherDedominici marked this conversation as resolved.
Resolved

## Installation

Expand Down Expand Up @@ -82,34 +82,62 @@ Usage Example with Viem:
import hre from "hardhat";
import { stringToHex } from "viem";

const { viem } = await hre.network.create("yourNetworkName");
const connection = await hre.network.create("yourNetworkName");

const ledgerAddress = "0x..."; // Your ledger address

const [senderClient] = await viem.getWalletClients();
try {
const [senderClient] = await connection.viem.getWalletClients();

const hexMsg = stringToHex("Hello world");
const hexMsg = stringToHex("Hello world");

const signature = await senderClient.request({
method: "eth_sign",
params: [ledgerAddress, hexMsg],
});
const signature = await senderClient.request({
method: "eth_sign",
params: [ledgerAddress, hexMsg],
});
} finally {
// Hardhat cannot exit while the Ledger connection is open (see below).
await connection.close();
}
```

Usage Example with the provider:

```typescript
import hre from "hardhat";

const { provider, ethers } = await hre.network.create("yourNetworkName");
const connection = await hre.network.create("yourNetworkName");

const ledgerAddress = "0x..."; // Your ledger address

const msg = ethers.toUtf8Bytes("Hello world");
const hexMsg = ethers.hexlify(msg);
try {
const msg = connection.ethers.toUtf8Bytes("Hello world");
const hexMsg = connection.ethers.hexlify(msg);

const signature = await connection.provider.request({
method: "eth_sign",
params: [ledgerAddress, hexMsg],
});
} finally {
// Hardhat cannot exit while the Ledger connection is open (see below).
await connection.close();
}
```

const signature = await provider.request({
method: "eth_sign",
params: [ledgerAddress, hexMsg],
});
## Closing the connection

Hardhat cannot exit while the connection to your Ledger is open, and it does not close network connections on its own. Once your script has finished using the Ledger, close the connection:
Comment thread
Copilot marked this conversation as resolved.
Resolved

```typescript
const connection = await hre.network.create("yourNetworkName");

try {
// ... sign and send transactions ...
} finally {
await connection.close();
}
```

Without it, the process keeps running after your script ends until you stop it with Ctrl+C.

Hardhat Ignition closes the connection for you at the end of `ignition deploy`, `ignition track-tx` and `ignition verify`.
Loading
Loading