Skip to content

Commit

Permalink
Migrating to modern syntax and scoping (#634).
Browse files Browse the repository at this point in the history
  • Loading branch information
ricmoo committed Nov 1, 2019
1 parent 1d4f90a commit 394c36c
Show file tree
Hide file tree
Showing 33 changed files with 322 additions and 339 deletions.
63 changes: 31 additions & 32 deletions packages/abstract-signer/src.ts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,13 +132,13 @@ export abstract class Signer {
// - estimateGas
// - populateTransaction (and therefor sendTransaction)
checkTransaction(transaction: TransactionRequest): TransactionRequest {
for (let key in transaction) {
for (const key in transaction) {
if (allowedTransactionKeys.indexOf(key) === -1) {
logger.throwArgumentError("invalid transaction key: " + key, "transaction", transaction);
}
}

let tx = shallowCopy(transaction);
const tx = shallowCopy(transaction);
if (tx.from == null) { tx.from = this.getAddress(); }
return tx;
}
Expand All @@ -147,39 +147,38 @@ export abstract class Signer {
// this Signer. Should be used by sendTransaction but NOT by signTransaction.
// By default called from: (overriding these prevents it)
// - sendTransaction
populateTransaction(transaction: TransactionRequest): Promise<TransactionRequest> {
return resolveProperties(this.checkTransaction(transaction)).then((tx) => {

if (tx.to != null) { tx.to = Promise.resolve(tx.to).then((to) => this.resolveName(to)); }
if (tx.gasPrice == null) { tx.gasPrice = this.getGasPrice(); }
if (tx.nonce == null) { tx.nonce = this.getTransactionCount("pending"); }

// Make sure any provided address matches this signer
if (tx.from == null) {
tx.from = this.getAddress();
} else {
tx.from = Promise.all([
this.getAddress(),
this.provider.resolveName(tx.from)
]).then((results) => {
if (results[0] !== results[1]) {
logger.throwArgumentError("from address mismatch", "transaction", transaction);
}
return results[0];
});
}
async populateTransaction(transaction: TransactionRequest): Promise<TransactionRequest> {
const tx = await resolveProperties(this.checkTransaction(transaction))

if (tx.to != null) { tx.to = Promise.resolve(tx.to).then((to) => this.resolveName(to)); }
if (tx.gasPrice == null) { tx.gasPrice = this.getGasPrice(); }
if (tx.nonce == null) { tx.nonce = this.getTransactionCount("pending"); }

// Make sure any provided address matches this signer
if (tx.from == null) {
tx.from = this.getAddress();
} else {
tx.from = Promise.all([
this.getAddress(),
this.provider.resolveName(tx.from)
]).then((results) => {
if (results[0] !== results[1]) {
logger.throwArgumentError("from address mismatch", "transaction", transaction);
}
return results[0];
});
}

if (tx.gasLimit == null) {
tx.gasLimit = this.estimateGas(tx).catch((error) => {
logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
tx: tx
});
if (tx.gasLimit == null) {
tx.gasLimit = this.estimateGas(tx).catch((error) => {
logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
tx: tx
});
}
if (tx.chainId == null) { tx.chainId = this.getChainId(); }
});
}
if (tx.chainId == null) { tx.chainId = this.getChainId(); }

return resolveProperties(tx);
});
return await resolveProperties(tx);
}


Expand Down
20 changes: 9 additions & 11 deletions packages/address/src.ts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@ function getChecksumAddress(address: string): string {

address = address.toLowerCase();

let chars = address.substring(2).split("");
const chars = address.substring(2).split("");

let hashed = new Uint8Array(40);
const expanded = new Uint8Array(40);
for (let i = 0; i < 40; i++) {
hashed[i] = chars[i].charCodeAt(0);
expanded[i] = chars[i].charCodeAt(0);
}
hashed = arrayify(keccak256(hashed));

const hashed = arrayify(keccak256(expanded));

for (let i = 0; i < 40; i += 2) {
if ((hashed[i >> 1] >> 4) >= 8) {
Expand All @@ -51,21 +52,18 @@ function log10(x: number): number {
// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number

// Create lookup table
let ibanLookup: { [character: string]: string } = {};
const ibanLookup: { [character: string]: string } = { };
for (let i = 0; i < 10; i++) { ibanLookup[String(i)] = String(i); }
for (let i = 0; i < 26; i++) { ibanLookup[String.fromCharCode(65 + i)] = String(10 + i); }

// How many decimal digits can we process? (for 64-bit float, this is 15)
let safeDigits = Math.floor(log10(MAX_SAFE_INTEGER));
const safeDigits = Math.floor(log10(MAX_SAFE_INTEGER));

function ibanChecksum(address: string): string {
address = address.toUpperCase();
address = address.substring(4) + address.substring(0, 2) + "00";

let expanded = "";
address.split("").forEach(function(c) {
expanded += ibanLookup[c];
});
let expanded = address.split("").map((c) => { return ibanLookup[c]; }).join("");

// Javascript can handle integers safely up to 15 (decimal) digits
while (expanded.length >= safeDigits){
Expand Down Expand Up @@ -140,7 +138,7 @@ export function getContractAddress(transaction: { from: string, nonce: BigNumber
logger.throwArgumentError("missing from address", "transaction", transaction);
}

let nonce = stripZeros(arrayify(BigNumber.from(transaction.nonce).toHexString()));
const nonce = stripZeros(arrayify(BigNumber.from(transaction.nonce).toHexString()));

return getAddress(hexDataSlice(keccak256(encode([ from, nonce ])), 12));
}
Expand Down
2 changes: 1 addition & 1 deletion packages/base64/src.ts/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { arrayify, BytesLike } from "@ethersproject/bytes";

export function decode(textData: string): Uint8Array {
textData = atob(textData);
let data = [];
const data = [];
for (let i = 0; i < textData.length; i++) {
data.push(textData.charCodeAt(i));
}
Expand Down
6 changes: 3 additions & 3 deletions packages/bignumber/src.ts/bignumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export class BigNumber implements Hexable {
}

div(other: BigNumberish): BigNumber {
let o = BigNumber.from(other);
const o = BigNumber.from(other);
if (o.isZero()) {
throwFault("division by zero", "div");
}
Expand Down Expand Up @@ -247,15 +247,15 @@ function toBigNumber(value: BN): BigNumber {
}

function toBN(value: BigNumberish): BN {
let hex = BigNumber.from(value).toHexString();
const hex = BigNumber.from(value).toHexString();
if (hex[0] === "-") {
return (new BN("-" + hex.substring(3), 16));
}
return new BN(hex.substring(2), 16);
}

function throwFault(fault: string, operation: string, value?: any): never {
let params: any = { fault: fault, operation: operation };
const params: any = { fault: fault, operation: operation };
if (value != null) { params.value = value; }

return logger.throwError(fault, Logger.errors.NUMERIC_FAULT, params);
Expand Down
54 changes: 27 additions & 27 deletions packages/bignumber/src.ts/fixednumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const Zero = BigNumber.from(0);
const NegativeOne = BigNumber.from(-1);

function throwFault(message: string, fault: string, operation: string, value?: any): never {
let params: any = { fault: fault, operation: operation };
const params: any = { fault: fault, operation: operation };
if (value !== undefined) { params.value = value; }
return logger.throwError(message, Logger.errors.NUMERIC_FAULT, params);
}
Expand All @@ -41,12 +41,12 @@ function getMultiplier(decimals: BigNumberish): string {

export function formatFixed(value: BigNumberish, decimals?: string | BigNumberish): string {
if (decimals == null) { decimals = 0; }
let multiplier = getMultiplier(decimals);
const multiplier = getMultiplier(decimals);

// Make sure wei is a big number (convert as necessary)
value = BigNumber.from(value);

let negative = value.lt(Zero);
const negative = value.lt(Zero);
if (negative) { value = value.mul(NegativeOne); }

let fraction = value.mod(multiplier).toString();
Expand All @@ -55,7 +55,7 @@ export function formatFixed(value: BigNumberish, decimals?: string | BigNumberis
// Strip training 0
fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];

let whole = value.div(multiplier).toString();
const whole = value.div(multiplier).toString();

value = whole + "." + fraction;

Expand All @@ -66,7 +66,7 @@ export function formatFixed(value: BigNumberish, decimals?: string | BigNumberis

export function parseFixed(value: string, decimals?: BigNumberish): BigNumber {
if (decimals == null) { decimals = 0; }
let multiplier = getMultiplier(decimals);
const multiplier = getMultiplier(decimals);

if (typeof(value) !== "string" || !value.match(/^-?[0-9.,]+$/)) {
logger.throwArgumentError("invalid decimal value", "value", value);
Expand All @@ -77,15 +77,15 @@ export function parseFixed(value: string, decimals?: BigNumberish): BigNumber {
}

// Is it negative?
let negative = (value.substring(0, 1) === "-");
const negative = (value.substring(0, 1) === "-");
if (negative) { value = value.substring(1); }

if (value === ".") {
logger.throwArgumentError("missing value", "value", value);
}

// Split it into a whole and fractional part
let comps = value.split(".");
const comps = value.split(".");
if (comps.length > 2) {
logger.throwArgumentError("too many decimal points", "value", value);
}
Expand All @@ -102,8 +102,8 @@ export function parseFixed(value: string, decimals?: BigNumberish): BigNumber {
// Fully pad the string with zeros to get to wei
while (fraction.length < multiplier.length - 1) { fraction += "0"; }

let wholeValue = BigNumber.from(whole);
let fractionValue = BigNumber.from(fraction);
const wholeValue = BigNumber.from(whole);
const fractionValue = BigNumber.from(fraction);

let wei = (wholeValue.mul(multiplier)).add(fractionValue);

Expand Down Expand Up @@ -144,14 +144,14 @@ export class FixedFormat {
} else if (value === "ufixed") {
signed = false;
} else if (value != null) {
let match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
if (!match) { logger.throwArgumentError("invalid fixed format", "format", value); }
signed = (match[1] !== "u");
width = parseInt(match[2]);
decimals = parseInt(match[3]);
}
} else if (value) {
let check = (key: string, type: string, defaultValue: any): any => {
const check = (key: string, type: string, defaultValue: any): any => {
if (value[key] == null) { return defaultValue; }
if (typeof(value[key]) !== type) {
logger.throwArgumentError("invalid fixed format (" + key + " not " + type +")", "format." + key, value[key]);
Expand Down Expand Up @@ -202,29 +202,29 @@ export class FixedNumber {

addUnsafe(other: FixedNumber): FixedNumber {
this._checkFormat(other);
let a = parseFixed(this._value, this.format.decimals);
let b = parseFixed(other._value, other.format.decimals);
const a = parseFixed(this._value, this.format.decimals);
const b = parseFixed(other._value, other.format.decimals);
return FixedNumber.fromValue(a.add(b), this.format.decimals, this.format);
}

subUnsafe(other: FixedNumber): FixedNumber {
this._checkFormat(other);
let a = parseFixed(this._value, this.format.decimals);
let b = parseFixed(other._value, other.format.decimals);
const a = parseFixed(this._value, this.format.decimals);
const b = parseFixed(other._value, other.format.decimals);
return FixedNumber.fromValue(a.sub(b), this.format.decimals, this.format);
}

mulUnsafe(other: FixedNumber): FixedNumber {
this._checkFormat(other);
let a = parseFixed(this._value, this.format.decimals);
let b = parseFixed(other._value, other.format.decimals);
const a = parseFixed(this._value, this.format.decimals);
const b = parseFixed(other._value, other.format.decimals);
return FixedNumber.fromValue(a.mul(b).div(this.format._multiplier), this.format.decimals, this.format);
}

divUnsafe(other: FixedNumber): FixedNumber {
this._checkFormat(other);
let a = parseFixed(this._value, this.format.decimals);
let b = parseFixed(other._value, other.format.decimals);
const a = parseFixed(this._value, this.format.decimals);
const b = parseFixed(other._value, other.format.decimals);
return FixedNumber.fromValue(a.mul(this.format._multiplier).div(b), this.format.decimals, this.format);
}

Expand All @@ -240,7 +240,7 @@ export class FixedNumber {
if (comps[1].length <= decimals) { return this; }

// Bump the value up by the 0.00...0005
let bump = "0." + zeros.substring(0, decimals) + "5";
const bump = "0." + zeros.substring(0, decimals) + "5";
comps = this.addUnsafe(FixedNumber.fromString(bump, this.format))._value.split(".");

// Now it is safe to truncate
Expand All @@ -253,7 +253,7 @@ export class FixedNumber {
toHexString(width?: number): string {
if (width == null) { return this._hex; }
if (width % 8) { logger.throwArgumentError("invalid byte width", "width", width); }
let hex = BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString();
const hex = BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString();
return hexZeroPad(hex, width / 8);
}

Expand Down Expand Up @@ -281,9 +281,9 @@ export class FixedNumber {
static fromString(value: string, format?: FixedFormat | string): FixedNumber {
if (format == null) { format = "fixed"; }

let fixedFormat = FixedFormat.from(format);
const fixedFormat = FixedFormat.from(format);

let numeric = parseFixed(value, fixedFormat.decimals);
const numeric = parseFixed(value, fixedFormat.decimals);

if (!fixedFormat.signed && numeric.lt(Zero)) {
throwFault("unsigned value cannot be negative", "overflow", "value", value);
Expand All @@ -297,15 +297,15 @@ export class FixedNumber {
hex = hexZeroPad(hex, fixedFormat.width / 8);
}

let decimal = formatFixed(numeric, fixedFormat.decimals);
const decimal = formatFixed(numeric, fixedFormat.decimals);

return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat);
}

static fromBytes(value: BytesLike, format?: FixedFormat | string): FixedNumber {
if (format == null) { format = "fixed"; }

let fixedFormat = FixedFormat.from(format);
const fixedFormat = FixedFormat.from(format);

if (arrayify(value).length > fixedFormat.width / 8) {
throw new Error("overflow");
Expand All @@ -314,8 +314,8 @@ export class FixedNumber {
let numeric = BigNumber.from(value);
if (fixedFormat.signed) { numeric = numeric.fromTwos(fixedFormat.width); }

let hex = numeric.toTwos((fixedFormat.signed ? 0: 1) + fixedFormat.width).toHexString();
let decimal = formatFixed(numeric, fixedFormat.decimals);
const hex = numeric.toTwos((fixedFormat.signed ? 0: 1) + fixedFormat.width).toHexString();
const decimal = formatFixed(numeric, fixedFormat.decimals);

return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat);
}
Expand Down
Loading

0 comments on commit 394c36c

Please sign in to comment.