ethers.js/lib.esm/wallet/base-wallet.js

73 lines
3.0 KiB
JavaScript
Raw Normal View History

2022-09-05 23:57:11 +03:00
import { getAddress, resolveAddress } from "../address/index.js";
import { hashMessage, TypedDataEncoder } from "../hash/index.js";
import { AbstractSigner } from "../providers/index.js";
import { computeAddress, Transaction } from "../transaction/index.js";
2022-09-16 05:58:45 +03:00
import { defineProperties, resolveProperties, throwArgumentError, throwError } from "../utils/index.js";
2022-09-05 23:57:11 +03:00
export class BaseWallet extends AbstractSigner {
address;
#signingKey;
constructor(privateKey, provider) {
super(provider);
this.#signingKey = privateKey;
const address = computeAddress(this.signingKey.publicKey);
defineProperties(this, { address });
}
// Store these in getters to reduce visibility in console.log
get signingKey() { return this.#signingKey; }
get privateKey() { return this.signingKey.privateKey; }
async getAddress() { return this.address; }
connect(provider) {
return new BaseWallet(this.#signingKey, provider);
}
2022-10-20 12:03:32 +03:00
async signTransaction(tx) {
2022-09-05 23:57:11 +03:00
// Replace any Addressable or ENS name with an address
2022-10-20 12:03:32 +03:00
const { to, from } = await resolveProperties({
to: (tx.to ? resolveAddress(tx.to, this.provider) : undefined),
from: (tx.from ? resolveAddress(tx.from, this.provider) : undefined)
});
if (to != null) {
tx.to = to;
}
if (from != null) {
tx.from = from;
}
2022-09-05 23:57:11 +03:00
if (tx.from != null) {
2022-10-20 12:03:32 +03:00
if (getAddress((tx.from)) !== this.address) {
throwArgumentError("transaction from address mismatch", "tx.from", tx.from);
2022-09-05 23:57:11 +03:00
}
delete tx.from;
}
// Build the transaction
const btx = Transaction.from(tx);
btx.signature = this.signingKey.sign(btx.unsignedHash);
return btx.serialized;
}
async signMessage(message) {
return this.signingKey.sign(hashMessage(message)).serialized;
}
2022-10-20 12:03:32 +03:00
// @TODO: Add a secialized signTx and signTyped sync that enforces
// all parameters are known?
signMessageSync(message) {
return this.signingKey.sign(hashMessage(message)).serialized;
}
2022-09-05 23:57:11 +03:00
async signTypedData(domain, types, value) {
// Populate any ENS names
const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (name) => {
if (this.provider == null) {
2022-09-16 05:58:45 +03:00
return throwError("cannot resolve ENS names without a provider", "UNSUPPORTED_OPERATION", {
2022-09-05 23:57:11 +03:00
operation: "resolveName",
info: { name }
});
}
const address = await this.provider.resolveName(name);
if (address == null) {
2022-09-16 05:58:45 +03:00
return throwError("unconfigured ENS name", "UNCONFIGURED_NAME", {
2022-09-05 23:57:11 +03:00
value: name
});
}
return address;
});
return this.signingKey.sign(TypedDataEncoder.hash(populated.domain, types, populated.value)).serialized;
}
}
//# sourceMappingURL=base-wallet.js.map