From 5dbc86868669ea9e78ffd480a333eb058f952bc1 Mon Sep 17 00:00:00 2001 From: Sebastian Gerske Date: Tue, 2 Oct 2018 10:06:26 +0200 Subject: [PATCH] new linter styles --- src/Ocean.ts | 51 ++++++----- src/Tribe.ts | 14 +-- src/keeper/Auth.ts | 24 ++--- src/keeper/ContractHandler.ts | 74 ++++++++-------- src/keeper/ContractWrapperBase.ts | 28 +++--- src/keeper/EventListener.ts | 24 ++--- src/keeper/Keeper.ts | 34 ++++---- src/keeper/Market.ts | 40 ++++----- src/keeper/Token.ts | 25 +++--- src/keeper/Web3Helper.ts | 61 +++++++------ src/metadata.ts | 30 +++---- src/models/Asset.ts | 6 +- src/models/Config.ts | 9 +- src/models/Order.ts | 14 +-- src/ocean/Asset.ts | 10 +-- src/ocean/Order.ts | 140 +++++++++++++++--------------- src/squid.ts | 6 +- src/utils/Logger.ts | 12 +-- test/Keeper.test.ts | 30 +++---- tslint.json | 6 +- 20 files changed, 319 insertions(+), 319 deletions(-) diff --git a/src/Ocean.ts b/src/Ocean.ts index fe2999b..2d089cc 100644 --- a/src/Ocean.ts +++ b/src/Ocean.ts @@ -1,45 +1,44 @@ -import Keeper from "./keeper/Keeper"; -import Web3Helper from "./keeper/Web3Helper"; -import MetaData from "./metadata"; -import Config from "./models/Config"; -import Asset from "./ocean/Asset"; -import Order from "./ocean/Order"; +import Keeper from "./keeper/Keeper" +import Web3Helper from "./keeper/Web3Helper" +import MetaData from "./metadata" +import Config from "./models/Config" +import Asset from "./ocean/Asset" +import Order from "./ocean/Order" export default class Ocean { public static async getInstance(config) { - const ocean = new Ocean(config); - ocean.keeper = await Keeper.getInstance(config, ocean.helper); - ocean.order = new Order(ocean.keeper); - ocean.asset = new Asset(ocean.keeper); - - return ocean; + const ocean = new Ocean(config) + ocean.keeper = await Keeper.getInstance(config, ocean.helper) + ocean.order = new Order(ocean.keeper) + ocean.asset = new Asset(ocean.keeper) + return ocean } - public order: Order; - public asset: Asset; - public helper: Web3Helper; - public metadata: MetaData; + public order: Order + public asset: Asset + public helper: Web3Helper + public metadata: MetaData - private keeper: Keeper; - private config: Config; + private keeper: Keeper + private config: Config private constructor(config: Config) { - this.config = config; + this.config = config - this.helper = new Web3Helper(config); - this.metadata = new MetaData(config); + this.helper = new Web3Helper(config) + this.metadata = new MetaData(config) } // Transactions with gas cost public async requestTokens(amount: number, receiver: string): Promise { - return this.keeper.market.requestTokens(amount, receiver); + return this.keeper.market.requestTokens(amount, receiver) } public async getAccounts() { - const {token} = this.keeper; - const {helper} = this; + const {token} = this.keeper + const {helper} = this return Promise.all((await helper.getAccounts()).map(async (account: string) => { // await ocean.market.requestTokens(account, 1000) @@ -49,7 +48,7 @@ export default class Ocean { eth: await token.getEthBalance(account), ocn: await token.getTokenBalance(account), }, - }; - })); + } + })) } } diff --git a/src/Tribe.ts b/src/Tribe.ts index 8e296e1..9060c4a 100644 --- a/src/Tribe.ts +++ b/src/Tribe.ts @@ -1,30 +1,30 @@ -import Web3Helper from "./keeper/Web3Helper"; +import Web3Helper from "./keeper/Web3Helper" export default class Tribe { public static getInstance(web3Helper: Web3Helper) { - return new Tribe(web3Helper); + return new Tribe(web3Helper) } - private web3Helper: Web3Helper; + private web3Helper: Web3Helper private constructor(web3Helper: Web3Helper) { - this.web3Helper = web3Helper; + this.web3Helper = web3Helper } // did ddo for tribes/marketplaces public registerTribe() { - return ""; + return "" } public tribessList() { - return ""; + return "" } public resolveTribeDID() { // verify DDO - return "DDO"; + return "DDO" } } diff --git a/src/keeper/Auth.ts b/src/keeper/Auth.ts index b155dfe..f504ef6 100644 --- a/src/keeper/Auth.ts +++ b/src/keeper/Auth.ts @@ -1,38 +1,38 @@ -import BigNumber from "bignumber.js"; -import Asset from "../models/Asset"; -import Config from "../models/Config"; -import ContractBaseWrapper from "./ContractWrapperBase"; -import Web3Helper from "./Web3Helper"; +import BigNumber from "bignumber.js" +import Asset from "../models/Asset" +import Config from "../models/Config" +import ContractBaseWrapper from "./ContractWrapperBase" +import Web3Helper from "./Web3Helper" export default class OceanAuth extends ContractBaseWrapper { public static async getInstance(config: Config, web3Helper: Web3Helper) { - const auth = new OceanAuth(config, "OceanAuth", web3Helper); - await auth.init(); - return auth; + const auth = new OceanAuth(config, "OceanAuth", web3Helper) + await auth.init() + return auth } public async getOrderStatus(orderId: string): Promise { return this.contract.statusOfAccessRequest.call(orderId) - .then((status: BigNumber) => status.toNumber()); + .then((status: BigNumber) => status.toNumber()) } public async cancelAccessRequest(orderId: string, senderAddress: string) { return this.contract.cancelAccessRequest.send(orderId, { from: senderAddress, - }); + }) } public async getEncryptedAccessToken(orderId: string, senderAddress: string) { return this.contract.getEncryptedAccessToken.send(orderId, { from: senderAddress, - }); + }) } public async initiateAccessRequest(asset: Asset, publicKey: string, timeout, buyerAddress: string) { return this.contract.initiateAccessRequest.send( asset.assetId, asset.publisherId, publicKey, timeout, { from: buyerAddress, gas: this.config.defaultGas, - }); + }) } } diff --git a/src/keeper/ContractHandler.ts b/src/keeper/ContractHandler.ts index 2eda0d5..3620875 100644 --- a/src/keeper/ContractHandler.ts +++ b/src/keeper/ContractHandler.ts @@ -1,28 +1,28 @@ -import Contract from "web3"; -import Logger from "../utils/Logger"; -import Web3Helper from "./Web3Helper"; +import Contract from "web3" +import Logger from "../utils/Logger" +import Web3Helper from "./Web3Helper" -const contracts: Map = new Map(); +const contracts: Map = new Map() export default class ContractHandler { public static async get(what: string, web3Helper: Web3Helper) { - return contracts.get(what) || await ContractHandler.load(what, web3Helper); + return contracts.get(what) || await ContractHandler.load(what, web3Helper) } public static async deployContracts(web3Helper: Web3Helper) { - Logger.log("Deploying contracts"); + Logger.log("Deploying contracts") - const web3 = web3Helper.getWeb3(); + const web3 = web3Helper.getWeb3() - const deployerAddress = (await web3.eth.getAccounts())[0]; + const deployerAddress = (await web3.eth.getAccounts())[0] // deploy libs - const dll = await ContractHandler.deployContract(web3, "DLL", deployerAddress); - const attributeStore = await ContractHandler.deployContract(web3, "AttributeStore", deployerAddress); + const dll = await ContractHandler.deployContract(web3, "DLL", deployerAddress) + const attributeStore = await ContractHandler.deployContract(web3, "AttributeStore", deployerAddress) // deploy contracts - const token = await ContractHandler.deployContract(web3, "OceanToken", deployerAddress); + const token = await ContractHandler.deployContract(web3, "OceanToken", deployerAddress) const plcrVoting = await ContractHandler.deployContract(web3, "PLCRVoting", deployerAddress, { args: [token.options.address], tokens: [ @@ -32,35 +32,35 @@ export default class ContractHandler { name: "AttributeStore", address: attributeStore.options.address, }, ], - }); + }) const registry = await ContractHandler.deployContract(web3, "OceanRegistry", deployerAddress, { args: [token.options.address, plcrVoting.options.address], - }); + }) const market = await ContractHandler.deployContract(web3, "OceanMarket", deployerAddress, { args: [token.options.address, registry.options.address], - }); + }) const dispute = await ContractHandler.deployContract(web3, "OceanDispute", deployerAddress, { args: [market.options.address, registry.options.address, plcrVoting.options.address], - }); + }) const auth = await ContractHandler.deployContract(web3, "OceanAuth", deployerAddress, { args: [market.options.address, dispute.options.address], - }); + }) } private static async load(what: string, web3Helper: Web3Helper): Promise { - const where = (await web3Helper.getNetworkName()).toLowerCase(); - Logger.log("Loading", what, "from", where); + const where = (await web3Helper.getNetworkName()).toLowerCase() + Logger.log("Loading", what, "from", where) try { - const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${what}.${where}`); + const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${what}.${where}`) // Logger.log('Loaded artifact', artifact) - Logger.log("Getting instance of", what, "from", where, "at", artifact.address); - const web3 = web3Helper.getWeb3(); - const contract = new web3.eth.Contract(artifact.abi, artifact.address); - Logger.log("Loaded", what, "from", where); - contracts.set(what, contract); - return contracts.get(what); + Logger.log("Getting instance of", what, "from", where, "at", artifact.address) + const web3 = web3Helper.getWeb3() + const contract = new web3.eth.Contract(artifact.abi, artifact.address) + Logger.log("Loaded", what, "from", where) + contracts.set(what, contract) + return contracts.get(what) } catch (err) { - Logger.error("Failed to load", what, "from", where, err); + Logger.error("Failed to load", what, "from", where, err) } } @@ -70,21 +70,21 @@ export default class ContractHandler { bytecode = bytecode.replace( new RegExp(`_+${token.name}_+`, "g"), - token.address.replace("0x", "")); + token.address.replace("0x", "")) } // Logger.log(bytecode); - return bytecode.toString(); + return bytecode.toString() } private static async deployContract(web3, name, from, params?): Promise { - let contractInstance; + let contractInstance try { - Logger.log("Deploying", name); + Logger.log("Deploying", name) - const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${name}.development.json`); - const tempContract = new web3.eth.Contract(artifact.abi, artifact.address); + const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${name}.development.json`) + const tempContract = new web3.eth.Contract(artifact.abi, artifact.address) contractInstance = await tempContract.deploy({ data: params && params.tokens ? ContractHandler.replaceTokens(artifact.bytecode.toString(), params.tokens) : @@ -94,14 +94,14 @@ export default class ContractHandler { from, gas: 3000000, gasPrice: 10000000000, - }); - contracts.set(name, contractInstance); + }) + contracts.set(name, contractInstance) // Logger.log("Deployed", name, "at", contractInstance.options.address); } catch (err) { - Logger.error("Deployment failed for", name, "with params", JSON.stringify(params, null, 2), err.message); - throw err; + Logger.error("Deployment failed for", name, "with params", JSON.stringify(params, null, 2), err.message) + throw err } - return contractInstance; + return contractInstance } } diff --git a/src/keeper/ContractWrapperBase.ts b/src/keeper/ContractWrapperBase.ts index 748746b..cc1110f 100644 --- a/src/keeper/ContractWrapperBase.ts +++ b/src/keeper/ContractWrapperBase.ts @@ -1,33 +1,33 @@ -import Config from "../models/Config"; -import ContractHandler from "./ContractHandler"; -import Web3Helper from "./Web3Helper"; +import Config from "../models/Config" +import ContractHandler from "./ContractHandler" +import Web3Helper from "./Web3Helper" export default class ContractWrapperBase { - protected contract: any = null; - protected config: Config; - protected web3Helper: Web3Helper; + protected contract: any = null + protected config: Config + protected web3Helper: Web3Helper - private contractName: string; + private contractName: string constructor(config: Config, contractName: string, web3Helper: Web3Helper) { - this.config = config; - this.contractName = contractName; - this.web3Helper = web3Helper; + this.config = config + this.contractName = contractName + this.web3Helper = web3Helper } public async init() { - this.contract = await ContractHandler.get(this.contractName, this.web3Helper); + this.contract = await ContractHandler.get(this.contractName, this.web3Helper) } public getAddress() { - return this.contract.address; + return this.contract.address } public getEvent(name: string) { if (!this.contract.events[name]) { - throw new Error(`Event ${name} not found on contract ${this.contractName}`); + throw new Error(`Event ${name} not found on contract ${this.contractName}`) } - return this.contract.events[name]; + return this.contract.events[name] } } diff --git a/src/keeper/EventListener.ts b/src/keeper/EventListener.ts index f667f6a..5080147 100644 --- a/src/keeper/EventListener.ts +++ b/src/keeper/EventListener.ts @@ -1,30 +1,30 @@ -import Logger from "../utils/Logger"; +import Logger from "../utils/Logger" export default class EventListener { public static async listenOnce(event: any, eventName: string): Promise { return new Promise((resolve, reject) => { event.watch((error: any, result: any) => { - event.stopWatching(); + event.stopWatching() if (error) { - Logger.log(`Error in keeper ${eventName} event: `, error); - return reject(error); + Logger.log(`Error in keeper ${eventName} event: `, error) + return reject(error) } - resolve(result); - }); - }); + resolve(result) + }) + }) } public static getEvents(event: any): Promise { return new Promise((resolve, reject) => { event.get((error: any, logs: any[]) => { if (error) { - reject(error); - throw new Error(error); + reject(error) + throw new Error(error) } else { - resolve(logs); + resolve(logs) } - }); - }); + }) + }) } } diff --git a/src/keeper/Keeper.ts b/src/keeper/Keeper.ts index 1008893..3f8281a 100644 --- a/src/keeper/Keeper.ts +++ b/src/keeper/Keeper.ts @@ -1,31 +1,31 @@ -import Config from "../models/Config"; -import OceanAuth from "./Auth"; -import OceanMarket from "./Market"; -import OceanToken from "./Token"; -import Web3Helper from "./Web3Helper"; +import Config from "../models/Config" +import OceanAuth from "./Auth" +import OceanMarket from "./Market" +import OceanToken from "./Token" +import Web3Helper from "./Web3Helper" export default class Keeper { public static async getInstance(config: Config, helper: Web3Helper) { - const contracts = new Keeper(config, helper); + const contracts = new Keeper(config, helper) - contracts.market = await OceanMarket.getInstance(config, helper); - contracts.auth = await OceanAuth.getInstance(config, helper); - contracts.token = await OceanToken.getInstance(config, helper); + contracts.market = await OceanMarket.getInstance(config, helper) + contracts.auth = await OceanAuth.getInstance(config, helper) + contracts.token = await OceanToken.getInstance(config, helper) - return contracts; + return contracts } - public web3Helper: Web3Helper; - public token: OceanToken; - public market: OceanMarket; - public auth: OceanAuth; + public web3Helper: Web3Helper + public token: OceanToken + public market: OceanMarket + public auth: OceanAuth - private config: Config; + private config: Config private constructor(config: Config, helper: Web3Helper) { - this.config = config; - this.web3Helper = helper; + this.config = config + this.web3Helper = helper } } diff --git a/src/keeper/Market.ts b/src/keeper/Market.ts index 4964fb0..476c9bb 100644 --- a/src/keeper/Market.ts +++ b/src/keeper/Market.ts @@ -1,56 +1,56 @@ -import Asset from "../models/Asset"; -import Config from "../models/Config"; -import Order from "../models/Order"; -import Logger from "../utils/Logger"; -import ContractWrapperBase from "./ContractWrapperBase"; -import Web3Helper from "./Web3Helper"; +import Asset from "../models/Asset" +import Config from "../models/Config" +import Order from "../models/Order" +import Logger from "../utils/Logger" +import ContractWrapperBase from "./ContractWrapperBase" +import Web3Helper from "./Web3Helper" export default class OceanMarket extends ContractWrapperBase { public static async getInstance(config: Config, web3Helper: Web3Helper) { - const market = new OceanMarket(config, "OceanMarket", web3Helper); - await market.init(); - return market; + const market = new OceanMarket(config, "OceanMarket", web3Helper) + await market.init() + return market } // call functions (costs no gas) public async isAssetActive(assetId: string): Promise { - return this.contract.methods.checkAsset(assetId).call; + return this.contract.methods.checkAsset(assetId).call } public async verifyOrderPayment(orderId: string): Promise { - return this.contract.methods.verifyPaymentReceived(orderId).call; + return this.contract.methods.verifyPaymentReceived(orderId).call } public async getAssetPrice(assetId: string): Promise { - return this.contract.methods.getAssetPrice(assetId).call().then((result) => result.toNumber()); + return this.contract.methods.getAssetPrice(assetId).call().then((result) => result.toNumber()) } public async requestTokens(amount: number, receiverAddress: string): Promise { return this.contract.methods.requestTokens(amount).send({ from: receiverAddress, - }); + }) } public async registerAsset(name: string, description: string, price: number, publisherAddress: string): Promise { - const assetId = await this.contract.methods.generateId(name + description).call(); - Logger.log("Registering: ", assetId); + const assetId = await this.contract.methods.generateId(name + description).call() + Logger.log("Registering: ", assetId) const result = await this.contract.methods.register(assetId, price).send({ from: publisherAddress, gas: this.config.defaultGas, }, - ); - Logger.log("Registered: ", result); - return assetId; + ) + Logger.log("Registered: ", result) + return assetId } public async payAsset(asset: Asset, order: Order, buyerAddress: string): Promise { - Logger.log("Sending payment"); + Logger.log("Sending payment") return this.contract.methods.sendPayment(order.id, asset.publisherId, asset.price, order.timeout).send({ from: buyerAddress, gas: this.config.defaultGas, - }); + }) } } diff --git a/src/keeper/Token.ts b/src/keeper/Token.ts index c8ca9a8..f254026 100644 --- a/src/keeper/Token.ts +++ b/src/keeper/Token.ts @@ -1,18 +1,17 @@ -import Config from "../models/Config"; -import Logger from "../utils/Logger"; -import ContractBaseWrapper from "./ContractWrapperBase"; -import Web3Helper from "./Web3Helper"; +import Config from "../models/Config" +import ContractBaseWrapper from "./ContractWrapperBase" +import Web3Helper from "./Web3Helper" export default class OceanToken extends ContractBaseWrapper { public static async getInstance(config: Config, web3Helper: Web3Helper) { - const token = new OceanToken(config, "OceanToken", web3Helper); - await token.init(); - return token; + const token = new OceanToken(config, "OceanToken", web3Helper) + await token.init() + return token } public async getTokenBalance(accountAddress: string) { - return this.contract.methods.balanceOf(accountAddress).call(); + return this.contract.methods.balanceOf(accountAddress).call() } public async getEthBalance(account: string): Promise { @@ -20,18 +19,18 @@ export default class OceanToken extends ContractBaseWrapper { // Logger.log("getting balance for", account); this.web3Helper.getWeb3().eth.getBalance(account, "latest", (err: any, balance: number) => { if (err) { - return reject(err); + return reject(err) } // Logger.log("balance", balance); - resolve(balance); - }); - }); + resolve(balance) + }) + }) } public async approve(marketAddress: string, price: number, buyerAddress: string) { return this.contract.methods.approve(marketAddress, price).send({ from: buyerAddress, gas: this.config.defaultGas, - }); + }) } } diff --git a/src/keeper/Web3Helper.ts b/src/keeper/Web3Helper.ts index cc60623..508765d 100644 --- a/src/keeper/Web3Helper.ts +++ b/src/keeper/Web3Helper.ts @@ -1,72 +1,71 @@ -import Web3 = require("web3"); -import Config from "../models/Config"; -import Logger from "../utils/Logger"; +import Web3 = require("web3") +import Config from "../models/Config" export default class Web3Helper { - private web3: Web3; + private web3: Web3 public constructor(config: Config) { - const web3Provider = config.web3Provider || new Web3.providers.HttpProvider(config.nodeUri); - this.web3 = new Web3(web3Provider); + const web3Provider = config.web3Provider || new Web3.providers.HttpProvider(config.nodeUri) + this.web3 = new Web3(web3Provider) } public getWeb3() { - return this.web3; + return this.web3 } public getCurrentProvider() { - return this.web3.currentProvider; + return this.web3.currentProvider } public async getAccounts(): Promise { return new Promise((resolve, reject) => { this.web3.eth.getAccounts((err: any, accounts: string[]) => { if (err) { - reject(err); - throw err; + reject(err) + throw err } - resolve(accounts); - }); - }); + resolve(accounts) + }) + }) } public async getNetworkName(): Promise { return new Promise((resolve, reject) => { - let network: string = "unknown"; + let network: string = "unknown" this.web3.eth.net.getId((err, networkId) => { if (err) { - reject(err); - throw err; + reject(err) + throw err } switch (networkId) { case 1: - network = "Main"; - break; + network = "Main" + break case 2: - network = "Morden"; - break; + network = "Morden" + break case 3: - network = "Ropsten"; - break; + network = "Ropsten" + break case 4: - network = "Rinkeby"; - break; + network = "Rinkeby" + break case 42: - network = "Kovan"; - break; + network = "Kovan" + break default: - network = "development"; + network = "development" } - resolve(network); - }); - }); + resolve(network) + }) + }) } // web3 wrappers public sign(accountAddress: string, message: string) { - return this.web3.eth.sign(accountAddress, message); + return this.web3.eth.sign(accountAddress, message) } } diff --git a/src/metadata.ts b/src/metadata.ts index ee81690..1acee86 100644 --- a/src/metadata.ts +++ b/src/metadata.ts @@ -1,22 +1,22 @@ -import Config from "./models/Config"; -import Logger from "./utils/Logger"; +import Config from "./models/Config" +import Logger from "./utils/Logger" -declare var fetch; +declare var fetch export default class MetaData { - private assetsUrl: string; + private assetsUrl: string constructor(config: Config) { - const providerUri = config.providerUri || null; + const providerUri = config.providerUri || null - this.assetsUrl = providerUri + "/assets"; + this.assetsUrl = providerUri + "/assets" } public getAssetsMetadata() { return fetch(this.assetsUrl + "/metadata", {method: "GET"}) .then((res) => res.json()) - .then((data) => JSON.parse(data)); + .then((data) => JSON.parse(data)) } public publishDataAsset(asset: object) { @@ -27,19 +27,19 @@ export default class MetaData { headers: {"Content-type": "application/json"}, }) .then((response: any) => { - Logger.log("Success:", response); + Logger.log("Success:", response) if (response.ok) { - Logger.log("Success:", response); - return true; + Logger.log("Success:", response) + return true } - Logger.log("Failed: ", response.status, response.statusText); - return false; + Logger.log("Failed: ", response.status, response.statusText) + return false // throw new Error(response.statusText ? response.statusText : // `publish asset failed with status ${response.status}`) }) .catch((error: Error) => { - Logger.log(`Publish asset to ocean database could not be completed: ${error.message}`); - return false; - }); + Logger.log(`Publish asset to ocean database could not be completed: ${error.message}`) + return false + }) } } diff --git a/src/models/Asset.ts b/src/models/Asset.ts index 9f5a22b..5fbc986 100644 --- a/src/models/Asset.ts +++ b/src/models/Asset.ts @@ -1,5 +1,5 @@ export default class Asset { - public assetId: string; - public publisherId: string; - public price: number; + public assetId: string + public publisherId: string + public price: number } diff --git a/src/models/Config.ts b/src/models/Config.ts index fb33f23..264db95 100644 --- a/src/models/Config.ts +++ b/src/models/Config.ts @@ -1,7 +1,6 @@ export default class Config { - - public defaultGas: number = 300000; - public providerUri: string; - public nodeUri: string; - public web3Provider: any; + public defaultGas: number = 300000 + public providerUri: string + public nodeUri: string + public web3Provider: any } diff --git a/src/models/Order.ts b/src/models/Order.ts index 10e7679..ba573fa 100644 --- a/src/models/Order.ts +++ b/src/models/Order.ts @@ -1,10 +1,10 @@ -import Asset from "./Asset"; +import Asset from "./Asset" export default class Order { - public id: string; - public asset: Asset; - public assetId: string; - public timeout: any; - public pubkey: string; - public key: any; + public id: string + public asset: Asset + public assetId: string + public timeout: any + public pubkey: string + public key: any } diff --git a/src/ocean/Asset.ts b/src/ocean/Asset.ts index df41638..9f5a076 100644 --- a/src/ocean/Asset.ts +++ b/src/ocean/Asset.ts @@ -1,16 +1,16 @@ -import Keeper from "../keeper/Keeper"; +import Keeper from "../keeper/Keeper" export default class Asset { - private keeper: Keeper; + private keeper: Keeper constructor(keeper: Keeper) { - this.keeper = keeper; + this.keeper = keeper } public isAssetActive(assetId: string): Promise { - const {market} = this.keeper; - return market.isAssetActive(assetId); + const {market} = this.keeper + return market.isAssetActive(assetId) } } diff --git a/src/ocean/Order.ts b/src/ocean/Order.ts index 5eac901..3127b22 100644 --- a/src/ocean/Order.ts +++ b/src/ocean/Order.ts @@ -1,21 +1,21 @@ -import * as EthCrypto from "eth-crypto"; -import EthEcies from "eth-ecies"; -import * as EthjsUtil from "ethereumjs-util"; -import JWT from "jsonwebtoken"; -import EventListener from "../keeper/EventListener"; -import Keeper from "../keeper/Keeper"; -import Asset from "../models/Asset"; -import OrderModel from "../models/Order"; -import Logger from "../utils/Logger"; +import * as EthCrypto from "eth-crypto" +import EthEcies from "eth-ecies" +import * as EthjsUtil from "ethereumjs-util" +import JWT from "jsonwebtoken" +import EventListener from "../keeper/EventListener" +import Keeper from "../keeper/Keeper" +import Asset from "../models/Asset" +import OrderModel from "../models/Order" +import Logger from "../utils/Logger" -declare var fetch; +declare var fetch export default class Order { private static create(asset: Asset, args, key): OrderModel { - Logger.log("keeper AccessConsentRequested event received on asset: ", asset.assetId, "\nevent:", args); - const accessId = args._id; - Logger.log("got new access request id: ", accessId); + Logger.log("keeper AccessConsentRequested event received on asset: ", asset.assetId, "\nevent:", args) + const accessId = args._id + Logger.log("got new access request id: ", accessId) return { id: accessId, assetId: asset.assetId, @@ -23,25 +23,25 @@ export default class Order { timeout: args._timeout, pubkey: args._pubKey, key, - } as OrderModel; + } as OrderModel } - private keeper: Keeper; + private keeper: Keeper constructor(keeper: Keeper) { - this.keeper = keeper; + this.keeper = keeper } public async getOrdersByConsumer(consumerAddress: string) { - const {auth, market} = this.keeper; + const {auth, market} = this.keeper const accessConsentEvent = auth.getEvent("AccessConsentRequested")({ _consumer: consumerAddress, }, { fromBlock: 0, toBlock: "latest", - }); + }) - const events = await EventListener.getEvents(accessConsentEvent); + const events = await EventListener.getEvents(accessConsentEvent) const orders = await Promise.all(events .filter((event: any) => (event.args._consumer === consumerAddress)) @@ -51,104 +51,104 @@ export default class Order { status: await auth.getOrderStatus(event.args._id), paid: await market.verifyOrderPayment(event.args._id), key: null, - } as Order))); - Logger.log("Got orders: ", orders); - return orders; + } as Order))) + Logger.log("Got orders: ", orders) + return orders } public async purchaseAsset(asset: Asset, timeout: number, buyerAddress: string): Promise { - const {token, market, auth} = this.keeper; + const {token, market, auth} = this.keeper - const key = EthCrypto.createIdentity(); - const publicKey = EthjsUtil.privateToPublic(key.privateKey).toString("hex"); - const price = await market.getAssetPrice(asset.assetId); - const isValid = await market.isAssetActive(asset.assetId); + const key = EthCrypto.createIdentity() + const publicKey = EthjsUtil.privateToPublic(key.privateKey).toString("hex") + const price = await market.getAssetPrice(asset.assetId) + const isValid = await market.isAssetActive(asset.assetId) - Logger.log("The asset:", asset.assetId, "is it valid?", isValid, "it's price is:", price); + Logger.log("The asset:", asset.assetId, "is it valid?", isValid, "it's price is:", price) if (!isValid) { - throw new Error("asset not valid"); + throw new Error("asset not valid") } try { // Allow market contract to transfer funds on the consumer"s behalf - await token.approve(market.getAddress(), price, buyerAddress); + await token.approve(market.getAddress(), price, buyerAddress) } catch (err) { - Logger.log("token approve", err); + Logger.log("token approve", err) } try { // Submit the access request - await auth.initiateAccessRequest(asset, publicKey, timeout, buyerAddress); + await auth.initiateAccessRequest(asset, publicKey, timeout, buyerAddress) } catch (err) { - Logger.log("initiateAccessRequest", err); + Logger.log("initiateAccessRequest", err) } const resourceFilter = { _resourceId: asset.assetId, _consumer: buyerAddress, - }; + } // todo: Event - implement proper eventing - const accessConsentRequestedEvent = auth.getEvent("AccessConsentRequested")(resourceFilter); - let order: OrderModel; + const accessConsentRequestedEvent = auth.getEvent("AccessConsentRequested")(resourceFilter) + let order: OrderModel const finalOrder: OrderModel = await EventListener.listenOnce( accessConsentRequestedEvent, "AccessConsentRequested") .then((accessConsentRequestedResult) => { - order = Order.create(asset, accessConsentRequestedResult.args, key); + order = Order.create(asset, accessConsentRequestedResult.args, key) const requestIdFilter = { _id: order.id, - }; + } // todo: Event - implement proper eventing - const accessCommittedEvent = auth.getEvent("AccessRequestCommitted")(requestIdFilter); + const accessCommittedEvent = auth.getEvent("AccessRequestCommitted")(requestIdFilter) - return EventListener.listenOnce(accessCommittedEvent, "AccessRequestCommitted"); + return EventListener.listenOnce(accessCommittedEvent, "AccessRequestCommitted") }) .then((accessRequestCommittedResult) => { - return this.payAsset(asset, accessRequestCommittedResult.args, order, buyerAddress); + return this.payAsset(asset, accessRequestCommittedResult.args, order, buyerAddress) }) .then(() => { const requestIdFilter = { _id: order.id, - }; + } // todo: Event - implement proper eventing - const tokenPublishedEvent = auth.getEvent("EncryptedTokenPublished")(requestIdFilter); - return EventListener.listenOnce(tokenPublishedEvent, "EncryptedTokenPublished"); + const tokenPublishedEvent = auth.getEvent("EncryptedTokenPublished")(requestIdFilter) + return EventListener.listenOnce(tokenPublishedEvent, "EncryptedTokenPublished") }) .then((result) => { return this.finalizePurchaseAsset( result, order, key, buyerAddress, - ); - }); + ) + }) - return finalOrder; + return finalOrder } private async payAsset(asset: Asset, args, order, buyerAddress) { - const {market} = this.keeper; + const {market} = this.keeper // send payment - Logger.log("Sending payment: ", order.id, args._id, asset.publisherId, asset.price, order.timeout); - return market.payAsset(asset, order, buyerAddress); + Logger.log("Sending payment: ", order.id, args._id, asset.publisherId, asset.price, order.timeout) + return market.payAsset(asset, order, buyerAddress) } private async finalizePurchaseAsset(args, order, key, buyerAddress): Promise { - const {auth, web3Helper} = this.keeper; + const {auth, web3Helper} = this.keeper // Logger.log('keeper EncryptedTokenPublished event received: ', order.id, eventResult.args) - const encryptedAccessToken = await auth.getEncryptedAccessToken(args._id, buyerAddress); + const encryptedAccessToken = await auth.getEncryptedAccessToken(args._id, buyerAddress) // grab the access token from acl contract - const tokenNo0x = encryptedAccessToken.slice(2); - const encryptedTokenBuffer = Buffer.from(tokenNo0x, "hex"); + const tokenNo0x = encryptedAccessToken.slice(2) + const encryptedTokenBuffer = Buffer.from(tokenNo0x, "hex") - const privateKey = key.privateKey.slice(2); - const accessTokenEncoded = EthEcies.Decrypt(Buffer.from(privateKey, "hex"), encryptedTokenBuffer); - const accessToken = JWT.decode(accessTokenEncoded); // Returns a json object + const privateKey = key.privateKey.slice(2) + const accessTokenEncoded = EthEcies.Decrypt(Buffer.from(privateKey, "hex"), encryptedTokenBuffer) + const accessToken = JWT.decode(accessTokenEncoded) // Returns a json object // sign it - const hexEncrToken = `0x${encryptedTokenBuffer.toString("hex")}`; + const hexEncrToken = `0x${encryptedTokenBuffer.toString("hex")}` - const signature = web3Helper.sign(buyerAddress, hexEncrToken); - const fixedMsgSha = web3Helper.getWeb3().utils.sha3(encryptedAccessToken); + const signature = web3Helper.sign(buyerAddress, hexEncrToken) + const fixedMsgSha = web3Helper.getWeb3().utils.sha3(encryptedAccessToken) // Download the data set from the provider using the url in the access token // decode the access token, grab the service_endpoint, request_id, @@ -159,7 +159,7 @@ export default class Order { fixed_msg: fixedMsgSha, sigEncJWT: signature, jwt: accessTokenEncoded, - }); + }) const accessUrl = await fetch(`${accessToken.service_endpoint}/${accessToken.resource_id}`, { method: "POST", body: payload, @@ -169,20 +169,20 @@ export default class Order { }) .then((response: any) => { if (response.ok) { - return response.text(); + return response.text() } - Logger.log("Failed: ", response.status, response.statusText); + Logger.log("Failed: ", response.status, response.statusText) }) .then((consumptionUrl: string) => { - Logger.log("Success accessing consume endpoint: ", consumptionUrl); - return consumptionUrl; + Logger.log("Success accessing consume endpoint: ", consumptionUrl) + return consumptionUrl }) .catch((error) => { - Logger.error("Error fetching the data asset consumption url: ", error); - }); - Logger.log("consume url: ", accessUrl); - order.accessUrl = accessUrl; + Logger.error("Error fetching the data asset consumption url: ", error) + }) + Logger.log("consume url: ", accessUrl) + order.accessUrl = accessUrl - return order; + return order } } diff --git a/src/squid.ts b/src/squid.ts index a3f51d0..1c6b895 100644 --- a/src/squid.ts +++ b/src/squid.ts @@ -1,7 +1,7 @@ -import Ocean from "./Ocean"; -import Logger from "./utils/Logger"; +import Ocean from "./Ocean" +import Logger from "./utils/Logger" export { Ocean, Logger, -}; +} diff --git a/src/utils/Logger.ts b/src/utils/Logger.ts index aa0be13..d90b70c 100644 --- a/src/utils/Logger.ts +++ b/src/utils/Logger.ts @@ -1,21 +1,21 @@ export default class Logger { public static log(...args: any[]) { - Logger.dispatch("log", ...args); + Logger.dispatch("log", ...args) } public static debug(...args: any[]) { - Logger.dispatch("debug", ...args); + Logger.dispatch("debug", ...args) } public static warn(...args: any[]) { - Logger.dispatch("warn", ...args); + Logger.dispatch("warn", ...args) } public static error(...args: any[]) { - Logger.dispatch("error", ...args); + Logger.dispatch("error", ...args) } private static dispatch(verb: string, ...args: any[]) { - console[verb](...args); + console[verb](...args) } -} \ No newline at end of file +} diff --git a/test/Keeper.test.ts b/test/Keeper.test.ts index 6dc3a41..e8e3d7a 100644 --- a/test/Keeper.test.ts +++ b/test/Keeper.test.ts @@ -1,24 +1,24 @@ -import ContractHandler from "../src/keeper/ContractHandler"; -import Keeper from "../src/keeper/Keeper"; -import Web3Helper from "../src/keeper/Web3Helper"; -import Config from "../src/models/Config"; -import Logger from "../src/utils/Logger"; +import ContractHandler from "../src/keeper/ContractHandler" +import Keeper from "../src/keeper/Keeper" +import Web3Helper from "../src/keeper/Web3Helper" +import Config from "../src/models/Config" +import Logger from "../src/utils/Logger" -let keeper: Keeper; +let keeper: Keeper before(async () => { - const config: Config = {nodeUri: "http://localhost:8545"} as Config; - const web3Helper = new Web3Helper(config); - await ContractHandler.deployContracts(web3Helper); - keeper = await Keeper.getInstance(config, web3Helper); -}); + const config: Config = {nodeUri: "http://localhost:8545"} as Config + const web3Helper = new Web3Helper(config) + await ContractHandler.deployContracts(web3Helper) + keeper = await Keeper.getInstance(config, web3Helper) +}) describe("Keeper", () => { it("should keep", async () => { - const balance = await keeper.token.getTokenBalance("0xB0EdD05A5874c5c1Fcd6bCB4E52143fB7134b7EE"); + const balance = await keeper.token.getTokenBalance("0xB0EdD05A5874c5c1Fcd6bCB4E52143fB7134b7EE") - Logger.log(balance); - }); -}); + Logger.log(balance) + }) +}) diff --git a/tslint.json b/tslint.json index a63e8b8..415768f 100644 --- a/tslint.json +++ b/tslint.json @@ -5,7 +5,11 @@ ], "jsRules": {}, "rules": { - "object-literal-sort-keys": false + "object-literal-sort-keys": false, + "semicolon": [ + true, + "never" + ] }, "rulesDirectory": [] } \ No newline at end of file