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

new linter styles

This commit is contained in:
Sebastian Gerske 2018-10-02 10:06:26 +02:00
parent 163ac95681
commit 5dbc868686
20 changed files with 319 additions and 319 deletions

View File

@ -1,45 +1,44 @@
import Keeper from "./keeper/Keeper"; import Keeper from "./keeper/Keeper"
import Web3Helper from "./keeper/Web3Helper"; import Web3Helper from "./keeper/Web3Helper"
import MetaData from "./metadata"; import MetaData from "./metadata"
import Config from "./models/Config"; import Config from "./models/Config"
import Asset from "./ocean/Asset"; import Asset from "./ocean/Asset"
import Order from "./ocean/Order"; import Order from "./ocean/Order"
export default class Ocean { export default class Ocean {
public static async getInstance(config) { public static async getInstance(config) {
const ocean = new Ocean(config); const ocean = new Ocean(config)
ocean.keeper = await Keeper.getInstance(config, ocean.helper); ocean.keeper = await Keeper.getInstance(config, ocean.helper)
ocean.order = new Order(ocean.keeper); ocean.order = new Order(ocean.keeper)
ocean.asset = new Asset(ocean.keeper); ocean.asset = new Asset(ocean.keeper)
return ocean
return ocean;
} }
public order: Order; public order: Order
public asset: Asset; public asset: Asset
public helper: Web3Helper; public helper: Web3Helper
public metadata: MetaData; public metadata: MetaData
private keeper: Keeper; private keeper: Keeper
private config: Config; private config: Config
private constructor(config: Config) { private constructor(config: Config) {
this.config = config; this.config = config
this.helper = new Web3Helper(config); this.helper = new Web3Helper(config)
this.metadata = new MetaData(config); this.metadata = new MetaData(config)
} }
// Transactions with gas cost // Transactions with gas cost
public async requestTokens(amount: number, receiver: string): Promise<boolean> { public async requestTokens(amount: number, receiver: string): Promise<boolean> {
return this.keeper.market.requestTokens(amount, receiver); return this.keeper.market.requestTokens(amount, receiver)
} }
public async getAccounts() { public async getAccounts() {
const {token} = this.keeper; const {token} = this.keeper
const {helper} = this; const {helper} = this
return Promise.all((await helper.getAccounts()).map(async (account: string) => { return Promise.all((await helper.getAccounts()).map(async (account: string) => {
// await ocean.market.requestTokens(account, 1000) // await ocean.market.requestTokens(account, 1000)
@ -49,7 +48,7 @@ export default class Ocean {
eth: await token.getEthBalance(account), eth: await token.getEthBalance(account),
ocn: await token.getTokenBalance(account), ocn: await token.getTokenBalance(account),
}, },
}; }
})); }))
} }
} }

View File

@ -1,30 +1,30 @@
import Web3Helper from "./keeper/Web3Helper"; import Web3Helper from "./keeper/Web3Helper"
export default class Tribe { export default class Tribe {
public static getInstance(web3Helper: Web3Helper) { public static getInstance(web3Helper: Web3Helper) {
return new Tribe(web3Helper); return new Tribe(web3Helper)
} }
private web3Helper: Web3Helper; private web3Helper: Web3Helper
private constructor(web3Helper: Web3Helper) { private constructor(web3Helper: Web3Helper) {
this.web3Helper = web3Helper; this.web3Helper = web3Helper
} }
// did ddo for tribes/marketplaces // did ddo for tribes/marketplaces
public registerTribe() { public registerTribe() {
return ""; return ""
} }
public tribessList() { public tribessList() {
return ""; return ""
} }
public resolveTribeDID() { public resolveTribeDID() {
// verify DDO // verify DDO
return "DDO"; return "DDO"
} }
} }

View File

@ -1,38 +1,38 @@
import BigNumber from "bignumber.js"; import BigNumber from "bignumber.js"
import Asset from "../models/Asset"; import Asset from "../models/Asset"
import Config from "../models/Config"; import Config from "../models/Config"
import ContractBaseWrapper from "./ContractWrapperBase"; import ContractBaseWrapper from "./ContractWrapperBase"
import Web3Helper from "./Web3Helper"; import Web3Helper from "./Web3Helper"
export default class OceanAuth extends ContractBaseWrapper { export default class OceanAuth extends ContractBaseWrapper {
public static async getInstance(config: Config, web3Helper: Web3Helper) { public static async getInstance(config: Config, web3Helper: Web3Helper) {
const auth = new OceanAuth(config, "OceanAuth", web3Helper); const auth = new OceanAuth(config, "OceanAuth", web3Helper)
await auth.init(); await auth.init()
return auth; return auth
} }
public async getOrderStatus(orderId: string): Promise<number> { public async getOrderStatus(orderId: string): Promise<number> {
return this.contract.statusOfAccessRequest.call(orderId) return this.contract.statusOfAccessRequest.call(orderId)
.then((status: BigNumber) => status.toNumber()); .then((status: BigNumber) => status.toNumber())
} }
public async cancelAccessRequest(orderId: string, senderAddress: string) { public async cancelAccessRequest(orderId: string, senderAddress: string) {
return this.contract.cancelAccessRequest.send(orderId, { return this.contract.cancelAccessRequest.send(orderId, {
from: senderAddress, from: senderAddress,
}); })
} }
public async getEncryptedAccessToken(orderId: string, senderAddress: string) { public async getEncryptedAccessToken(orderId: string, senderAddress: string) {
return this.contract.getEncryptedAccessToken.send(orderId, { return this.contract.getEncryptedAccessToken.send(orderId, {
from: senderAddress, from: senderAddress,
}); })
} }
public async initiateAccessRequest(asset: Asset, publicKey: string, timeout, buyerAddress: string) { public async initiateAccessRequest(asset: Asset, publicKey: string, timeout, buyerAddress: string) {
return this.contract.initiateAccessRequest.send( return this.contract.initiateAccessRequest.send(
asset.assetId, asset.publisherId, publicKey, timeout, { asset.assetId, asset.publisherId, publicKey, timeout, {
from: buyerAddress, gas: this.config.defaultGas, from: buyerAddress, gas: this.config.defaultGas,
}); })
} }
} }

View File

@ -1,28 +1,28 @@
import Contract from "web3"; import Contract from "web3"
import Logger from "../utils/Logger"; import Logger from "../utils/Logger"
import Web3Helper from "./Web3Helper"; import Web3Helper from "./Web3Helper"
const contracts: Map<string, object> = new Map<string, object>(); const contracts: Map<string, object> = new Map<string, object>()
export default class ContractHandler { export default class ContractHandler {
public static async get(what: string, web3Helper: Web3Helper) { 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) { 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 // deploy libs
const dll = await ContractHandler.deployContract(web3, "DLL", deployerAddress); const dll = await ContractHandler.deployContract(web3, "DLL", deployerAddress)
const attributeStore = await ContractHandler.deployContract(web3, "AttributeStore", deployerAddress); const attributeStore = await ContractHandler.deployContract(web3, "AttributeStore", deployerAddress)
// deploy contracts // 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, { const plcrVoting = await ContractHandler.deployContract(web3, "PLCRVoting", deployerAddress, {
args: [token.options.address], args: [token.options.address],
tokens: [ tokens: [
@ -32,35 +32,35 @@ export default class ContractHandler {
name: "AttributeStore", address: attributeStore.options.address, name: "AttributeStore", address: attributeStore.options.address,
}, },
], ],
}); })
const registry = await ContractHandler.deployContract(web3, "OceanRegistry", deployerAddress, { const registry = await ContractHandler.deployContract(web3, "OceanRegistry", deployerAddress, {
args: [token.options.address, plcrVoting.options.address], args: [token.options.address, plcrVoting.options.address],
}); })
const market = await ContractHandler.deployContract(web3, "OceanMarket", deployerAddress, { const market = await ContractHandler.deployContract(web3, "OceanMarket", deployerAddress, {
args: [token.options.address, registry.options.address], args: [token.options.address, registry.options.address],
}); })
const dispute = await ContractHandler.deployContract(web3, "OceanDispute", deployerAddress, { const dispute = await ContractHandler.deployContract(web3, "OceanDispute", deployerAddress, {
args: [market.options.address, registry.options.address, plcrVoting.options.address], args: [market.options.address, registry.options.address, plcrVoting.options.address],
}); })
const auth = await ContractHandler.deployContract(web3, "OceanAuth", deployerAddress, { const auth = await ContractHandler.deployContract(web3, "OceanAuth", deployerAddress, {
args: [market.options.address, dispute.options.address], args: [market.options.address, dispute.options.address],
}); })
} }
private static async load(what: string, web3Helper: Web3Helper): Promise<object> { private static async load(what: string, web3Helper: Web3Helper): Promise<object> {
const where = (await web3Helper.getNetworkName()).toLowerCase(); const where = (await web3Helper.getNetworkName()).toLowerCase()
Logger.log("Loading", what, "from", where); Logger.log("Loading", what, "from", where)
try { 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('Loaded artifact', artifact)
Logger.log("Getting instance of", what, "from", where, "at", artifact.address); Logger.log("Getting instance of", what, "from", where, "at", artifact.address)
const web3 = web3Helper.getWeb3(); const web3 = web3Helper.getWeb3()
const contract = new web3.eth.Contract(artifact.abi, artifact.address); const contract = new web3.eth.Contract(artifact.abi, artifact.address)
Logger.log("Loaded", what, "from", where); Logger.log("Loaded", what, "from", where)
contracts.set(what, contract); contracts.set(what, contract)
return contracts.get(what); return contracts.get(what)
} catch (err) { } 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( bytecode = bytecode.replace(
new RegExp(`_+${token.name}_+`, "g"), new RegExp(`_+${token.name}_+`, "g"),
token.address.replace("0x", "")); token.address.replace("0x", ""))
} }
// Logger.log(bytecode); // Logger.log(bytecode);
return bytecode.toString(); return bytecode.toString()
} }
private static async deployContract(web3, name, from, params?): Promise<Contract> { private static async deployContract(web3, name, from, params?): Promise<Contract> {
let contractInstance; let contractInstance
try { try {
Logger.log("Deploying", name); Logger.log("Deploying", name)
const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${name}.development.json`); const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${name}.development.json`)
const tempContract = new web3.eth.Contract(artifact.abi, artifact.address); const tempContract = new web3.eth.Contract(artifact.abi, artifact.address)
contractInstance = await tempContract.deploy({ contractInstance = await tempContract.deploy({
data: params && params.tokens ? data: params && params.tokens ?
ContractHandler.replaceTokens(artifact.bytecode.toString(), params.tokens) : ContractHandler.replaceTokens(artifact.bytecode.toString(), params.tokens) :
@ -94,14 +94,14 @@ export default class ContractHandler {
from, from,
gas: 3000000, gas: 3000000,
gasPrice: 10000000000, gasPrice: 10000000000,
}); })
contracts.set(name, contractInstance); contracts.set(name, contractInstance)
// Logger.log("Deployed", name, "at", contractInstance.options.address); // Logger.log("Deployed", name, "at", contractInstance.options.address);
} catch (err) { } catch (err) {
Logger.error("Deployment failed for", name, "with params", JSON.stringify(params, null, 2), err.message); Logger.error("Deployment failed for", name, "with params", JSON.stringify(params, null, 2), err.message)
throw err; throw err
} }
return contractInstance; return contractInstance
} }
} }

View File

@ -1,33 +1,33 @@
import Config from "../models/Config"; import Config from "../models/Config"
import ContractHandler from "./ContractHandler"; import ContractHandler from "./ContractHandler"
import Web3Helper from "./Web3Helper"; import Web3Helper from "./Web3Helper"
export default class ContractWrapperBase { export default class ContractWrapperBase {
protected contract: any = null; protected contract: any = null
protected config: Config; protected config: Config
protected web3Helper: Web3Helper; protected web3Helper: Web3Helper
private contractName: string; private contractName: string
constructor(config: Config, contractName: string, web3Helper: Web3Helper) { constructor(config: Config, contractName: string, web3Helper: Web3Helper) {
this.config = config; this.config = config
this.contractName = contractName; this.contractName = contractName
this.web3Helper = web3Helper; this.web3Helper = web3Helper
} }
public async init() { public async init() {
this.contract = await ContractHandler.get(this.contractName, this.web3Helper); this.contract = await ContractHandler.get(this.contractName, this.web3Helper)
} }
public getAddress() { public getAddress() {
return this.contract.address; return this.contract.address
} }
public getEvent(name: string) { public getEvent(name: string) {
if (!this.contract.events[name]) { 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]
} }
} }

View File

@ -1,30 +1,30 @@
import Logger from "../utils/Logger"; import Logger from "../utils/Logger"
export default class EventListener { export default class EventListener {
public static async listenOnce(event: any, eventName: string): Promise<any> { public static async listenOnce(event: any, eventName: string): Promise<any> {
return new Promise<any>((resolve, reject) => { return new Promise<any>((resolve, reject) => {
event.watch((error: any, result: any) => { event.watch((error: any, result: any) => {
event.stopWatching(); event.stopWatching()
if (error) { if (error) {
Logger.log(`Error in keeper ${eventName} event: `, error); Logger.log(`Error in keeper ${eventName} event: `, error)
return reject(error); return reject(error)
} }
resolve(result); resolve(result)
}); })
}); })
} }
public static getEvents(event: any): Promise<any[]> { public static getEvents(event: any): Promise<any[]> {
return new Promise<any>((resolve, reject) => { return new Promise<any>((resolve, reject) => {
event.get((error: any, logs: any[]) => { event.get((error: any, logs: any[]) => {
if (error) { if (error) {
reject(error); reject(error)
throw new Error(error); throw new Error(error)
} else { } else {
resolve(logs); resolve(logs)
} }
}); })
}); })
} }
} }

View File

@ -1,31 +1,31 @@
import Config from "../models/Config"; import Config from "../models/Config"
import OceanAuth from "./Auth"; import OceanAuth from "./Auth"
import OceanMarket from "./Market"; import OceanMarket from "./Market"
import OceanToken from "./Token"; import OceanToken from "./Token"
import Web3Helper from "./Web3Helper"; import Web3Helper from "./Web3Helper"
export default class Keeper { export default class Keeper {
public static async getInstance(config: Config, helper: Web3Helper) { 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.market = await OceanMarket.getInstance(config, helper)
contracts.auth = await OceanAuth.getInstance(config, helper); contracts.auth = await OceanAuth.getInstance(config, helper)
contracts.token = await OceanToken.getInstance(config, helper); contracts.token = await OceanToken.getInstance(config, helper)
return contracts; return contracts
} }
public web3Helper: Web3Helper; public web3Helper: Web3Helper
public token: OceanToken; public token: OceanToken
public market: OceanMarket; public market: OceanMarket
public auth: OceanAuth; public auth: OceanAuth
private config: Config; private config: Config
private constructor(config: Config, helper: Web3Helper) { private constructor(config: Config, helper: Web3Helper) {
this.config = config; this.config = config
this.web3Helper = helper; this.web3Helper = helper
} }
} }

View File

@ -1,56 +1,56 @@
import Asset from "../models/Asset"; import Asset from "../models/Asset"
import Config from "../models/Config"; import Config from "../models/Config"
import Order from "../models/Order"; import Order from "../models/Order"
import Logger from "../utils/Logger"; import Logger from "../utils/Logger"
import ContractWrapperBase from "./ContractWrapperBase"; import ContractWrapperBase from "./ContractWrapperBase"
import Web3Helper from "./Web3Helper"; import Web3Helper from "./Web3Helper"
export default class OceanMarket extends ContractWrapperBase { export default class OceanMarket extends ContractWrapperBase {
public static async getInstance(config: Config, web3Helper: Web3Helper) { public static async getInstance(config: Config, web3Helper: Web3Helper) {
const market = new OceanMarket(config, "OceanMarket", web3Helper); const market = new OceanMarket(config, "OceanMarket", web3Helper)
await market.init(); await market.init()
return market; return market
} }
// call functions (costs no gas) // call functions (costs no gas)
public async isAssetActive(assetId: string): Promise<boolean> { public async isAssetActive(assetId: string): Promise<boolean> {
return this.contract.methods.checkAsset(assetId).call; return this.contract.methods.checkAsset(assetId).call
} }
public async verifyOrderPayment(orderId: string): Promise<boolean> { public async verifyOrderPayment(orderId: string): Promise<boolean> {
return this.contract.methods.verifyPaymentReceived(orderId).call; return this.contract.methods.verifyPaymentReceived(orderId).call
} }
public async getAssetPrice(assetId: string): Promise<number> { public async getAssetPrice(assetId: string): Promise<number> {
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<boolean> { public async requestTokens(amount: number, receiverAddress: string): Promise<boolean> {
return this.contract.methods.requestTokens(amount).send({ return this.contract.methods.requestTokens(amount).send({
from: receiverAddress, from: receiverAddress,
}); })
} }
public async registerAsset(name: string, description: string, public async registerAsset(name: string, description: string,
price: number, publisherAddress: string): Promise<string> { price: number, publisherAddress: string): Promise<string> {
const assetId = await this.contract.methods.generateId(name + description).call(); const assetId = await this.contract.methods.generateId(name + description).call()
Logger.log("Registering: ", assetId); Logger.log("Registering: ", assetId)
const result = await this.contract.methods.register(assetId, price).send({ const result = await this.contract.methods.register(assetId, price).send({
from: publisherAddress, from: publisherAddress,
gas: this.config.defaultGas, gas: this.config.defaultGas,
}, },
); )
Logger.log("Registered: ", result); Logger.log("Registered: ", result)
return assetId; return assetId
} }
public async payAsset(asset: Asset, order: Order, buyerAddress: string): Promise<boolean> { public async payAsset(asset: Asset, order: Order, buyerAddress: string): Promise<boolean> {
Logger.log("Sending payment"); Logger.log("Sending payment")
return this.contract.methods.sendPayment(order.id, asset.publisherId, asset.price, order.timeout).send({ return this.contract.methods.sendPayment(order.id, asset.publisherId, asset.price, order.timeout).send({
from: buyerAddress, from: buyerAddress,
gas: this.config.defaultGas, gas: this.config.defaultGas,
}); })
} }
} }

View File

@ -1,18 +1,17 @@
import Config from "../models/Config"; import Config from "../models/Config"
import Logger from "../utils/Logger"; import ContractBaseWrapper from "./ContractWrapperBase"
import ContractBaseWrapper from "./ContractWrapperBase"; import Web3Helper from "./Web3Helper"
import Web3Helper from "./Web3Helper";
export default class OceanToken extends ContractBaseWrapper { export default class OceanToken extends ContractBaseWrapper {
public static async getInstance(config: Config, web3Helper: Web3Helper) { public static async getInstance(config: Config, web3Helper: Web3Helper) {
const token = new OceanToken(config, "OceanToken", web3Helper); const token = new OceanToken(config, "OceanToken", web3Helper)
await token.init(); await token.init()
return token; return token
} }
public async getTokenBalance(accountAddress: string) { 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<number> { public async getEthBalance(account: string): Promise<number> {
@ -20,18 +19,18 @@ export default class OceanToken extends ContractBaseWrapper {
// Logger.log("getting balance for", account); // Logger.log("getting balance for", account);
this.web3Helper.getWeb3().eth.getBalance(account, "latest", (err: any, balance: number) => { this.web3Helper.getWeb3().eth.getBalance(account, "latest", (err: any, balance: number) => {
if (err) { if (err) {
return reject(err); return reject(err)
} }
// Logger.log("balance", balance); // Logger.log("balance", balance);
resolve(balance); resolve(balance)
}); })
}); })
} }
public async approve(marketAddress: string, price: number, buyerAddress: string) { public async approve(marketAddress: string, price: number, buyerAddress: string) {
return this.contract.methods.approve(marketAddress, price).send({ return this.contract.methods.approve(marketAddress, price).send({
from: buyerAddress, from: buyerAddress,
gas: this.config.defaultGas, gas: this.config.defaultGas,
}); })
} }
} }

View File

@ -1,72 +1,71 @@
import Web3 = require("web3"); import Web3 = require("web3")
import Config from "../models/Config"; import Config from "../models/Config"
import Logger from "../utils/Logger";
export default class Web3Helper { export default class Web3Helper {
private web3: Web3; private web3: Web3
public constructor(config: Config) { public constructor(config: Config) {
const web3Provider = config.web3Provider || new Web3.providers.HttpProvider(config.nodeUri); const web3Provider = config.web3Provider || new Web3.providers.HttpProvider(config.nodeUri)
this.web3 = new Web3(web3Provider); this.web3 = new Web3(web3Provider)
} }
public getWeb3() { public getWeb3() {
return this.web3; return this.web3
} }
public getCurrentProvider() { public getCurrentProvider() {
return this.web3.currentProvider; return this.web3.currentProvider
} }
public async getAccounts(): Promise<any[]> { public async getAccounts(): Promise<any[]> {
return new Promise<any[]>((resolve, reject) => { return new Promise<any[]>((resolve, reject) => {
this.web3.eth.getAccounts((err: any, accounts: string[]) => { this.web3.eth.getAccounts((err: any, accounts: string[]) => {
if (err) { if (err) {
reject(err); reject(err)
throw err; throw err
} }
resolve(accounts); resolve(accounts)
}); })
}); })
} }
public async getNetworkName(): Promise<string> { public async getNetworkName(): Promise<string> {
return new Promise<string>((resolve, reject) => { return new Promise<string>((resolve, reject) => {
let network: string = "unknown"; let network: string = "unknown"
this.web3.eth.net.getId((err, networkId) => { this.web3.eth.net.getId((err, networkId) => {
if (err) { if (err) {
reject(err); reject(err)
throw err; throw err
} }
switch (networkId) { switch (networkId) {
case 1: case 1:
network = "Main"; network = "Main"
break; break
case 2: case 2:
network = "Morden"; network = "Morden"
break; break
case 3: case 3:
network = "Ropsten"; network = "Ropsten"
break; break
case 4: case 4:
network = "Rinkeby"; network = "Rinkeby"
break; break
case 42: case 42:
network = "Kovan"; network = "Kovan"
break; break
default: default:
network = "development"; network = "development"
} }
resolve(network); resolve(network)
}); })
}); })
} }
// web3 wrappers // web3 wrappers
public sign(accountAddress: string, message: string) { public sign(accountAddress: string, message: string) {
return this.web3.eth.sign(accountAddress, message); return this.web3.eth.sign(accountAddress, message)
} }
} }

View File

@ -1,22 +1,22 @@
import Config from "./models/Config"; import Config from "./models/Config"
import Logger from "./utils/Logger"; import Logger from "./utils/Logger"
declare var fetch; declare var fetch
export default class MetaData { export default class MetaData {
private assetsUrl: string; private assetsUrl: string
constructor(config: Config) { constructor(config: Config) {
const providerUri = config.providerUri || null; const providerUri = config.providerUri || null
this.assetsUrl = providerUri + "/assets"; this.assetsUrl = providerUri + "/assets"
} }
public getAssetsMetadata() { public getAssetsMetadata() {
return fetch(this.assetsUrl + "/metadata", {method: "GET"}) return fetch(this.assetsUrl + "/metadata", {method: "GET"})
.then((res) => res.json()) .then((res) => res.json())
.then((data) => JSON.parse(data)); .then((data) => JSON.parse(data))
} }
public publishDataAsset(asset: object) { public publishDataAsset(asset: object) {
@ -27,19 +27,19 @@ export default class MetaData {
headers: {"Content-type": "application/json"}, headers: {"Content-type": "application/json"},
}) })
.then((response: any) => { .then((response: any) => {
Logger.log("Success:", response); Logger.log("Success:", response)
if (response.ok) { if (response.ok) {
Logger.log("Success:", response); Logger.log("Success:", response)
return true; return true
} }
Logger.log("Failed: ", response.status, response.statusText); Logger.log("Failed: ", response.status, response.statusText)
return false; return false
// throw new Error(response.statusText ? response.statusText : // throw new Error(response.statusText ? response.statusText :
// `publish asset failed with status ${response.status}`) // `publish asset failed with status ${response.status}`)
}) })
.catch((error: Error) => { .catch((error: Error) => {
Logger.log(`Publish asset to ocean database could not be completed: ${error.message}`); Logger.log(`Publish asset to ocean database could not be completed: ${error.message}`)
return false; return false
}); })
} }
} }

View File

@ -1,5 +1,5 @@
export default class Asset { export default class Asset {
public assetId: string; public assetId: string
public publisherId: string; public publisherId: string
public price: number; public price: number
} }

View File

@ -1,7 +1,6 @@
export default class Config { export default class Config {
public defaultGas: number = 300000
public defaultGas: number = 300000; public providerUri: string
public providerUri: string; public nodeUri: string
public nodeUri: string; public web3Provider: any
public web3Provider: any;
} }

View File

@ -1,10 +1,10 @@
import Asset from "./Asset"; import Asset from "./Asset"
export default class Order { export default class Order {
public id: string; public id: string
public asset: Asset; public asset: Asset
public assetId: string; public assetId: string
public timeout: any; public timeout: any
public pubkey: string; public pubkey: string
public key: any; public key: any
} }

View File

@ -1,16 +1,16 @@
import Keeper from "../keeper/Keeper"; import Keeper from "../keeper/Keeper"
export default class Asset { export default class Asset {
private keeper: Keeper; private keeper: Keeper
constructor(keeper: Keeper) { constructor(keeper: Keeper) {
this.keeper = keeper; this.keeper = keeper
} }
public isAssetActive(assetId: string): Promise<boolean> { public isAssetActive(assetId: string): Promise<boolean> {
const {market} = this.keeper; const {market} = this.keeper
return market.isAssetActive(assetId); return market.isAssetActive(assetId)
} }
} }

View File

@ -1,21 +1,21 @@
import * as EthCrypto from "eth-crypto"; import * as EthCrypto from "eth-crypto"
import EthEcies from "eth-ecies"; import EthEcies from "eth-ecies"
import * as EthjsUtil from "ethereumjs-util"; import * as EthjsUtil from "ethereumjs-util"
import JWT from "jsonwebtoken"; import JWT from "jsonwebtoken"
import EventListener from "../keeper/EventListener"; import EventListener from "../keeper/EventListener"
import Keeper from "../keeper/Keeper"; import Keeper from "../keeper/Keeper"
import Asset from "../models/Asset"; import Asset from "../models/Asset"
import OrderModel from "../models/Order"; import OrderModel from "../models/Order"
import Logger from "../utils/Logger"; import Logger from "../utils/Logger"
declare var fetch; declare var fetch
export default class Order { export default class Order {
private static create(asset: Asset, args, key): OrderModel { private static create(asset: Asset, args, key): OrderModel {
Logger.log("keeper AccessConsentRequested event received on asset: ", asset.assetId, "\nevent:", args); Logger.log("keeper AccessConsentRequested event received on asset: ", asset.assetId, "\nevent:", args)
const accessId = args._id; const accessId = args._id
Logger.log("got new access request id: ", accessId); Logger.log("got new access request id: ", accessId)
return { return {
id: accessId, id: accessId,
assetId: asset.assetId, assetId: asset.assetId,
@ -23,25 +23,25 @@ export default class Order {
timeout: args._timeout, timeout: args._timeout,
pubkey: args._pubKey, pubkey: args._pubKey,
key, key,
} as OrderModel; } as OrderModel
} }
private keeper: Keeper; private keeper: Keeper
constructor(keeper: Keeper) { constructor(keeper: Keeper) {
this.keeper = keeper; this.keeper = keeper
} }
public async getOrdersByConsumer(consumerAddress: string) { public async getOrdersByConsumer(consumerAddress: string) {
const {auth, market} = this.keeper; const {auth, market} = this.keeper
const accessConsentEvent = auth.getEvent("AccessConsentRequested")({ const accessConsentEvent = auth.getEvent("AccessConsentRequested")({
_consumer: consumerAddress, _consumer: consumerAddress,
}, { }, {
fromBlock: 0, fromBlock: 0,
toBlock: "latest", toBlock: "latest",
}); })
const events = await EventListener.getEvents(accessConsentEvent); const events = await EventListener.getEvents(accessConsentEvent)
const orders = await Promise.all(events const orders = await Promise.all(events
.filter((event: any) => (event.args._consumer === consumerAddress)) .filter((event: any) => (event.args._consumer === consumerAddress))
@ -51,104 +51,104 @@ export default class Order {
status: await auth.getOrderStatus(event.args._id), status: await auth.getOrderStatus(event.args._id),
paid: await market.verifyOrderPayment(event.args._id), paid: await market.verifyOrderPayment(event.args._id),
key: null, key: null,
} as Order))); } as Order)))
Logger.log("Got orders: ", orders); Logger.log("Got orders: ", orders)
return orders; return orders
} }
public async purchaseAsset(asset: Asset, timeout: number, buyerAddress: string): Promise<OrderModel> { public async purchaseAsset(asset: Asset, timeout: number, buyerAddress: string): Promise<OrderModel> {
const {token, market, auth} = this.keeper; const {token, market, auth} = this.keeper
const key = EthCrypto.createIdentity(); const key = EthCrypto.createIdentity()
const publicKey = EthjsUtil.privateToPublic(key.privateKey).toString("hex"); const publicKey = EthjsUtil.privateToPublic(key.privateKey).toString("hex")
const price = await market.getAssetPrice(asset.assetId); const price = await market.getAssetPrice(asset.assetId)
const isValid = await market.isAssetActive(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) { if (!isValid) {
throw new Error("asset not valid"); throw new Error("asset not valid")
} }
try { try {
// Allow market contract to transfer funds on the consumer"s behalf // 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) { } catch (err) {
Logger.log("token approve", err); Logger.log("token approve", err)
} }
try { try {
// Submit the access request // Submit the access request
await auth.initiateAccessRequest(asset, publicKey, timeout, buyerAddress); await auth.initiateAccessRequest(asset, publicKey, timeout, buyerAddress)
} catch (err) { } catch (err) {
Logger.log("initiateAccessRequest", err); Logger.log("initiateAccessRequest", err)
} }
const resourceFilter = { const resourceFilter = {
_resourceId: asset.assetId, _resourceId: asset.assetId,
_consumer: buyerAddress, _consumer: buyerAddress,
}; }
// todo: Event - implement proper eventing // todo: Event - implement proper eventing
const accessConsentRequestedEvent = auth.getEvent("AccessConsentRequested")(resourceFilter); const accessConsentRequestedEvent = auth.getEvent("AccessConsentRequested")(resourceFilter)
let order: OrderModel; let order: OrderModel
const finalOrder: OrderModel = await EventListener.listenOnce( const finalOrder: OrderModel = await EventListener.listenOnce(
accessConsentRequestedEvent, accessConsentRequestedEvent,
"AccessConsentRequested") "AccessConsentRequested")
.then((accessConsentRequestedResult) => { .then((accessConsentRequestedResult) => {
order = Order.create(asset, accessConsentRequestedResult.args, key); order = Order.create(asset, accessConsentRequestedResult.args, key)
const requestIdFilter = { const requestIdFilter = {
_id: order.id, _id: order.id,
}; }
// todo: Event - implement proper eventing // 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) => { .then((accessRequestCommittedResult) => {
return this.payAsset(asset, accessRequestCommittedResult.args, order, buyerAddress); return this.payAsset(asset, accessRequestCommittedResult.args, order, buyerAddress)
}) })
.then(() => { .then(() => {
const requestIdFilter = { const requestIdFilter = {
_id: order.id, _id: order.id,
}; }
// todo: Event - implement proper eventing // todo: Event - implement proper eventing
const tokenPublishedEvent = auth.getEvent("EncryptedTokenPublished")(requestIdFilter); const tokenPublishedEvent = auth.getEvent("EncryptedTokenPublished")(requestIdFilter)
return EventListener.listenOnce(tokenPublishedEvent, "EncryptedTokenPublished"); return EventListener.listenOnce(tokenPublishedEvent, "EncryptedTokenPublished")
}) })
.then((result) => { .then((result) => {
return this.finalizePurchaseAsset( return this.finalizePurchaseAsset(
result, order, key, buyerAddress, result, order, key, buyerAddress,
); )
}); })
return finalOrder; return finalOrder
} }
private async payAsset(asset: Asset, args, order, buyerAddress) { private async payAsset(asset: Asset, args, order, buyerAddress) {
const {market} = this.keeper; const {market} = this.keeper
// send payment // send payment
Logger.log("Sending payment: ", order.id, args._id, asset.publisherId, asset.price, order.timeout); Logger.log("Sending payment: ", order.id, args._id, asset.publisherId, asset.price, order.timeout)
return market.payAsset(asset, order, buyerAddress); return market.payAsset(asset, order, buyerAddress)
} }
private async finalizePurchaseAsset(args, order, key, buyerAddress): Promise<OrderModel> { private async finalizePurchaseAsset(args, order, key, buyerAddress): Promise<OrderModel> {
const {auth, web3Helper} = this.keeper; const {auth, web3Helper} = this.keeper
// Logger.log('keeper EncryptedTokenPublished event received: ', order.id, eventResult.args) // 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 // grab the access token from acl contract
const tokenNo0x = encryptedAccessToken.slice(2); const tokenNo0x = encryptedAccessToken.slice(2)
const encryptedTokenBuffer = Buffer.from(tokenNo0x, "hex"); const encryptedTokenBuffer = Buffer.from(tokenNo0x, "hex")
const privateKey = key.privateKey.slice(2); const privateKey = key.privateKey.slice(2)
const accessTokenEncoded = EthEcies.Decrypt(Buffer.from(privateKey, "hex"), encryptedTokenBuffer); const accessTokenEncoded = EthEcies.Decrypt(Buffer.from(privateKey, "hex"), encryptedTokenBuffer)
const accessToken = JWT.decode(accessTokenEncoded); // Returns a json object const accessToken = JWT.decode(accessTokenEncoded) // Returns a json object
// sign it // sign it
const hexEncrToken = `0x${encryptedTokenBuffer.toString("hex")}`; const hexEncrToken = `0x${encryptedTokenBuffer.toString("hex")}`
const signature = web3Helper.sign(buyerAddress, hexEncrToken); const signature = web3Helper.sign(buyerAddress, hexEncrToken)
const fixedMsgSha = web3Helper.getWeb3().utils.sha3(encryptedAccessToken); const fixedMsgSha = web3Helper.getWeb3().utils.sha3(encryptedAccessToken)
// Download the data set from the provider using the url in the access token // Download the data set from the provider using the url in the access token
// decode the access token, grab the service_endpoint, request_id, // decode the access token, grab the service_endpoint, request_id,
@ -159,7 +159,7 @@ export default class Order {
fixed_msg: fixedMsgSha, fixed_msg: fixedMsgSha,
sigEncJWT: signature, sigEncJWT: signature,
jwt: accessTokenEncoded, jwt: accessTokenEncoded,
}); })
const accessUrl = await fetch(`${accessToken.service_endpoint}/${accessToken.resource_id}`, { const accessUrl = await fetch(`${accessToken.service_endpoint}/${accessToken.resource_id}`, {
method: "POST", method: "POST",
body: payload, body: payload,
@ -169,20 +169,20 @@ export default class Order {
}) })
.then((response: any) => { .then((response: any) => {
if (response.ok) { 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) => { .then((consumptionUrl: string) => {
Logger.log("Success accessing consume endpoint: ", consumptionUrl); Logger.log("Success accessing consume endpoint: ", consumptionUrl)
return consumptionUrl; return consumptionUrl
}) })
.catch((error) => { .catch((error) => {
Logger.error("Error fetching the data asset consumption url: ", error); Logger.error("Error fetching the data asset consumption url: ", error)
}); })
Logger.log("consume url: ", accessUrl); Logger.log("consume url: ", accessUrl)
order.accessUrl = accessUrl; order.accessUrl = accessUrl
return order; return order
} }
} }

View File

@ -1,7 +1,7 @@
import Ocean from "./Ocean"; import Ocean from "./Ocean"
import Logger from "./utils/Logger"; import Logger from "./utils/Logger"
export { export {
Ocean, Ocean,
Logger, Logger,
}; }

View File

@ -1,21 +1,21 @@
export default class Logger { export default class Logger {
public static log(...args: any[]) { public static log(...args: any[]) {
Logger.dispatch("log", ...args); Logger.dispatch("log", ...args)
} }
public static debug(...args: any[]) { public static debug(...args: any[]) {
Logger.dispatch("debug", ...args); Logger.dispatch("debug", ...args)
} }
public static warn(...args: any[]) { public static warn(...args: any[]) {
Logger.dispatch("warn", ...args); Logger.dispatch("warn", ...args)
} }
public static error(...args: any[]) { public static error(...args: any[]) {
Logger.dispatch("error", ...args); Logger.dispatch("error", ...args)
} }
private static dispatch(verb: string, ...args: any[]) { private static dispatch(verb: string, ...args: any[]) {
console[verb](...args); console[verb](...args)
} }
} }

View File

@ -1,24 +1,24 @@
import ContractHandler from "../src/keeper/ContractHandler"; import ContractHandler from "../src/keeper/ContractHandler"
import Keeper from "../src/keeper/Keeper"; import Keeper from "../src/keeper/Keeper"
import Web3Helper from "../src/keeper/Web3Helper"; import Web3Helper from "../src/keeper/Web3Helper"
import Config from "../src/models/Config"; import Config from "../src/models/Config"
import Logger from "../src/utils/Logger"; import Logger from "../src/utils/Logger"
let keeper: Keeper; let keeper: Keeper
before(async () => { before(async () => {
const config: Config = {nodeUri: "http://localhost:8545"} as Config; const config: Config = {nodeUri: "http://localhost:8545"} as Config
const web3Helper = new Web3Helper(config); const web3Helper = new Web3Helper(config)
await ContractHandler.deployContracts(web3Helper); await ContractHandler.deployContracts(web3Helper)
keeper = await Keeper.getInstance(config, web3Helper); keeper = await Keeper.getInstance(config, web3Helper)
}); })
describe("Keeper", () => { describe("Keeper", () => {
it("should keep", async () => { it("should keep", async () => {
const balance = await keeper.token.getTokenBalance("0xB0EdD05A5874c5c1Fcd6bCB4E52143fB7134b7EE"); const balance = await keeper.token.getTokenBalance("0xB0EdD05A5874c5c1Fcd6bCB4E52143fB7134b7EE")
Logger.log(balance); Logger.log(balance)
}); })
}); })

View File

@ -5,7 +5,11 @@
], ],
"jsRules": {}, "jsRules": {},
"rules": { "rules": {
"object-literal-sort-keys": false "object-literal-sort-keys": false,
"semicolon": [
true,
"never"
]
}, },
"rulesDirectory": [] "rulesDirectory": []
} }