ethers.js/src.ts/wallet/wallet.ts

188 lines
6.4 KiB
TypeScript
Raw Normal View History

2018-06-13 22:39:39 +03:00
'use strict';
import { defaultPath, entropyToMnemonic, fromMnemonic } from './hdnode';
2018-06-15 11:18:17 +03:00
import * as secretStorage from './secret-storage';
import { SigningKey } from './signing-key';
2018-06-15 11:18:17 +03:00
import { arrayify, concat, joinSignature } from '../utils/bytes';
2018-06-18 12:42:41 +03:00
import { hashMessage } from '../utils/hash';
import { isCrowdsaleWallet, isSecretStorageWallet } from '../utils/json-wallet';
2018-06-13 22:39:39 +03:00
import { keccak256 } from '../utils/keccak256';
import { defineReadOnly, resolveProperties, shallowCopy } from '../utils/properties';
2018-06-13 22:39:39 +03:00
import { randomBytes } from '../utils/random-bytes';
import { serialize as serializeTransaction } from '../utils/transaction';
2018-06-13 22:39:39 +03:00
import { Arrayish, BigNumber, BlockTag, HDNode, MinimalProvider, ProgressCallback, Signer, TransactionRequest, TransactionResponse, Wordlist } from '../utils/types';
2018-06-13 22:39:39 +03:00
import * as errors from '../utils/errors';
2018-06-13 22:39:39 +03:00
2018-06-18 12:42:41 +03:00
export class Wallet extends Signer {
readonly provider: MinimalProvider;
2018-06-18 12:42:41 +03:00
2018-06-13 22:39:39 +03:00
private readonly signingKey: SigningKey;
constructor(privateKey: SigningKey | HDNode | Arrayish, provider?: MinimalProvider) {
2018-06-18 12:42:41 +03:00
super();
2018-06-13 22:39:39 +03:00
errors.checkNew(this, Wallet);
// Make sure we have a valid signing key
if (privateKey instanceof SigningKey) {
2018-06-18 12:42:41 +03:00
defineReadOnly(this, 'signingKey', privateKey);
2018-06-13 22:39:39 +03:00
} else {
2018-06-18 12:42:41 +03:00
defineReadOnly(this, 'signingKey', new SigningKey(privateKey));
2018-06-13 22:39:39 +03:00
}
2018-06-18 12:42:41 +03:00
defineReadOnly(this, 'provider', provider);
2018-06-13 22:39:39 +03:00
}
2018-06-19 09:12:57 +03:00
get address(): string { return this.signingKey.address; }
get mnemonic(): string { return this.signingKey.mnemonic; }
get path(): string { return this.signingKey.mnemonic; }
get privateKey(): string { return this.signingKey.privateKey; }
/**
* Create a new instance of this Wallet connected to provider.
*/
connect(provider: MinimalProvider): Wallet {
if (!(provider instanceof MinimalProvider)) {
errors.throwError('invalid provider', errors.INVALID_ARGUMENT, { argument: 'provider', value: provider });
}
2018-06-18 12:42:41 +03:00
return new Wallet(this.signingKey, provider);
2018-06-13 22:39:39 +03:00
}
2018-06-18 12:42:41 +03:00
2018-06-15 11:18:17 +03:00
getAddress(): Promise<string> {
2018-06-13 22:39:39 +03:00
return Promise.resolve(this.address);
}
2018-06-18 12:42:41 +03:00
sign(transaction: TransactionRequest): Promise<string> {
return resolveProperties(transaction).then((tx) => {
2018-07-12 09:42:46 +03:00
let rawTx = serializeTransaction(tx);
let signature = this.signingKey.signDigest(keccak256(rawTx));
return Promise.resolve(serializeTransaction(tx, signature));
2018-06-18 12:42:41 +03:00
});
2018-06-13 22:39:39 +03:00
}
2018-06-18 12:42:41 +03:00
signMessage(message: Arrayish | string): Promise<string> {
return Promise.resolve(joinSignature(this.signingKey.signDigest(hashMessage(message))));
2018-06-13 22:39:39 +03:00
}
2018-06-18 12:42:41 +03:00
getBalance(blockTag?: BlockTag): Promise<BigNumber> {
if (!this.provider) { throw new Error('missing provider'); }
return this.provider.getBalance(this.address, blockTag);
}
2018-06-18 12:42:41 +03:00
getTransactionCount(blockTag?: BlockTag): Promise<number> {
2018-06-13 22:39:39 +03:00
if (!this.provider) { throw new Error('missing provider'); }
2018-06-18 12:42:41 +03:00
return this.provider.getTransactionCount(this.address, blockTag);
2018-06-13 22:39:39 +03:00
}
sendTransaction(transaction: TransactionRequest): Promise<TransactionResponse> {
2018-06-13 22:39:39 +03:00
if (!this.provider) { throw new Error('missing provider'); }
if (!transaction || typeof(transaction) !== 'object') {
throw new Error('invalid transaction object');
}
var tx = shallowCopy(transaction);
2018-06-13 22:39:39 +03:00
if (tx.to != null) {
tx.to = this.provider.resolveName(tx.to);
}
2018-06-13 22:39:39 +03:00
if (tx.gasLimit == null) {
tx.from = this.getAddress();
2018-06-18 12:42:41 +03:00
tx.gasLimit = this.provider.estimateGas(tx);
2018-06-13 22:39:39 +03:00
}
if (tx.gasPrice == null) {
2018-06-18 12:42:41 +03:00
tx.gasPrice = this.provider.getGasPrice();
2018-06-13 22:39:39 +03:00
}
if (tx.nonce == null) {
tx.nonce = this.getTransactionCount();
}
2018-06-13 22:39:39 +03:00
if (tx.chainId == null) {
tx.chainId = this.provider.getNetwork().then((network) => network.chainId);
2018-06-13 22:39:39 +03:00
}
return this.provider.sendTransaction(this.sign(tx));
2018-06-13 22:39:39 +03:00
}
2018-06-15 11:18:17 +03:00
encrypt(password: Arrayish | string, options: any, progressCallback: ProgressCallback): Promise<string> {
2018-06-13 22:39:39 +03:00
if (typeof(options) === 'function' && !progressCallback) {
progressCallback = options;
options = {};
}
if (progressCallback && typeof(progressCallback) !== 'function') {
throw new Error('invalid callback');
}
if (!options) { options = {}; }
if (this.mnemonic) {
// Make sure we don't accidentally bubble the mnemonic up the call-stack
var safeOptions: any = {};
2018-06-13 22:39:39 +03:00
for (var key in options) { safeOptions[key] = options[key]; }
options = safeOptions;
// Set the mnemonic and path
options.mnemonic = this.mnemonic;
options.path = this.path
}
return secretStorage.encrypt(this.privateKey, password, options, progressCallback);
}
2018-06-19 09:12:57 +03:00
/**
* Static methods to create Wallet instances.
*/
static createRandom(options?: any): Wallet {
2018-06-13 22:39:39 +03:00
var entropy: Uint8Array = randomBytes(16);
if (!options) { options = { }; }
if (options.extraEntropy) {
entropy = arrayify(keccak256(concat([entropy, options.extraEntropy])).substring(0, 34));
}
var mnemonic = entropyToMnemonic(entropy, options.locale);
return Wallet.fromMnemonic(mnemonic, options.path, options.locale);
2018-06-13 22:39:39 +03:00
}
static fromEncryptedJson(json: string, password: Arrayish, progressCallback: ProgressCallback): Promise<Wallet> {
if (isCrowdsaleWallet(json)) {
2018-07-03 23:44:05 +03:00
try {
if (progressCallback) { progressCallback(0); }
2018-07-03 23:44:05 +03:00
let privateKey = secretStorage.decryptCrowdsale(json, password);
if (progressCallback) { progressCallback(1); }
2018-07-03 23:44:05 +03:00
return Promise.resolve(new Wallet(privateKey));
} catch (error) {
return Promise.reject(error);
}
} else if (isSecretStorageWallet(json)) {
2018-07-03 23:44:05 +03:00
return secretStorage.decrypt(json, password, progressCallback).then(function(signingKey) {
return new Wallet(signingKey);
});
2018-06-13 22:39:39 +03:00
}
2018-07-03 23:44:05 +03:00
return Promise.reject('invalid wallet JSON');
2018-06-13 22:39:39 +03:00
}
static fromMnemonic(mnemonic: string, path?: string, wordlist?: Wordlist): Wallet {
2018-06-13 22:39:39 +03:00
if (!path) { path = defaultPath; }
return new Wallet(fromMnemonic(mnemonic, wordlist).derivePath(path));
2018-06-13 22:39:39 +03:00
}
}