Skip to content

Commit

Permalink
fix: Most lint issues across the codebase (#251)
Browse files Browse the repository at this point in the history
* fix: Most lint issues across the codebase

* fix: Lint issues from merge with master
  • Loading branch information
karelianpie authored Mar 22, 2022
1 parent b1a851f commit f09019e
Show file tree
Hide file tree
Showing 44 changed files with 333 additions and 152 deletions.
3 changes: 3 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
dist
*.d.ts
34 changes: 25 additions & 9 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,19 +1,35 @@
{
"extends": [
"react-app",
"prettier/@typescript-eslint",
"plugin:prettier/recommended"
],
"plugins": [
"simple-import-sort"
"prettier",
"eslint:recommended",
"plugin:prettier/recommended",
"plugin:import/typescript",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"plugins": ["simple-import-sort", "@typescript-eslint", "prettier", "import"],
"rules": {
"simple-import-sort/imports": "error",
"simple-import-sort/exports": "error"
},
"settings": {
"react": {
"version": "999.999.999"
"import/parsers": {
"@typescript-eslint/parser": [".ts"]
},
"import/resolver": {
"node": {
"extensions": [".js", ".ts"]
}
}
},
"overrides": [
{
"files": ["*.ts"],
"rules": {
"no-dupe-class-members": "off",
"@typescript-eslint/camelcase": "off",
"@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }]
}
}
}
]
}
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
"build": "tsdx build",
"test": "tsdx test",
"test:coverage": "tsdx test --coverage",
"lint": "tsdx lint src test",
"lint": "run-p lint:*",
"lint:eslint": "tsdx lint src test",
"lint:typescript": "tsc --noEmit",
"docs": "typedoc --out docs src/index.ts",
"size": "size-limit",
"analyze": "size-limit --why",
Expand All @@ -41,6 +43,7 @@
"cli-table3": "^0.6.0",
"eslint-plugin-simple-import-sort": "6",
"events": "3.3.0",
"npm-run-all": "^4.1.5",
"size-limit": "7.0.4",
"tsdx": "^0.14.1",
"tslib": "^2.1.0",
Expand Down
4 changes: 2 additions & 2 deletions src/abi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const AssetStaticAbi = `tuple(
uint8 decimals,
)`;

export const AssetDynamicAbi = (Metadata: string) => `tuple(
export const AssetDynamicAbi = (Metadata: string): string => `tuple(
address address,
string typeId,
address tokenId,
Expand All @@ -37,7 +37,7 @@ export const PositionAbi =
"tuple(address owner, address spender, uint256 amount)[] tokenAllowances," +
"tuple(address owner, address spender, uint256 amount)[] assetAllowances)";

export const AdapterAbi = (Metadata: string) => [
export const AdapterAbi = (Metadata: string): string[] => [
`function assetsStatic() public view returns (${AssetStaticAbi}[] memory)`,
`function assetsStatic(address[] memory) public view returns (${AssetStaticAbi}[] memory)`,
`function assetsDynamic() public view returns (${AssetDynamicAbi(Metadata)}[] memory)`,
Expand Down
5 changes: 3 additions & 2 deletions src/cache.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { PartialDeep } from "type-fest";

import { CachedFetcher } from "./cache";
import { Context } from "./context";

const contextCacheSpy = jest.spyOn(Context.prototype, "cache", "get");
const currentValueSpy = jest.spyOn(CachedFetcher.prototype as any, "currentValue", "get");
const consoleWarnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
const consoleWarnSpy = jest.spyOn(console, "warn").mockImplementation();
const fetchWithTimeoutSpy: jest.SpyInstance<Promise<PartialDeep<Response>>> = jest.spyOn(
CachedFetcher.prototype as any,
"fetchWithTimeout"
Expand Down Expand Up @@ -66,7 +67,7 @@ describe("CachedFetcher", () => {
const responseMock: PartialDeep<Response> = {
status: 200,
headers: {
get: _ => null
get: (_): null => null
},
json: () =>
Promise.resolve({
Expand Down
2 changes: 1 addition & 1 deletion src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export class Context implements ContextValue {
* interaction.
* @param provider new provider(s)
*/
setProvider(provider?: JsonRpcProvider | ReadWriteProvider) {
setProvider(provider?: JsonRpcProvider | ReadWriteProvider): void {
if (provider instanceof JsonRpcProvider) {
this.ctx.provider = { read: provider, write: provider };
} else if (provider) {
Expand Down
8 changes: 4 additions & 4 deletions src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export async function handleHttpError(response: Response): Promise<Response> {
}

// formally convert USD values to USDC values (* 1e6), using Usdc type alias.
export function usdc(usd: any): Usdc {
export function usdc(usd: unknown): Usdc {
return BigNumber.from(Math.floor(Number(usd) * 1e6)).toString();
}

Expand All @@ -25,14 +25,14 @@ export function int(value: BigNumber): Integer {
return value.toString();
}

export function chunkArray<T>(array: T[], size: number) {
export function chunkArray<T>(array: T[], size: number): T[][] {
if (size < 1) {
throw new Error(`Size needs to be positive: ${size}`);
}

let result = [];
const result = [];
for (let i = 0; i < array.length; i += size) {
let chunk = array.slice(i, i + size);
const chunk = array.slice(i, i + size);
result.push(chunk);
}
return result;
Expand Down
11 changes: 7 additions & 4 deletions src/interfaces/earnings.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { getAddress } from "@ethersproject/address";
import BigNumber from "bignumber.js";

Expand Down Expand Up @@ -225,7 +226,7 @@ describe("EarningsInterface", () => {

describe("assetsHistoricEarnings", () => {
const assetHistoricEarnings = createMockAssetHistoricEarnings();
let assetHistoricEarningsCacheFetchMock: jest.Mock<Promise<AssetHistoricEarnings[] | undefined>> = jest.fn();
const assetHistoricEarningsCacheFetchMock: jest.Mock<Promise<AssetHistoricEarnings[] | undefined>> = jest.fn();

beforeEach(() => {
(earningsInterface as any).assetHistoricEarningsCache.fetch = assetHistoricEarningsCacheFetchMock;
Expand All @@ -245,7 +246,7 @@ describe("EarningsInterface", () => {
});

describe("when there is no cached data", () => {
let assetHistoricEarningsMock: jest.Mock<Promise<AssetHistoricEarnings>> = jest.fn();
const assetHistoricEarningsMock: jest.Mock<Promise<AssetHistoricEarnings>> = jest.fn();
const assetsStatic = [createMockAssetStaticVaultV2()];
const assetHistoricEarnings = createMockAssetHistoricEarnings();

Expand All @@ -269,7 +270,9 @@ describe("EarningsInterface", () => {
});
});

describe("assetHistoricEarnings", () => {});
// eslint-disable-next-line @typescript-eslint/no-empty-function
describe.skip("assetHistoricEarnings", () => {});

describe("accountHistoricEarnings", () => {});
// eslint-disable-next-line @typescript-eslint/no-empty-function
describe.skip("accountHistoricEarnings", () => {});
});
19 changes: 10 additions & 9 deletions src/interfaces/earnings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class EarningsInterface<C extends ChainId> extends ServiceInterface<C> {
* @deprecated
* Not able to be accurately calculated by the subgraph, this functionality will be removed in a future version
*/
async protocolEarnings(): Promise<String> {
async protocolEarnings(): Promise<string> {
const response = await this.yearn.services.subgraph.fetchQuery<ProtocolEarningsResponse>(PROTOCOL_EARNINGS);

let result = BigZero;
Expand Down Expand Up @@ -172,7 +172,7 @@ export class EarningsInterface<C extends ChainId> extends ServiceInterface<C> {
this.chainId
);

async assetsHistoricEarnings(fromDaysAgo: number = 30): Promise<AssetHistoricEarnings[]> {
async assetsHistoricEarnings(fromDaysAgo = 30): Promise<AssetHistoricEarnings[]> {
if (fromDaysAgo === 30) {
const cached = await this.assetHistoricEarningsCache.fetch();
if (cached) {
Expand All @@ -189,7 +189,7 @@ export class EarningsInterface<C extends ChainId> extends ServiceInterface<C> {
assetAddresses.map(async address => this.assetHistoricEarnings(address, fromDaysAgo, latestBlockNumber))
);

let result = [];
const result = [];

for (const resolvedPromise of resolvedPromises) {
if (resolvedPromise.status === "fulfilled") {
Expand Down Expand Up @@ -225,6 +225,7 @@ export class EarningsInterface<C extends ChainId> extends ServiceInterface<C> {
.reverse()
.map(day => blockNumber - day * this.blocksPerDay());

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const response = await this.yearn.services.subgraph.fetchQuery<any>(ASSET_HISTORIC_EARNINGS(blocks), {
id: vault
});
Expand Down Expand Up @@ -312,7 +313,7 @@ export class EarningsInterface<C extends ChainId> extends ServiceInterface<C> {
balanceShares: BigNumber;
}

let snapshotTimeline: AccountSnapshot[] = [];
const snapshotTimeline: AccountSnapshot[] = [];

const updates = vaultPositions
.flatMap(vaultPosition => vaultPosition.updates)
Expand Down Expand Up @@ -374,9 +375,9 @@ export class EarningsInterface<C extends ChainId> extends ServiceInterface<C> {
const balanceTokens = snapshot.balanceShares
.multipliedBy(new BigNumber(vaultDayDatum.pricePerShare))
.dividedBy(new BigNumber(10 ** token.decimals));
let positives = balanceTokens.plus(snapshot.withdrawals).plus(snapshot.tokensSent);
let negatives = snapshot.deposits.plus(snapshot.tokensReceived);
let earnings = positives.minus(negatives);
const positives = balanceTokens.plus(snapshot.withdrawals).plus(snapshot.tokensSent);
const negatives = snapshot.deposits.plus(snapshot.tokensReceived);
const earnings = positives.minus(negatives);

const amountUsdc = usdcPrice.multipliedBy(earnings).dividedBy(new BigNumber(10).pow(token.decimals));

Expand Down Expand Up @@ -412,8 +413,8 @@ export class EarningsInterface<C extends ChainId> extends ServiceInterface<C> {
return new BigNumber(tokenUsdcPrice).multipliedBy(tokenAmount).div(10 ** decimals);
}

private getDate(daysAgo: number) {
let date = new Date();
private getDate(daysAgo: number): Date {
const date = new Date();
date.setDate(date.getDate() - daysAgo);
return date;
}
Expand Down
15 changes: 8 additions & 7 deletions src/interfaces/simulation.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Contract } from "@ethersproject/contracts";
import { JsonRpcSigner } from "@ethersproject/providers";

Expand All @@ -19,7 +20,7 @@ const zapOutApprovalTransactionMock = jest.fn(() => Promise.resolve({ from: "0x0
const getNormalizedValueUsdcMock = jest.fn(() => Promise.resolve("10"));
const zapInMock = jest.fn(() => Promise.resolve(true));
const zapOutMock = jest.fn(() => Promise.resolve(true));
const partnerEncodeDepositMock = jest.fn().mockReturnValue("");
const partnerEncodeDepositMock = jest.fn().mockReturnValue("encodedInputData");
const partnerIsAllowedMock = jest.fn().mockReturnValue(true);

jest.mock("../services/partner", () => ({
Expand All @@ -36,27 +37,27 @@ jest.mock("../vault", () => ({
token: tokenMock,
decimals: decimalsMock,
pricePerShare: pricePerShareMock,
encodeDeposit: jest.fn().mockReturnValue(Promise.resolve(""))
encodeDeposit: jest.fn().mockReturnValue(Promise.resolve("encodeDeposit"))
})),
YearnVaultContract: jest.fn().mockImplementation(() => ({
token: tokenMock,
decimals: decimalsMock,
pricePerShare: pricePerShareMock,
encodeDeposit: jest.fn().mockReturnValue("")
encodeDeposit: jest.fn().mockReturnValue("encodeDeposit")
}))
}));

const SignerMock = JsonRpcSigner as jest.Mocked<typeof JsonRpcSigner>;

const buildSignerMock = (balance = 1, transactionCount = 1) => {
const buildSignerMock = (balance = 1, transactionCount = 1): any => {
const getBalanceMock = jest.fn().mockImplementation(() => Promise.resolve(balance));

const getTransactionCountMock = jest.fn().mockImplementation(() => Promise.resolve(transactionCount));

const signer = new SignerMock("0x00", "provider" as any) as any;
signer.getBalance = getBalanceMock;
signer.getTransactionCount = getTransactionCountMock;
signer.getSigner = () => signer;
signer.getSigner = (): any => signer;
return signer;
};

Expand Down Expand Up @@ -258,7 +259,7 @@ describe("Simulation interface", () => {
expect(executeSimulationWithReSimulationOnFailureSpy).toHaveBeenCalledTimes(1);
expect(partnerEncodeDepositMock).toHaveBeenCalledTimes(0);
expect(simulateVaultInteractionSpy).toHaveBeenCalledTimes(1);
expect(simulateVaultInteractionSpy).toHaveBeenCalledWith("0x000", "0x0000", "", "0x0000", {
expect(simulateVaultInteractionSpy).toHaveBeenCalledWith("0x000", "0x0000", "encodeDeposit", "0x0000", {
forkId: undefined,
root: undefined,
save: undefined,
Expand All @@ -279,7 +280,7 @@ describe("Simulation interface", () => {
expect(executeSimulationWithReSimulationOnFailureSpy).toHaveBeenCalledTimes(1);
expect(partnerEncodeDepositMock).toHaveBeenCalledTimes(1);
expect(simulateVaultInteractionSpy).toHaveBeenCalledTimes(1);
expect(simulateVaultInteractionSpy).toHaveBeenCalledWith("0x000", "0x00001", "", "0x0000", {
expect(simulateVaultInteractionSpy).toHaveBeenCalledWith("0x000", "0x00001", "encodedInputData", "0x0000", {
forkId: undefined,
root: undefined,
save: undefined,
Expand Down
24 changes: 14 additions & 10 deletions src/interfaces/simulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export class SimulationInterface<T extends ChainId> extends ServiceInterface<T>
): Promise<TransactionOutcome> {
const signer = this.ctx.provider.write.getSigner(from);
const zapProtocol = PickleJars.includes(toVault) ? ZapProtocol.PICKLE : ZapProtocol.YEARN;
let vaultContract =
const vaultContract =
zapProtocol === ZapProtocol.PICKLE
? new PickleJarContract(toVault, signer)
: new YearnVaultContract(toVault, signer);
Expand Down Expand Up @@ -85,7 +85,7 @@ export class SimulationInterface<T extends ChainId> extends ServiceInterface<T>
: undefined;
options.root = approvalTransactionId;

simulateDeposit = (save: boolean) => {
simulateDeposit = (save: boolean): Promise<TransactionOutcome> => {
options.save = save;
return this.zapIn(
from,
Expand All @@ -110,7 +110,7 @@ export class SimulationInterface<T extends ChainId> extends ServiceInterface<T>
: undefined;
options.root = approvalTransactionId;

simulateDeposit = (save: boolean) => {
simulateDeposit = (save: boolean): Promise<TransactionOutcome> => {
options.save = save;
return this.directDeposit(from, sellToken, amount, toVault, vaultContract, options);
};
Expand Down Expand Up @@ -165,12 +165,12 @@ export class SimulationInterface<T extends ChainId> extends ServiceInterface<T>

options.root = approvalSimulationId;

simulateWithdrawal = (save: boolean) => {
simulateWithdrawal = (save: boolean): Promise<TransactionOutcome> => {
options.save = save;
return this.zapOut(from, toToken, underlyingToken, amount, fromVault, needsApproving, options);
};
} else {
simulateWithdrawal = (save: boolean) => {
simulateWithdrawal = (save: boolean): Promise<TransactionOutcome> => {
options.save = save;
return this.directWithdraw(from, toToken, amount, fromVault, vaultContract, options);
};
Expand Down Expand Up @@ -230,9 +230,13 @@ export class SimulationInterface<T extends ChainId> extends ServiceInterface<T>
options: SimulationOptions
): Promise<TransactionOutcome> {
const encodedInputData = await (this.shouldUsePartnerService(toVault)
? this.yearn.services.partner!.encodeDeposit(toVault, amount)
? this.yearn.services.partner?.encodeDeposit(toVault, amount)
: vaultContract.encodeDeposit(amount));

if (!encodedInputData) {
throw new Error("directDeposit#encodeDeposit failed");
}

const partnerAddress = await this.yearn.services.partner?.address;
const addressToDeposit = (this.shouldUsePartnerService(toVault) && partnerAddress) || toVault;

Expand Down Expand Up @@ -404,7 +408,7 @@ export class SimulationInterface<T extends ChainId> extends ServiceInterface<T>
throw new PriceFetchingError("error fetching price", PriceFetchingError.FETCHING_PRICE_ORACLE);
});

let result: TransactionOutcome = {
const result: TransactionOutcome = {
sourceTokenAddress: fromVault,
sourceTokenAmount: amount,
targetTokenAddress: toToken,
Expand Down Expand Up @@ -443,9 +447,9 @@ export class SimulationInterface<T extends ChainId> extends ServiceInterface<T>
options.gasLimit = zapOutParams.gas;
}

const tokensReceived = await (async () => {
const tokensReceived = await (async (): Promise<string> => {
if (zapToken === ZeroAddress) {
let response: SimulationResponse = await this.simulationExecutor.makeSimulationRequest(
const response: SimulationResponse = await this.simulationExecutor.makeSimulationRequest(
from,
zapOutParams.to,
zapOutParams.data,
Expand Down Expand Up @@ -477,7 +481,7 @@ export class SimulationInterface<T extends ChainId> extends ServiceInterface<T>

const conversionRate = new BigNumber(zapOutAmountUsdc).div(new BigNumber(soldAssetAmountUsdc)).toNumber();

let result: TransactionOutcome = {
const result: TransactionOutcome = {
sourceTokenAddress: fromVault,
sourceTokenAmount: amount,
targetTokenAddress: toToken,
Expand Down
Loading

0 comments on commit f09019e

Please sign in to comment.