1
0
mirror of https://github.com/oceanprotocol-archive/squid-js.git synced 2024-02-02 15:31:51 +01:00

Fix linter errors.

This commit is contained in:
Pedro Gutiérrez 2019-03-21 03:17:36 +01:00 committed by Pedro Gutiérrez
parent ebb2308df7
commit 05ca0da57f
24 changed files with 98 additions and 97 deletions

View File

@ -26,7 +26,7 @@ describe("Consume Asset", () => {
}) })
// Accounts // Accounts
const instanceConfig = (<any>ocean).instanceConfig const instanceConfig = (ocean as any).instanceConfig
publisher = new Account("0x00Bd138aBD70e2F00903268F3Db08f2D25677C9e", instanceConfig) publisher = new Account("0x00Bd138aBD70e2F00903268F3Db08f2D25677C9e", instanceConfig)
publisher.setPassword("node0") publisher.setPassword("node0")
consumer = new Account("0x068Ed00cF0441e4829D9784fCBe7b9e26D4BD8d0", instanceConfig) consumer = new Account("0x068Ed00cF0441e4829D9784fCBe7b9e26D4BD8d0", instanceConfig)

View File

@ -26,7 +26,7 @@ describe("Consume Asset (Brizo)", () => {
}) })
// Accounts // Accounts
const instanceConfig = (<any>ocean).instanceConfig const instanceConfig = (ocean as any).instanceConfig
publisher = new Account("0x00Bd138aBD70e2F00903268F3Db08f2D25677C9e", instanceConfig) publisher = new Account("0x00Bd138aBD70e2F00903268F3Db08f2D25677C9e", instanceConfig)
publisher.setPassword("node0") publisher.setPassword("node0")
consumer = new Account("0x068Ed00cF0441e4829D9784fCBe7b9e26D4BD8d0", instanceConfig) consumer = new Account("0x068Ed00cF0441e4829D9784fCBe7b9e26D4BD8d0", instanceConfig)

View File

@ -22,7 +22,7 @@
"build:watch": "tsc -w", "build:watch": "tsc -w",
"doc": "typedoc --mode modules --exclude \"**/examples/**\" --out ./doc/ ./src/", "doc": "typedoc --mode modules --exclude \"**/examples/**\" --out ./doc/ ./src/",
"merge-coverages": "npx lcov-result-merger \"coverage/*/lcov.info\" coverage/lcov.info", "merge-coverages": "npx lcov-result-merger \"coverage/*/lcov.info\" coverage/lcov.info",
"report-coverage": "cat ./coverage/unit/lcov.info | codacy-coverage --token 71ef0d15f6f04ac29b31d704b28f866a", "report-coverage": "cat ./coverage/lcov.info | codacy-coverage --token 71ef0d15f6f04ac29b31d704b28f866a",
"run": "ts-node", "run": "ts-node",
"release": "./node_modules/release-it/bin/release-it.js --src.tagName='v%s' --github.release --npm.publish --non-interactive", "release": "./node_modules/release-it/bin/release-it.js --src.tagName='v%s' --github.release --npm.publish --non-interactive",
"release-minor": "./node_modules/release-it/bin/release-it.js minor --src.tagName='v%s' --github.release --npm.publish --non-interactive", "release-minor": "./node_modules/release-it/bin/release-it.js minor --src.tagName='v%s' --github.release --npm.publish --non-interactive",

View File

@ -23,10 +23,6 @@ export function generateIntantiableConfigFromConfig(config: Config): Partial<Ins
} }
export abstract class Instantiable { export abstract class Instantiable {
private _ocean: Ocean
private _web3: Web3
private _config: Config
private _logger: Logger
protected get ocean() { protected get ocean() {
if (!this._ocean) { if (!this._ocean) {
@ -65,6 +61,11 @@ export abstract class Instantiable {
return {ocean, web3, config, logger} return {ocean, web3, config, logger}
} }
public static async getInstance(...args: any[]): Promise<any>
public static async getInstance(config: InstantiableConfig): Promise<any> {
LoggerInstance.warn("getInstance() methods has needs to be added to child class.")
}
protected static setInstanceConfig<T extends Instantiable>(instance: T, {ocean, config, web3, logger}: InstantiableConfig) { protected static setInstanceConfig<T extends Instantiable>(instance: T, {ocean, config, web3, logger}: InstantiableConfig) {
instance._ocean = ocean instance._ocean = ocean
instance._config = config instance._config = config
@ -72,10 +73,16 @@ export abstract class Instantiable {
instance._logger = logger instance._logger = logger
} }
// tslint:disable-next-line
private _ocean: Ocean
// tslint:disable-next-line
private _web3: Web3
// tslint:disable-next-line
private _config: Config
// tslint:disable-next-line
private _logger: Logger
protected setInstanceConfig(config: InstantiableConfig) { protected setInstanceConfig(config: InstantiableConfig) {
Instantiable.setInstanceConfig(this, config) Instantiable.setInstanceConfig(this, config)
} }
public static async getInstance(...args: any[]): Promise<any>
public static async getInstance(config: InstantiableConfig): Promise<any> { }
} }

View File

@ -1,12 +1,14 @@
import ContractBase from "./contracts/ContractBase" import ContractBase from "./contracts/ContractBase"
interface EventEmitter { interface EventEmitter {
// tslint:disable-next-line
subscribe: Function subscribe: Function
// tslint:disable-next-line
unsubscribe: Function unsubscribe: Function
} }
export interface ContractEventSubscription { export interface ContractEventSubscription {
unsubscribe: Function unsubscribe: () => void
} }
export class ContractEvent { export class ContractEvent {
@ -17,8 +19,8 @@ export class ContractEvent {
private filter: {[key: string]: any}, private filter: {[key: string]: any},
) { } ) { }
subscribe(callback: (events: any[]) => void): ContractEventSubscription { public subscribe(callback: (events: any[]) => void): ContractEventSubscription {
const onEvent = async blockNumber => { const onEvent = async (blockNumber) => {
const events = await this.contract.getEventData(this.eventName, { const events = await this.contract.getEventData(this.eventName, {
filter: this.filter, filter: this.filter,
fromBlock: blockNumber, fromBlock: blockNumber,
@ -35,9 +37,9 @@ export class ContractEvent {
} }
} }
once(callback?: (events: any[]) => void) { public once(callback?: (events: any[]) => void) {
return new Promise(resolve => { return new Promise((resolve) => {
const subscription = this.subscribe(events => { const subscription = this.subscribe((events) => {
subscription.unsubscribe() subscription.unsubscribe()
if (callback) { if (callback) {
callback(events) callback(events)

View File

@ -3,17 +3,6 @@ import { Instantiable, InstantiableConfig } from "../Instantiable.abstract"
export default class ContractHandler extends Instantiable { export default class ContractHandler extends Instantiable {
constructor(config: InstantiableConfig) {
super()
this.setInstanceConfig(config)
}
private static contracts: Map<string, Contract> = new Map<string, Contract>()
private static getHash(what: string, networkId: number): string {
return `${what}/#${networkId}`
}
protected static getContract(what: string, networkId: number) { protected static getContract(what: string, networkId: number) {
return ContractHandler.contracts.get(this.getHash(what, networkId)) return ContractHandler.contracts.get(this.getHash(what, networkId))
} }
@ -26,6 +15,16 @@ export default class ContractHandler extends Instantiable {
return ContractHandler.contracts.has(this.getHash(what, networkId)) return ContractHandler.contracts.has(this.getHash(what, networkId))
} }
private static contracts: Map<string, Contract> = new Map<string, Contract>()
private static getHash(what: string, networkId: number): string {
return `${what}/#${networkId}`
}
constructor(config: InstantiableConfig) {
super()
this.setInstanceConfig(config)
}
public async get(what: string): Promise<Contract> { public async get(what: string): Promise<Contract> {
const where = (await this.ocean.keeper.getNetworkName()).toLowerCase() const where = (await this.ocean.keeper.getNetworkName()).toLowerCase()

View File

@ -4,21 +4,43 @@ import ContractBase from "./contracts/ContractBase"
import { Instantiable, InstantiableConfig } from "../Instantiable.abstract" import { Instantiable, InstantiableConfig } from "../Instantiable.abstract"
export class EventHandler extends Instantiable { export class EventHandler extends Instantiable {
get count() {
return this.events.size
}
private events = new Set<(blockNumber) => void>() private events = new Set<(blockNumber) => void>()
private lastBlock: number private lastBlock: number
private interval = 200 private interval = 200
private polling: boolean = false private polling: boolean = false
private lastTimeout: NodeJS.Timeout private lastTimeout: NodeJS.Timeout
get count() {
return this.events.size
}
constructor(config: InstantiableConfig) { constructor(config: InstantiableConfig) {
super() super()
this.setInstanceConfig(config) this.setInstanceConfig(config)
} }
public subscribe(callback: (blockNumber: number) => void) {
this.events.add(callback)
this.checkBlock()
return {
unsubscribe: () => this.unsubscribe(callback),
}
}
public unsubscribe(callback: (blockNumber: number) => void) {
this.events.delete(callback)
if (!this.count) {
clearTimeout(this.lastTimeout)
delete this.lastBlock
this.polling = false
}
}
public getEvent(contract: ContractBase, eventName: string, filter: {[key: string]: any}) {
return new ContractEvent(this, contract, eventName, filter)
}
private async checkBlock(isInterval?: boolean, n = 0) { private async checkBlock(isInterval?: boolean, n = 0) {
const blockNumber = await this.web3.eth.getBlockNumber() const blockNumber = await this.web3.eth.getBlockNumber()
@ -32,31 +54,9 @@ export class EventHandler extends Instantiable {
} }
if (this.lastBlock !== blockNumber) { if (this.lastBlock !== blockNumber) {
this.events.forEach(fn => fn(this.lastBlock + 1)) this.events.forEach((fn) => fn(this.lastBlock + 1))
this.lastBlock = blockNumber this.lastBlock = blockNumber
} }
this.lastTimeout = setTimeout(() => this.checkBlock(true, n++), this.interval) this.lastTimeout = setTimeout(() => this.checkBlock(true, n++), this.interval)
} }
public subscribe(callback: (number) => void) {
this.events.add(callback)
this.checkBlock()
return {
unsubscribe: () => this.unsubscribe(callback),
}
}
public unsubscribe(callback: (number) => void) {
this.events.delete(callback)
if (!this.count) {
clearTimeout(this.lastTimeout)
delete this.lastBlock
this.polling = false
}
}
public getEvent(contract: ContractBase, eventName: string, filter: {[key: string]: any}) {
return new ContractEvent(this, contract, eventName, filter)
}
} }

View File

@ -115,7 +115,7 @@ export class Keeper extends Instantiable {
* Helpers for contracts. * Helpers for contracts.
*/ */
public utils: { public utils: {
eventHandler: EventHandler eventHandler: EventHandler,
} }
/** /**

View File

@ -102,6 +102,13 @@ export default abstract class ContractBase extends Instantiable {
} }
} }
protected getEvent(eventName: string, filter: {[key: string]: any}) {
if (!this.contract.events[eventName]) {
throw new Error(`Event ${eventName} is not part of contract ${this.contractName}`)
}
return this.ocean.keeper.utils.eventHandler.getEvent(this, eventName, filter)
}
private searchMethod(methodName: string, args: any[] = []) { private searchMethod(methodName: string, args: any[] = []) {
const methods = this.contract.options.jsonInterface const methods = this.contract.options.jsonInterface
.map((method) => ({...method, signature: (method as any).signature})) .map((method) => ({...method, signature: (method as any).signature}))
@ -112,11 +119,4 @@ export default abstract class ContractBase extends Instantiable {
} }
return foundMethod return foundMethod
} }
protected getEvent(eventName: string, filter: {[key: string]: any}) {
if (!this.contract.events[eventName]) {
throw new Error(`Event ${eventName} is not part of contract ${this.contractName}`)
}
return this.ocean.keeper.utils.eventHandler.getEvent(this, eventName, filter)
}
} }

View File

@ -1,7 +1,6 @@
import ContractBase from "./ContractBase" import ContractBase from "./ContractBase"
import { InstantiableConfig } from "../../Instantiable.abstract" import { InstantiableConfig } from "../../Instantiable.abstract"
export default class GenericContract extends ContractBase { export default class GenericContract extends ContractBase {
public static async getInstance(config: InstantiableConfig, contractName: string): Promise<ContractBase> { public static async getInstance(config: InstantiableConfig, contractName: string): Promise<ContractBase> {

View File

@ -2,7 +2,6 @@ import ContractBase from "../ContractBase"
import { zeroX } from "../../../utils" import { zeroX } from "../../../utils"
import { InstantiableConfig } from "../../../Instantiable.abstract" import { InstantiableConfig } from "../../../Instantiable.abstract"
export enum TemplateState { export enum TemplateState {
Uninitialized = 0, Uninitialized = 0,
Proposed = 1, Proposed = 1,

View File

@ -7,7 +7,11 @@ import { InstantiableConfig } from "../../../Instantiable.abstract"
export abstract class AgreementTemplate extends ContractBase { export abstract class AgreementTemplate extends ContractBase {
public static async getInstance(config: InstantiableConfig, conditionName: string, templateClass: any): Promise<AgreementTemplate & any> { public static async getInstance(
config: InstantiableConfig,
conditionName: string,
templateClass: any,
): Promise<AgreementTemplate & any> {
const condition: AgreementTemplate = new (templateClass as any)(conditionName) const condition: AgreementTemplate = new (templateClass as any)(conditionName)
await condition.init(config) await condition.init(config)
return condition return condition

View File

@ -252,7 +252,7 @@ export class OceanAssets extends Instantiable {
try { try {
await paymentFlow await paymentFlow
} catch(e) { } catch (e) {
throw new Error("Error paying the asset.") throw new Error("Error paying the asset.")
} }

View File

@ -5,7 +5,6 @@ import { Ocean } from "./ocean/Ocean"
import { LoggerInstance as Logger} from "./utils/Logger" import { LoggerInstance as Logger} from "./utils/Logger"
import WebServiceConnectorProvider from "./utils/WebServiceConnectorProvider" import WebServiceConnectorProvider from "./utils/WebServiceConnectorProvider"
import Keeper from "./keeper/Keeper" import Keeper from "./keeper/Keeper"
import EventListener from "./keeper/EventListener"
import * as templates from "./keeper/contracts/templates" import * as templates from "./keeper/contracts/templates"
import * as conditions from "./keeper/contracts/conditions" import * as conditions from "./keeper/contracts/conditions"

View File

@ -1,7 +1,6 @@
import * as Web3 from "web3" import * as Web3 from "web3"
import LoggerInstance from "./Logger" import LoggerInstance from "./Logger"
export async function signText(web3: Web3, text: string, publicKey: string, password?: string): Promise<string> { export async function signText(web3: Web3, text: string, publicKey: string, password?: string): Promise<string> {
try { try {
return await web3.eth.personal.sign(text, publicKey, password) return await web3.eth.personal.sign(text, publicKey, password)

View File

@ -9,7 +9,7 @@ import WebServiceConnectorMock from "../mocks/WebServiceConnector.mock"
describe("Aquarius", () => { describe("Aquarius", () => {
const aquarius: Aquarius = new Aquarius(<any>{config}) const aquarius: Aquarius = new Aquarius({config} as any)
describe("#queryMetadata()", () => { describe("#queryMetadata()", () => {

View File

@ -7,6 +7,7 @@ import { Service } from "../../src/ddo/Service"
import * as signatureHelpers from "../../src/utils/SignatureHelpers" import * as signatureHelpers from "../../src/utils/SignatureHelpers"
import { Ocean } from "../../src/ocean/Ocean" import { Ocean } from "../../src/ocean/Ocean"
import config from "../config" import config from "../config"
import TestContractHandler from "../keeper/TestContractHandler"
import * as jsonDDO from "../testdata/ddo.json" import * as jsonDDO from "../testdata/ddo.json"
@ -166,6 +167,7 @@ describe("DDO", () => {
let web3: Web3 let web3: Web3
beforeEach(async () => { beforeEach(async () => {
await TestContractHandler.prepareContracts()
web3 = (await Ocean.getInstance(config) as any).web3 web3 = (await Ocean.getInstance(config) as any).web3
}) })

View File

@ -14,7 +14,7 @@ describe("ContractWrapperBase", () => {
await TestContractHandler.prepareContracts() await TestContractHandler.prepareContracts()
const ocean: Ocean = await Ocean.getInstance(config) const ocean: Ocean = await Ocean.getInstance(config)
accounts = await ocean.accounts.list() accounts = await ocean.accounts.list()
await wrappedContract.initMock((<any>ocean).instanceConfig) await wrappedContract.initMock((ocean as any).instanceConfig)
}) })
describe("#call()", () => { describe("#call()", () => {

View File

@ -15,7 +15,7 @@ describe("ContractEvent", () => {
beforeEach(async () => { beforeEach(async () => {
await TestContractHandler.prepareContracts() await TestContractHandler.prepareContracts()
ocean = await Ocean.getInstance(config) ocean = await Ocean.getInstance(config)
eventHandler = new EventHandler((<any>ocean).instanceConfig) eventHandler = new EventHandler((ocean as any).instanceConfig)
account = (await ocean.accounts.list())[0].getId() account = (await ocean.accounts.list())[0].getId()
executeTransaction = () => ocean.keeper.dispenser.requestTokens(10, account) executeTransaction = () => ocean.keeper.dispenser.requestTokens(10, account)
@ -27,8 +27,8 @@ describe("ContractEvent", () => {
let validResolve = false let validResolve = false
let subscription: ContractEventSubscription let subscription: ContractEventSubscription
const waitUntilEvent = new Promise(resolve => { const waitUntilEvent = new Promise((resolve) => {
subscription = event.subscribe(events => { subscription = event.subscribe((events) => {
assert.isDefined(events) assert.isDefined(events)
assert.lengthOf(events, 2) assert.lengthOf(events, 2)
if (validResolve) { if (validResolve) {
@ -42,7 +42,7 @@ describe("ContractEvent", () => {
executeTransaction(), executeTransaction(),
]) ])
await new Promise(_ => setTimeout(_, 2000)) await new Promise((_) => setTimeout(_, 2000))
validResolve = true validResolve = true
await Promise.all([ await Promise.all([
@ -63,7 +63,7 @@ describe("ContractEvent", () => {
let canBeRejected = false let canBeRejected = false
const waitUntilEvent = new Promise((resolve, reject) => { const waitUntilEvent = new Promise((resolve, reject) => {
event.once(events => { event.once((events) => {
if (canBeRejected) { if (canBeRejected) {
reject() reject()
} }
@ -73,7 +73,7 @@ describe("ContractEvent", () => {
await executeTransaction() await executeTransaction()
await new Promise(_ => setTimeout(_, 2000)) await new Promise((_) => setTimeout(_, 2000))
canBeRejected = true canBeRejected = true
await executeTransaction() await executeTransaction()
@ -87,7 +87,7 @@ describe("ContractEvent", () => {
const waitUntilEvent = event.once() const waitUntilEvent = event.once()
await new Promise(_ => setTimeout(_, 400)) await new Promise((_) => setTimeout(_, 400))
await executeTransaction() await executeTransaction()

View File

@ -3,12 +3,11 @@ import ContractHandler from "../../src/keeper/ContractHandler"
import { Ocean } from "../../src/ocean/Ocean" import { Ocean } from "../../src/ocean/Ocean"
import config from "../config" import config from "../config"
describe("ContractHandler", () => { describe("ContractHandler", () => {
let contractHandler: ContractHandler let contractHandler: ContractHandler
before(async () => { before(async () => {
const instanceConfig = (<any>await Ocean.getInstance(config)).instanceConfig const instanceConfig = (await Ocean.getInstance(config) as any).instanceConfig
contractHandler = new ContractHandler(instanceConfig) contractHandler = new ContractHandler(instanceConfig)
}) })

View File

@ -13,7 +13,7 @@ describe("EventHandler", () => {
before(async () => { before(async () => {
ocean = await Ocean.getInstance(config) ocean = await Ocean.getInstance(config)
eventHandler = new EventHandler((<any>ocean).instanceConfig) eventHandler = new EventHandler((ocean as any).instanceConfig)
}) })
afterEach(() => { afterEach(() => {
@ -24,22 +24,19 @@ describe("EventHandler", () => {
it("should subscribe to an event", async () => { it("should subscribe to an event", async () => {
const countBefore = eventHandler.count const countBefore = eventHandler.count
const subscription = eventHandler.subscribe(() => {}) const subscription = eventHandler.subscribe(() => null)
assert.isDefined(subscription) assert.isDefined(subscription)
const countAfter = eventHandler.count const countAfter = eventHandler.count
assert.equal(countBefore + 1, countAfter, "The event seems not added.") assert.equal(countBefore + 1, countAfter, "The event seems not added.")
try { subscription.unsubscribe()
// Not important in this test
subscription.unsubscribe()
} catch(e) { }
}) })
it("should unsubscribe using the subscription", async () => { it("should unsubscribe using the subscription", async () => {
const countBefore = eventHandler.count const countBefore = eventHandler.count
const subscription = eventHandler.subscribe(() => {}) const subscription = eventHandler.subscribe(() => null)
assert.isDefined(subscription) assert.isDefined(subscription)
subscription.unsubscribe() subscription.unsubscribe()
@ -52,7 +49,7 @@ describe("EventHandler", () => {
describe("#unsubscribe()", () => { describe("#unsubscribe()", () => {
it("should unsubscribe from an event", async () => { it("should unsubscribe from an event", async () => {
const countBefore = eventHandler.count const countBefore = eventHandler.count
const callback = () => {} const callback = () => null
eventHandler.subscribe(callback) eventHandler.subscribe(callback)
eventHandler.unsubscribe(callback) eventHandler.unsubscribe(callback)
@ -71,19 +68,16 @@ describe("EventHandler", () => {
const subscription = eventHandler.subscribe(callbackSpy) const subscription = eventHandler.subscribe(callbackSpy)
await new Promise(_ => setTimeout(_, 300)) await new Promise((_) => setTimeout(_, 300))
expect(callbackSpy).not.to.has.been.called() expect(callbackSpy).not.to.has.been.called()
blockNumber++ blockNumber++
await new Promise(_ => setTimeout(_, 300)) await new Promise((_) => setTimeout(_, 300))
expect(callbackSpy).to.has.been.called.with(blockNumber) expect(callbackSpy).to.has.been.called.with(blockNumber)
try { subscription.unsubscribe()
// Not important in this test
subscription.unsubscribe()
} catch(e) { }
}) })
}) })
}) })

View File

@ -6,8 +6,6 @@ import config from "../config"
export default class TestContractHandler extends ContractHandler { export default class TestContractHandler extends ContractHandler {
private static networkId: number
public static async prepareContracts() { public static async prepareContracts() {
const web3 = Web3Provider.getWeb3(config) const web3 = Web3Provider.getWeb3(config)
const deployerAddress = (await web3.eth.getAccounts())[0] const deployerAddress = (await web3.eth.getAccounts())[0]
@ -17,6 +15,8 @@ export default class TestContractHandler extends ContractHandler {
await TestContractHandler.deployContracts(deployerAddress) await TestContractHandler.deployContracts(deployerAddress)
} }
private static networkId: number
private static async deployContracts(deployerAddress: string) { private static async deployContracts(deployerAddress: string) {
Logger.log("Trying to deploy contracts") Logger.log("Trying to deploy contracts")

View File

@ -4,7 +4,6 @@ import config from "../../config"
import TestContractHandler from "../TestContractHandler" import TestContractHandler from "../TestContractHandler"
import { Ocean } from "../../../src/ocean/Ocean" import { Ocean } from "../../../src/ocean/Ocean"
let condition: EscrowAccessSecretStoreTemplate let condition: EscrowAccessSecretStoreTemplate
describe("EscrowAccessSecretStoreTemplate", () => { describe("EscrowAccessSecretStoreTemplate", () => {

View File

@ -42,7 +42,6 @@ describe("SignatureHelpers", () => {
describe("#verifyText", () => { describe("#verifyText", () => {
it("should recover the privateKey of a signed message", async () => { it("should recover the privateKey of a signed message", async () => {
const web3 = Web3Provider.getWeb3()
const personalRecoverSpy = spy.on(web3.eth.personal, "ecRecover", () => publicKey) const personalRecoverSpy = spy.on(web3.eth.personal, "ecRecover", () => publicKey)
const verifiedPublicKey = await verifyText(web3, text, signature) const verifiedPublicKey = await verifyText(web3, text, signature)