From 4038697a4b6dfff46b47f5a43dffa8444b3aa185 Mon Sep 17 00:00:00 2001 From: Sebastian Gerske Date: Mon, 1 Oct 2018 18:10:57 +0200 Subject: [PATCH] new structure --- src/keeper/auth.ts | 42 +++++++------ src/keeper/market.ts | 65 ++++++++++---------- src/keeper/token.ts | 33 ++++++----- src/ocean.ts | 138 +++++++------------------------------------ 4 files changed, 92 insertions(+), 186 deletions(-) diff --git a/src/keeper/auth.ts b/src/keeper/auth.ts index 361baa7..b155dfe 100644 --- a/src/keeper/auth.ts +++ b/src/keeper/auth.ts @@ -1,30 +1,38 @@ -import Config from "../utils/config"; -import Web3Helper from "../utils/Web3Helper"; -import ContractLoader from "./contractLoader"; -import KeeperBase from "./keeper-base"; +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 KeeperBase { +export default class OceanAuth extends ContractBaseWrapper { - public static async getInstance(config: Config, web3Helper) { - const auth = new OceanAuth(config, web3Helper); - - auth.contract = await ContractLoader.load("OceanAuth", auth.web3Helper); + public static async getInstance(config: Config, web3Helper: Web3Helper) { + const auth = new OceanAuth(config, "OceanAuth", web3Helper); + await auth.init(); return auth; } - private constructor(config: Config, web3Helper: Web3Helper) { - super(config, web3Helper); + public async getOrderStatus(orderId: string): Promise { + return this.contract.statusOfAccessRequest.call(orderId) + .then((status: BigNumber) => status.toNumber()); } - public cancelAccessRequest(orderId: string, senderAddress: string) { - return this.contract.cancelAccessRequest(orderId, {from: senderAddress}); + public async cancelAccessRequest(orderId: string, senderAddress: string) { + return this.contract.cancelAccessRequest.send(orderId, { + from: senderAddress, + }); } - public getOrderStatus(orderId: string) { - return this.contract.statusOfAccessRequest(orderId); + public async getEncryptedAccessToken(orderId: string, senderAddress: string) { + return this.contract.getEncryptedAccessToken.send(orderId, { + from: senderAddress, + }); } - public getEncryptedAccessToken(orderId: string, senderAddress: string) { - return this.contract.getEncryptedAccessToken(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/market.ts b/src/keeper/market.ts index 2b48303..4964fb0 100644 --- a/src/keeper/market.ts +++ b/src/keeper/market.ts @@ -1,61 +1,56 @@ -import BigNumber from "bignumber.js"; -import Config from "../utils/config"; -import Logger from "../utils/logger"; -import Web3Helper from "../utils/Web3Helper"; -import ContractLoader from "./contractLoader"; -import KeeperBase from "./keeper-base"; +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 KeeperBase { +export default class OceanMarket extends ContractWrapperBase { public static async getInstance(config: Config, web3Helper: Web3Helper) { - const market = new OceanMarket(config, web3Helper); - market.contract = await ContractLoader.load("OceanMarket", market.web3Helper); + const market = new OceanMarket(config, "OceanMarket", web3Helper); + await market.init(); return market; } - private constructor(config: Config, web3Helper: Web3Helper) { - super(config, web3Helper); - } - // call functions (costs no gas) - public checkAsset(assetId: string) { - return this.contract.checkAsset(assetId); + public async isAssetActive(assetId: string): Promise { + return this.contract.methods.checkAsset(assetId).call; } - public verifyOrderPayment(orderId: string): boolean { - return this.contract.verifyPaymentReceived(orderId); + public async verifyOrderPayment(orderId: string): Promise { + return this.contract.methods.verifyPaymentReceived(orderId).call; } - public getAssetPrice(assetId: string) { - return this.contract.getAssetPrice(assetId) - .then((price: BigNumber) => price.toNumber()); + public async getAssetPrice(assetId: string): Promise { + return this.contract.methods.getAssetPrice(assetId).call().then((result) => result.toNumber()); } - // Transactions with gas cost - public requestTokens(amount: number, address: string) { - return this.contract.requestTokens(amount, {from: address}); + 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) { - const assetId = await this.contract.generateId(name + description); - const result = await this.contract.register( - assetId, - price, { + 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 result = await this.contract.methods.register(assetId, price).send({ from: publisherAddress, gas: this.config.defaultGas, }, ); - Logger.log("registered: ", result); + Logger.log("Registered: ", result); return assetId; } - public async payAsset(assetId: string, order: any, publisherAddress: string, senderAddress: string) { - const assetPrice = await this.contract.getAssetPrice(assetId) - .then((price: BigNumber) => price.toNumber()); - this.contract.sendPayment(order.id, publisherAddress, assetPrice, order.timeout, { - from: senderAddress, - gas: 2000000, + public async payAsset(asset: Asset, order: Order, buyerAddress: string): Promise { + 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 26b2cf1..4139e7f 100644 --- a/src/keeper/token.ts +++ b/src/keeper/token.ts @@ -1,30 +1,24 @@ -import Config from "../utils/config"; -import Logger from "../utils/logger"; -import Web3Helper from "../utils/Web3Helper"; -import ContractLoader from "./contractLoader"; -import KeeperBase from "./keeper-base"; +import Config from "../models/config"; +import Logger from "../utils/Logger"; +import ContractBaseWrapper from "./ContractWrapperBase"; +import Web3Helper from "./Web3Helper"; -export default class OceanToken extends KeeperBase { +export default class OceanToken extends ContractBaseWrapper { public static async getInstance(config: Config, web3Helper: Web3Helper) { - const token = new OceanToken(config, web3Helper); - token.contract = await ContractLoader.load("OceanToken", token.web3Helper); - + const token = new OceanToken(config, "OceanToken", web3Helper); + await token.init(); return token; } - private constructor(config: Config, web3Helper: Web3Helper) { - super(config, web3Helper); - } - - public getTokenBalance(accountAddress: string) { - return this.contract.balanceOf.call(accountAddress); + public async getTokenBalance(accountAddress: string) { + return this.contract.methods.balanceOf(accountAddress).call(); } public async getEthBalance(account: string): Promise { return new Promise((resolve, reject) => { // Logger.log("getting balance for", account); - this.web3Helper.web3.eth.getBalance(account, "latest", (err: any, balance: number) => { + this.web3Helper.getWeb3().eth.getBalance(account, "latest", (err: any, balance: number) => { if (err) { return reject(err); } @@ -33,4 +27,11 @@ export default class OceanToken extends KeeperBase { }); }); } + + 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/ocean.ts b/src/ocean.ts index a1012e9..932aae7 100644 --- a/src/ocean.ts +++ b/src/ocean.ts @@ -1,31 +1,27 @@ -import BigNumber from "bignumber.js"; -import OceanAuth from "./keeper/auth"; -import OceanMarket from "./keeper/market"; -import OceanToken from "./keeper/token"; +import Keeper from "./keeper/Keeper"; +import Web3Helper from "./keeper/Web3Helper"; import MetaData from "./metadata"; -import Config from "./utils/config"; -import Logger from "./utils/logger"; -import Web3Helper from "./utils/Web3Helper"; +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.market = await OceanMarket.getInstance(config, ocean.helper); - ocean.auth = await OceanAuth.getInstance(config, ocean.helper); - ocean.token = await OceanToken.getInstance(config, ocean.helper); + ocean.keeper = await Keeper.getInstance(config, ocean.helper); + ocean.order = new Order(ocean.keeper); + ocean.asset = new Asset(ocean.keeper); return ocean; } - public token: OceanToken; - public market: OceanMarket; - public auth: OceanAuth; + public order: Order; + public asset: Asset; public helper: Web3Helper; public metadata: MetaData; + private keeper: Keeper; private config: Config; private constructor(config: Config) { @@ -36,10 +32,17 @@ export default class Ocean { this.metadata = new MetaData(config); } + // Transactions with gas cost + public async requestTokens(amount: number, receiver: string): Promise { + return this.keeper.market.requestTokens(amount, receiver); + } + public async getAccounts() { - return Promise.all((await this.helper.getAccounts()).map(async (account: string) => { + const {token} = this.keeper; + const {helper} = this; + + return Promise.all((await helper.getAccounts()).map(async (account: string) => { // await ocean.market.requestTokens(account, 1000) - const {token} = this; return { name: account, balance: { @@ -49,105 +52,4 @@ export default class Ocean { }; })); } - - public async getOrdersByConsumer(consumerAddress: string) { - const {auth} = this; - const accessConsentEvent = auth.contract.AccessConsentRequested({_consumer: consumerAddress}, { - fromBlock: 0, - toBlock: "latest", - }); - - let outerResolve = null; - let outerReject = null; - const promise = new Promise((resolve, reject) => { - outerResolve = resolve; - outerReject = reject; - }); - - const getEvents = (): Promise => { - accessConsentEvent.get((error: any, logs: any[]) => { - if (error) { - outerReject(error); - throw new Error(error); - } else { - outerResolve(logs); - } - }); - return promise; - }; - const events = await getEvents().then((result) => result); - // let orders = await this.buildOrdersFromEvents(events, consumerAddress).then((result) => result) - const orders = events - .filter((obj: any) => (obj.args._consumer === consumerAddress)) - .map(async (event: any) => ({ - ...event.args, - timeout: event.args._timeout.toNumber(), - status: await this.auth.getOrderStatus(event.args._id) - .then((status: BigNumber) => status.toNumber()), - paid: this.market.verifyOrderPayment(event.args._id), - key: null, - })); - Logger.debug("got orders: ", orders); - return orders; - } - - public async purchaseAsset( - assetId: string, publisherId: string, price: number, privateKey: string, publicKey: string, timeout: number, - senderAddress: string, initialRequestEventHandler, accessCommittedEventHandler, tokenPublishedEventHandler) { - const {token, market, auth, config} = this; - try { - // Allow market contract to transfer funds on the consumer"s behalf - await token.contract.approve(market.contract.address, price, {from: senderAddress, gas: config.defaultGas}); - } catch (err) { - Logger.log("token approve", err); - } - try { - // Submit the access request - await auth.contract.initiateAccessRequest( - assetId, publisherId, publicKey, - timeout, {from: senderAddress, gas: 1000000}, - ); - } catch (err) { - Logger.log("initiateAccessRequest", err); - } - const resourceFilter = {_resourceId: assetId, _consumer: senderAddress}; - const initRequestEvent = auth.contract.AccessConsentRequested(resourceFilter); - let order: any = {}; - this._listenOnce( - initRequestEvent, - "AccessConsentRequested", - (result: any, error: any) => { - order = initialRequestEventHandler(result, error); - const requestIdFilter = {_id: order.id}; - const accessCommittedEvent = auth.contract.AccessRequestCommitted(requestIdFilter); - const tokenPublishedEvent = auth.contract.EncryptedTokenPublished(requestIdFilter); - this._listenOnce( - accessCommittedEvent, - "AccessRequestCommitted", - (accessRequestCommittedResult: any, accessRequestCommittedError: any) => { - accessCommittedEventHandler(accessRequestCommittedResult, order, accessRequestCommittedError); - }, - ); - this._listenOnce( - tokenPublishedEvent, - "EncryptedTokenPublished", - (encryptedTokenPublishedResult: any, encryptedTokenPublishedError: any) => { - tokenPublishedEventHandler(encryptedTokenPublishedResult, order, encryptedTokenPublishedError); - }, - ); - }); - return order; - } - - // Helper functions (private) - public _listenOnce(event: any, eventName: string, callback) { - // eslint-disable-next-line security/detect-non-literal-fs-filename - event.watch((error: any, result: any) => { - event.stopWatching(); - if (error) { - Logger.log(`Error in keeper ${eventName} event: `, error); - } - callback(result, error); - }); - } }