Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wip: bump ethers to v6 #666

Draft
wants to merge 10 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/hdwallet-coinbase/src/ethereum.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as core from "@shapeshiftoss/hdwallet-core";
import { ETHSignedMessage } from "@shapeshiftoss/hdwallet-core";
import { isHexString } from "ethers/lib/utils";
import { isHex } from "viem";

export function describeETHPath(path: core.BIP32Path): core.PathDescription {
return core.describeETHPath(path);
Expand Down Expand Up @@ -86,7 +86,7 @@ export async function ethSignMessage(
address: string
): Promise<core.ETHSignedMessage | null> {
try {
if (!isHexString(msg.message)) throw new Error("data is not an hex string");
if (!isHex(msg.message)) throw new Error("data is not an hex string");
const signedMsg = await ethereum.request({
method: "personal_sign",
params: [msg, address],
Expand Down
4 changes: 2 additions & 2 deletions packages/hdwallet-core/src/ethereum.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Bytes } from "@ethersproject/bytes";
import { TypedData } from "eip-712";
import { BytesLike } from "ethers";

import { addressNListToBIP32, slip44ByCoin } from "./utils";
import { BIP32Path, HDWallet, HDWalletInfo, PathDescription } from "./wallet";
Expand Down Expand Up @@ -114,7 +114,7 @@ export interface ETHSignedTypedData {

export interface ETHVerifyMessage {
address: string;
message: string | Bytes;
message: BytesLike;
signature: string;
}

Expand Down
9 changes: 5 additions & 4 deletions packages/hdwallet-keepkey/src/ethereum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import * as Types from "@keepkey/device-protocol/lib/types_pb";
import { SignTypedDataVersion, TypedDataUtils } from "@metamask/eth-sig-util";
import * as core from "@shapeshiftoss/hdwallet-core";
import * as eip55 from "eip55";
import { arrayify, isBytes, isHexString } from "ethers/lib/utils.js";
import { getBytes, isBytesLike } from "ethers";
import { isHex } from "viem";

import { Transport } from "./transport";
import { toUTF8Array } from "./utils";
Expand Down Expand Up @@ -173,10 +174,10 @@ export async function ethGetAddress(transport: Transport, msg: core.ETHGetAddres

export async function ethSignMessage(transport: Transport, msg: core.ETHSignMessage): Promise<core.ETHSignedMessage> {
const { addressNList, message } = msg;
if (!isHexString(message)) throw new Error("data is not an hex string");
if (!isHex(message)) throw new Error("data is not an hex string");
const m = new Ethereum.EthereumSignMessage();
m.setAddressNList(addressNList);
const messageBytes = arrayify(message);
const messageBytes = getBytes(message);
m.setMessage(messageBytes);
const response = await transport.call(Messages.MessageType.MESSAGETYPE_ETHEREUMSIGNMESSAGE, m, {
msgTimeout: core.LONG_TIMEOUT,
Expand Down Expand Up @@ -241,7 +242,7 @@ export async function ethVerifyMessage(transport: Transport, msg: core.ETHVerify
const m = new Ethereum.EthereumVerifyMessage();
m.setAddress(core.arrayify(msg.address));
m.setSignature(core.arrayify(msg.signature));
m.setMessage(isBytes(msg.message) ? arrayify(msg.message) : toUTF8Array(msg.message));
m.setMessage(isBytesLike(msg.message) ? getBytes(msg.message) : toUTF8Array(msg.message));
let event: core.Event;
try {
event = await transport.call(Messages.MessageType.MESSAGETYPE_ETHEREUMVERIFYMESSAGE, m, {
Expand Down
8 changes: 4 additions & 4 deletions packages/hdwallet-ledger/src/ethereum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import EthereumTx from "ethereumjs-tx";
// @ts-ignore
// TODO: fix ts-ignore
import * as ethereumUtil from "ethereumjs-util";
import { arrayify, isBytes } from "ethers/lib/utils.js";
import { isHexString } from "ethjs-util";
import { getBytes, isBytesLike } from "ethers";
import { isHex } from "viem";

import { LedgerTransport } from "./transport";
import { compressPublicKey, createXpub, handleError, networksUtil } from "./utils";
Expand Down Expand Up @@ -159,7 +159,7 @@ export async function ethSignMessage(
): Promise<core.ETHSignedMessage> {
const bip32path = core.addressNListToBIP32(msg.addressNList);

if (!isHexString(msg.message)) throw new Error("data is not an hex string");
if (!isHex(msg.message)) throw new Error("data is not an hex string");

// Ledger's inner implementation does a Buffer.from(messageHex, "hex").length on our message
// However, Buffer.from method with the "hex" encoding expects a valid hexadecimal string without the 0x prefix
Expand Down Expand Up @@ -189,7 +189,7 @@ export async function ethVerifyMessage(msg: core.ETHVerifyMessage): Promise<bool
return false;
}
sigb[64] = sigb[64] === 0 || sigb[64] === 1 ? sigb[64] + 27 : sigb[64];
const buffer = isBytes(msg.message) ? Buffer.from(arrayify(msg.message)) : Buffer.from(msg.message);
const buffer = isBytesLike(msg.message) ? Buffer.from(getBytes(msg.message)) : Buffer.from(msg.message);
const hash = ethereumUtil.hashPersonalMessage(buffer);
const pubKey = ethereumUtil.ecrecover(hash, sigb[64], sigb.slice(0, 32), sigb.slice(32, 64));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import detectEthereumProvider from "@metamask/detect-provider";
import MetaMaskOnboarding from "@metamask/onboarding";
import * as core from "@shapeshiftoss/hdwallet-core";
import { enableShapeShiftSnap, shapeShiftSnapInstalled } from "@shapeshiftoss/metamask-snaps-adapter";
import { providers } from "ethers";
import { Eip1193Provider } from "ethers";

import { SNAP_ID } from "./common";
import { MetaMaskShapeShiftMultiChainHDWallet } from "./shapeshift-multichain";
Expand Down Expand Up @@ -94,7 +94,7 @@ export class MetaMaskAdapter {
mustBeMetaMask: true,
silent: false,
timeout: 3000,
})) as providers.ExternalProvider | null;
})) as Eip1193Provider | null;
if (!provider) {
const onboarding = new MetaMaskOnboarding();
onboarding.startOnboarding();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as core from "@shapeshiftoss/hdwallet-core";
import { ETHSignedMessage } from "@shapeshiftoss/hdwallet-core";
import { isHexString } from "ethers/lib/utils";
import { isHex } from "viem";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export async function ethVerifyMessage(msg: core.ETHVerifyMessage, ethereum: any): Promise<boolean | null> {
Expand Down Expand Up @@ -71,7 +71,7 @@ export async function ethSignMessage(
address: string
): Promise<core.ETHSignedMessage | null> {
try {
if (!isHexString(msg.message)) throw new Error("data is not an hex string");
if (!isHex(msg.message)) throw new Error("data is not an hex string");
const signedMsg = await ethereum.request({
method: "personal_sign",
params: [msg.message, address],
Expand Down
4 changes: 2 additions & 2 deletions packages/hdwallet-metamask/src/adapter.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import detectEthereumProvider from "@metamask/detect-provider";
import MetaMaskOnboarding from "@metamask/onboarding";
import * as core from "@shapeshiftoss/hdwallet-core";
import { providers } from "ethers";
import { Eip1193Provider } from "ethers";

import { MetaMaskHDWallet } from "./metamask";

Expand All @@ -27,7 +27,7 @@ export class MetaMaskAdapter {
mustBeMetaMask: true,
silent: false,
timeout: 3000,
})) as providers.ExternalProvider | null;
})) as Eip1193Provider | null;
if (!provider) {
const onboarding = new MetaMaskOnboarding();
onboarding.startOnboarding();
Expand Down
4 changes: 2 additions & 2 deletions packages/hdwallet-metamask/src/ethereum.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as core from "@shapeshiftoss/hdwallet-core";
import { ETHSignedMessage } from "@shapeshiftoss/hdwallet-core";
import { isHexString } from "ethers/lib/utils";
import { isHex } from "viem";

export function describeETHPath(path: core.BIP32Path): core.PathDescription {
const pathStr = core.addressNListToBIP32(path);
Expand Down Expand Up @@ -101,7 +101,7 @@ export async function ethSignMessage(
address: string
): Promise<core.ETHSignedMessage | null> {
try {
if (!isHexString(msg.message)) throw new Error("data is not an hex string");
if (!isHex(msg.message)) throw new Error("data is not an hex string");
const signedMsg = await ethereum.request({
method: "personal_sign",
params: [msg.message, address],
Expand Down
3 changes: 2 additions & 1 deletion packages/hdwallet-native/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"bnb-javascript-sdk-nobroadcast": "^2.16.14",
"crypto-js": "^4.0.0",
"eip-712": "^1.0.0",
"ethers": "5.7.2",
"ethers": "^6.11.1",
"eventemitter2": "^5.0.1",
"funtypes": "^3.0.1",
"lodash": "^4.17.21",
Expand All @@ -36,6 +36,7 @@
"scrypt-js": "^3.0.1",
"tendermint-tx-builder": "^1.0.9",
"tiny-secp256k1": "^1.1.6",
"viem": "^1.16.6",
"web-encoding": "^1.1.0"
},
"devDependencies": {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import * as core from "@shapeshiftoss/hdwallet-core";
import { getMessage, TypedData } from "eip-712";
import { BigNumber, BytesLike, providers, Signature, UnsignedTransaction } from "ethers";
import {
arrayify,
BytesLike,
computeAddress,
Deferrable,
getAddress,
joinSignature,
getBytes,
Provider,
resolveProperties,
serializeTransaction,
splitSignature,
} from "ethers/lib/utils.js";
SigningKey,
Transaction,
TransactionLike,
TransactionRequest,
} from "ethers";
import { hexToSignature, Signature, signatureToHex, toHex } from "viem";

import { buildMessage } from "../../../util";
import { Isolation } from "../..";
Expand All @@ -19,14 +21,14 @@ import { SecP256K1 } from "../core";
function ethSigFromRecoverableSig(x: SecP256K1.RecoverableSignature): Signature {
const sig = SecP256K1.RecoverableSignature.sig(x);
const recoveryParam = SecP256K1.RecoverableSignature.recoveryParam(x);
return splitSignature(core.compatibleBufferConcat([sig, Buffer.from([recoveryParam])]));
return hexToSignature(toHex(core.compatibleBufferConcat([sig, Buffer.from([recoveryParam])])));
}

export class SignerAdapter {
protected readonly nodeAdapter: Isolation.Adapters.BIP32;
readonly provider?: providers.Provider;
readonly provider?: Provider;

constructor(nodeAdapter: Isolation.Adapters.BIP32, provider?: providers.Provider) {
constructor(nodeAdapter: Isolation.Adapters.BIP32, provider?: Provider) {
this.nodeAdapter = nodeAdapter;
this.provider = provider;
}
Expand All @@ -36,62 +38,64 @@ export class SignerAdapter {
// wrapper that deferred its initialization and awaited it before calling through to a "real" method, but that's
// a lot of complexity just to implement this one method we don't actually use.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
connect(_provider: providers.Provider): never {
connect(_provider: Provider): never {
throw new Error("changing providers on a SignerAdapter is unsupported");
}

async getAddress(addressNList: core.BIP32Path): Promise<string> {
const nodeAdapter = await this.nodeAdapter.derivePath(core.addressNListToBIP32(addressNList));
return computeAddress(SecP256K1.UncompressedPoint.from(nodeAdapter.getPublicKey()));
return computeAddress(new SigningKey(SecP256K1.UncompressedPoint.from(nodeAdapter.getPublicKey())));
}

async signDigest(digest: BytesLike, addressNList: core.BIP32Path): Promise<Signature> {
const nodeAdapter = await this.nodeAdapter.derivePath(core.addressNListToBIP32(addressNList));
const recoverableSig = await SecP256K1.RecoverableSignature.signCanonically(
nodeAdapter.node,
null,
digest instanceof Uint8Array ? digest : arrayify(digest)
digest instanceof Uint8Array ? digest : getBytes(digest)
);
const sig = SecP256K1.RecoverableSignature.sig(recoverableSig);
const recoveryParam = SecP256K1.RecoverableSignature.recoveryParam(recoverableSig);
return splitSignature(core.compatibleBufferConcat([sig, Buffer.from([recoveryParam])]));
return hexToSignature(toHex(core.compatibleBufferConcat([sig, Buffer.from([recoveryParam])])));
}

async signTransaction(
transaction: Deferrable<providers.TransactionRequest>,
addressNList: core.BIP32Path
): Promise<string> {
async signTransaction(transaction: TransactionRequest, addressNList: core.BIP32Path): Promise<string> {
const tx = await resolveProperties(transaction);
if (tx.from != null) {
if (getAddress(tx.from) !== (await this.getAddress(addressNList))) {
// This can be string | Addressable, where Addressable is an object containing getAddress()
// for ENS names. We can safely narrow it down to a string, as we do not instantiate contracts with an ens name.
if (getAddress(tx.from as string) !== (await this.getAddress(addressNList))) {
throw new Error("transaction from address mismatch");
}
delete tx.from;
}
const unsignedTx: UnsignedTransaction = {
const unsignedTx = {
...tx,
nonce: tx.nonce !== undefined ? BigNumber.from(tx.nonce).toNumber() : undefined,
};
nonce: tx?.nonce !== undefined ? tx!.nonce : undefined,
} as TransactionLike<string>;

const nodeAdapter = await this.nodeAdapter.derivePath(core.addressNListToBIP32(addressNList));
const txBuf = arrayify(serializeTransaction(unsignedTx));
const txBuf = getBytes(Transaction.from(unsignedTx).serialized);
const rawSig = await SecP256K1.RecoverableSignature.signCanonically(nodeAdapter.node, "keccak256", txBuf);
return serializeTransaction(unsignedTx, ethSigFromRecoverableSig(rawSig));
return Transaction.from({
...unsignedTx,
signature: ethSigFromRecoverableSig(rawSig),
}).serialized;
}

async signMessage(messageData: BytesLike, addressNList: core.BIP32Path): Promise<string> {
const messageBuf = buildMessage(messageData);
const nodeAdapter = await this.nodeAdapter.derivePath(core.addressNListToBIP32(addressNList));
const rawSig = await SecP256K1.RecoverableSignature.signCanonically(nodeAdapter.node, "keccak256", messageBuf);
return joinSignature(ethSigFromRecoverableSig(rawSig));
return signatureToHex(ethSigFromRecoverableSig(rawSig));
}

async signTypedData(typedData: TypedData, addressNList: core.BIP32Path): Promise<core.ETHSignedTypedData> {
const address = await this.getAddress(addressNList);
const messageArray = getMessage(typedData);
const nodeAdapter = await this.nodeAdapter.derivePath(core.addressNListToBIP32(addressNList));
const rawSig = await SecP256K1.RecoverableSignature.signCanonically(nodeAdapter.node, "keccak256", messageArray);
const signature = joinSignature(ethSigFromRecoverableSig(rawSig));
const signature = signatureToHex(ethSigFromRecoverableSig(rawSig));
return { address, signature };
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as core from "@shapeshiftoss/hdwallet-core";
import { SigningKey, toQuantity } from "ethers";
import { Literal, Object as Obj, Static, Union } from "funtypes";
import PLazy from "p-lazy";
import * as tinyecc from "tiny-secp256k1";
Expand Down Expand Up @@ -294,10 +295,7 @@ const _recoverableSignatureStatic = {
const sig = RecoverableSignature.sig(x);
const recoveryParam = RecoverableSignature.recoveryParam(x);
const ethSig = core.compatibleBufferConcat([sig, Buffer.from([recoveryParam])]);
const ethRecovered = (await ethers).utils.recoverPublicKey(
msgOrDigest,
(await ethers).utils.splitSignature(ethSig)
);
const ethRecovered = SigningKey.recoverPublicKey(msgOrDigest, (await ethers).Signature.from(toQuantity(ethSig)));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here viem hexToSignature too

return checkType(UncompressedPoint, Buffer.from(ethRecovered.slice(2), "hex"));
},
r: (x: RecoverableSignature): FieldElement => Signature.r(RecoverableSignature.sig(x)),
Expand Down
6 changes: 3 additions & 3 deletions packages/hdwallet-native/src/ethereum.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as core from "@shapeshiftoss/hdwallet-core";
import { parseTransaction } from "ethers/lib/utils.js";
import { Transaction } from "ethers";

import * as native from "./native";

Expand Down Expand Up @@ -152,7 +152,7 @@ describe("NativeETHWallet", () => {
"v": 38,
}
`);*/
expect(parseTransaction(sig!.serialized).from).toEqual("0x73d0385F4d8E00C5e6504C6030F47BF6212736A8");
expect(Transaction.from(sig!.serialized).from).toEqual("0x73d0385F4d8E00C5e6504C6030F47BF6212736A8");
});

it("should sign a EIP-1559 transaction correctly", async () => {
Expand Down Expand Up @@ -186,7 +186,7 @@ describe("NativeETHWallet", () => {
"v": 38,
}
`);*/
expect(parseTransaction(sig!.serialized).from).toEqual("0x73d0385F4d8E00C5e6504C6030F47BF6212736A8");
expect(Transaction.from(sig!.serialized).from).toEqual("0x73d0385F4d8E00C5e6504C6030F47BF6212736A8");
});

describe("sign and verify message", () => {
Expand Down
12 changes: 6 additions & 6 deletions packages/hdwallet-native/src/ethereum.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as core from "@shapeshiftoss/hdwallet-core";
import { keccak256, parseTransaction, recoverAddress } from "ethers/lib/utils.js";
import { keccak256, recoverAddress, toNumber, Transaction } from "ethers";

import * as Isolation from "./crypto/isolation";
import SignerAdapter from "./crypto/isolation/adapters/ethereum";
Expand Down Expand Up @@ -84,7 +84,7 @@ export function MixinNativeETHWallet<TBase extends core.Constructor<NativeHDWall
to: msg.to,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
from: await this.#ethSigner!.getAddress(msg.addressNList),
nonce: msg.nonce,
nonce: toNumber(msg.nonce),
gasLimit: msg.gasLimit,
data: msg.data,
value: msg.value,
Expand All @@ -111,11 +111,11 @@ export function MixinNativeETHWallet<TBase extends core.Constructor<NativeHDWall
msg.addressNList
);

const decoded = parseTransaction(result);
const decoded = Transaction.from(result);
return {
v: core.mustBeDefined(decoded.v),
r: core.mustBeDefined(decoded.r),
s: core.mustBeDefined(decoded.s),
v: core.mustBeDefined(decoded.signature?.v),
r: core.mustBeDefined(decoded.signature?.r),
s: core.mustBeDefined(decoded.signature?.s),
serialized: result,
};
});
Expand Down
Loading
Loading