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

new structure

This commit is contained in:
Sebastian Gerske 2018-10-01 18:10:57 +02:00
parent d63fc69dab
commit 4038697a4b
4 changed files with 92 additions and 186 deletions

View File

@ -1,30 +1,38 @@
import Config from "../utils/config"; import BigNumber from "bignumber.js";
import Web3Helper from "../utils/Web3Helper"; import Asset from "../models/Asset";
import ContractLoader from "./contractLoader"; import Config from "../models/Config";
import KeeperBase from "./keeper-base"; 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) { public static async getInstance(config: Config, web3Helper: Web3Helper) {
const auth = new OceanAuth(config, web3Helper); const auth = new OceanAuth(config, "OceanAuth", web3Helper);
await auth.init();
auth.contract = await ContractLoader.load("OceanAuth", auth.web3Helper);
return auth; return auth;
} }
private constructor(config: Config, web3Helper: Web3Helper) { public async getOrderStatus(orderId: string): Promise<number> {
super(config, web3Helper); return this.contract.statusOfAccessRequest.call(orderId)
.then((status: BigNumber) => status.toNumber());
} }
public cancelAccessRequest(orderId: string, senderAddress: string) { public async cancelAccessRequest(orderId: string, senderAddress: string) {
return this.contract.cancelAccessRequest(orderId, {from: senderAddress}); return this.contract.cancelAccessRequest.send(orderId, {
from: senderAddress,
});
} }
public getOrderStatus(orderId: string) { public async getEncryptedAccessToken(orderId: string, senderAddress: string) {
return this.contract.statusOfAccessRequest(orderId); return this.contract.getEncryptedAccessToken.send(orderId, {
from: senderAddress,
});
} }
public getEncryptedAccessToken(orderId: string, senderAddress: string) { public async initiateAccessRequest(asset: Asset, publicKey: string, timeout, buyerAddress: string) {
return this.contract.getEncryptedAccessToken(orderId, {from: senderAddress}); return this.contract.initiateAccessRequest.send(
asset.assetId, asset.publisherId, publicKey, timeout, {
from: buyerAddress, gas: this.config.defaultGas,
});
} }
} }

View File

@ -1,61 +1,56 @@
import BigNumber from "bignumber.js"; import Asset from "../models/Asset";
import Config from "../utils/config"; import Config from "../models/Config";
import Logger from "../utils/logger"; import Order from "../models/Order";
import Web3Helper from "../utils/Web3Helper"; import Logger from "../utils/Logger";
import ContractLoader from "./contractLoader"; import ContractWrapperBase from "./ContractWrapperBase";
import KeeperBase from "./keeper-base"; import Web3Helper from "./Web3Helper";
export default class OceanMarket extends KeeperBase { 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, web3Helper); const market = new OceanMarket(config, "OceanMarket", web3Helper);
market.contract = await ContractLoader.load("OceanMarket", market.web3Helper); await market.init();
return market; return market;
} }
private constructor(config: Config, web3Helper: Web3Helper) {
super(config, web3Helper);
}
// call functions (costs no gas) // call functions (costs no gas)
public checkAsset(assetId: string) { public async isAssetActive(assetId: string): Promise<boolean> {
return this.contract.checkAsset(assetId); return this.contract.methods.checkAsset(assetId).call;
} }
public verifyOrderPayment(orderId: string): boolean { public async verifyOrderPayment(orderId: string): Promise<boolean> {
return this.contract.verifyPaymentReceived(orderId); return this.contract.methods.verifyPaymentReceived(orderId).call;
} }
public getAssetPrice(assetId: string) { public async getAssetPrice(assetId: string): Promise<number> {
return this.contract.getAssetPrice(assetId) return this.contract.methods.getAssetPrice(assetId).call().then((result) => result.toNumber());
.then((price: BigNumber) => price.toNumber());
} }
// Transactions with gas cost public async requestTokens(amount: number, receiverAddress: string): Promise<boolean> {
public requestTokens(amount: number, address: string) { return this.contract.methods.requestTokens(amount).send({
return this.contract.requestTokens(amount, {from: address}); from: receiverAddress,
});
} }
public async registerAsset(name: string, description: string, price: number, publisherAddress: string) { public async registerAsset(name: string, description: string,
const assetId = await this.contract.generateId(name + description); price: number, publisherAddress: string): Promise<string> {
const result = await this.contract.register( const assetId = await this.contract.methods.generateId(name + description).call();
assetId, Logger.log("Registering: ", assetId);
price, { 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(assetId: string, order: any, publisherAddress: string, senderAddress: string) { public async payAsset(asset: Asset, order: Order, buyerAddress: string): Promise<boolean> {
const assetPrice = await this.contract.getAssetPrice(assetId) Logger.log("Sending payment");
.then((price: BigNumber) => price.toNumber()); return this.contract.methods.sendPayment(order.id, asset.publisherId, asset.price, order.timeout).send({
this.contract.sendPayment(order.id, publisherAddress, assetPrice, order.timeout, { from: buyerAddress,
from: senderAddress, gas: this.config.defaultGas,
gas: 2000000,
}); });
} }
} }

View File

@ -1,30 +1,24 @@
import Config from "../utils/config"; import Config from "../models/config";
import Logger from "../utils/logger"; import Logger from "../utils/Logger";
import Web3Helper from "../utils/Web3Helper"; import ContractBaseWrapper from "./ContractWrapperBase";
import ContractLoader from "./contractLoader"; import Web3Helper from "./Web3Helper";
import KeeperBase from "./keeper-base";
export default class OceanToken extends KeeperBase { 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, web3Helper); const token = new OceanToken(config, "OceanToken", web3Helper);
token.contract = await ContractLoader.load("OceanToken", token.web3Helper); await token.init();
return token; return token;
} }
private constructor(config: Config, web3Helper: Web3Helper) { public async getTokenBalance(accountAddress: string) {
super(config, web3Helper); return this.contract.methods.balanceOf(accountAddress).call();
}
public getTokenBalance(accountAddress: string) {
return this.contract.balanceOf.call(accountAddress);
} }
public async getEthBalance(account: string): Promise<number> { public async getEthBalance(account: string): Promise<number> {
return new Promise<number>((resolve, reject) => { return new Promise<number>((resolve, reject) => {
// Logger.log("getting balance for", account); // 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) { if (err) {
return reject(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,
});
}
} }

View File

@ -1,31 +1,27 @@
import BigNumber from "bignumber.js"; import Keeper from "./keeper/Keeper";
import OceanAuth from "./keeper/auth"; import Web3Helper from "./keeper/Web3Helper";
import OceanMarket from "./keeper/market";
import OceanToken from "./keeper/token";
import MetaData from "./metadata"; import MetaData from "./metadata";
import Config from "./utils/config"; import Config from "./models/config";
import Logger from "./utils/logger"; import Asset from "./ocean/Asset";
import Web3Helper from "./utils/Web3Helper"; 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.market = await OceanMarket.getInstance(config, ocean.helper); ocean.order = new Order(ocean.keeper);
ocean.auth = await OceanAuth.getInstance(config, ocean.helper); ocean.asset = new Asset(ocean.keeper);
ocean.token = await OceanToken.getInstance(config, ocean.helper);
return ocean; return ocean;
} }
public token: OceanToken; public order: Order;
public market: OceanMarket; public asset: Asset;
public auth: OceanAuth;
public helper: Web3Helper; public helper: Web3Helper;
public metadata: MetaData; public metadata: MetaData;
private keeper: Keeper;
private config: Config; private config: Config;
private constructor(config: Config) { private constructor(config: Config) {
@ -36,10 +32,17 @@ export default class Ocean {
this.metadata = new MetaData(config); this.metadata = new MetaData(config);
} }
// Transactions with gas cost
public async requestTokens(amount: number, receiver: string): Promise<boolean> {
return this.keeper.market.requestTokens(amount, receiver);
}
public async getAccounts() { 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) // await ocean.market.requestTokens(account, 1000)
const {token} = this;
return { return {
name: account, name: account,
balance: { 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<any[]>((resolve, reject) => {
outerResolve = resolve;
outerReject = reject;
});
const getEvents = (): Promise<any[]> => {
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);
});
}
} }