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

moved test code to test, added metadata, added endpoint generation to aquarius, removed unused code and tests, updated to latest keeper

This commit is contained in:
Sebastian Gerske 2018-11-07 14:33:56 +01:00
parent 8e3a30990b
commit cbf0b55831
31 changed files with 285 additions and 403 deletions

8
package-lock.json generated
View File

@ -1,6 +1,6 @@
{ {
"name": "@oceanprotocol/squid", "name": "@oceanprotocol/squid",
"version": "0.1.4", "version": "0.1.6",
"lockfileVersion": 1, "lockfileVersion": 1,
"requires": true, "requires": true,
"dependencies": { "dependencies": {
@ -120,9 +120,9 @@
} }
}, },
"@oceanprotocol/keeper-contracts": { "@oceanprotocol/keeper-contracts": {
"version": "0.3.18", "version": "0.3.19",
"resolved": "https://registry.npmjs.org/@oceanprotocol/keeper-contracts/-/keeper-contracts-0.3.18.tgz", "resolved": "https://registry.npmjs.org/@oceanprotocol/keeper-contracts/-/keeper-contracts-0.3.19.tgz",
"integrity": "sha512-gtKc/zohk52JD9FDI9PbwrxDmXjP5GJxoxvUzG0nFCBUEOkvIb31FCaefDFTgyShGscVZc+XNG2RfXDMaD+YwA==" "integrity": "sha512-5pfcJ07v2UH3XwFPYTzPOm1UpArh1KvyDU45i+3YDMnW4LasuPDkf6yfBKOrjTxTEuwmIi8SGYdBrqFmzfPwFQ=="
}, },
"@oceanprotocol/secret-store-client": { "@oceanprotocol/secret-store-client": {
"version": "0.0.7", "version": "0.0.7",

View File

@ -51,7 +51,7 @@
"node": ">=8 <10" "node": ">=8 <10"
}, },
"dependencies": { "dependencies": {
"@oceanprotocol/keeper-contracts": "0.3.18", "@oceanprotocol/keeper-contracts": "0.3.19",
"@oceanprotocol/secret-store-client": "0.0.7", "@oceanprotocol/secret-store-client": "0.0.7",
"bignumber.js": "^8.0.1", "bignumber.js": "^8.0.1",
"eth-crypto": "^1.2.5", "eth-crypto": "^1.2.5",

View File

@ -23,9 +23,10 @@ export default class Aquarius {
return response.text() return response.text()
} }
Logger.error("Failed: ", response.status, response.statusText) Logger.error("Failed: ", response.status, response.statusText)
return null
}) })
.then((consumptionUrl: string): string => { .then((consumptionUrl: string): string => {
Logger.log("Success accessing consume endpoint: ", consumptionUrl) Logger.error("Success accessing consume endpoint: ", consumptionUrl)
return consumptionUrl return consumptionUrl
}) })
.catch((error) => { .catch((error) => {
@ -44,7 +45,8 @@ export default class Aquarius {
if (response.ok) { if (response.ok) {
return response.json() return response.json()
} }
Logger.log("Failed: ", response.status, response.statusText) Logger.error("queryMetadata failed:", response.status, response.statusText)
return null
}) })
.catch((error) => { .catch((error) => {
Logger.error("Error fetching querying metadata: ", error) Logger.error("Error fetching querying metadata: ", error)
@ -66,7 +68,8 @@ export default class Aquarius {
if (response.ok) { if (response.ok) {
return response.json() return response.json()
} }
Logger.log("Failed: ", response.status, response.statusText) Logger.log("queryMetadataByText failed:", response.status, response.statusText)
return null
}) })
.catch((error) => { .catch((error) => {
Logger.error("Error fetching querying metadata: ", error) Logger.error("Error fetching querying metadata: ", error)
@ -83,7 +86,8 @@ export default class Aquarius {
if (response.ok) { if (response.ok) {
return response.json() return response.json()
} }
Logger.log("Failed:", response.status, response.statusText) Logger.error("storeDDO failed:", response.status, response.statusText)
return null
}) })
.catch((error) => { .catch((error) => {
Logger.error("Error fetching querying metadata: ", error) Logger.error("Error fetching querying metadata: ", error)
@ -100,7 +104,8 @@ export default class Aquarius {
if (response.ok) { if (response.ok) {
return response.json() return response.json()
} }
Logger.log("Failed:", response.status, response.statusText) Logger.log("retrieveDDO failed:", response.status, response.statusText)
return null
}) })
.catch((error) => { .catch((error) => {
Logger.error("Error fetching querying metadata: ", error) Logger.error("Error fetching querying metadata: ", error)
@ -108,4 +113,8 @@ export default class Aquarius {
return result return result
} }
public getServiceEndpoint(did) {
return `${this.url}/api/v1/provider/assets/metadata/${did}`
}
} }

View File

@ -10,27 +10,22 @@ export default class MetaData {
type: "dataset", type: "dataset",
description: "Weather information of UK including temperature and humidity", description: "Weather information of UK including temperature and humidity",
size: "3.1gb", size: "3.1gb",
dateCreated: "2012-10-10T17:00:000Z", dateCreated: "2012-02-01T10:55:11+00:00",
author: "Met Office", author: "Met Office",
license: "CC-BY", license: "CC-BY",
copyrightHolder: "Met Office", copyrightHolder: "Met Office",
encoding: "UTF-8", encoding: "UTF-8",
compression: "zip", compression: "zip",
contentType: "text/csv", contentType: "text/csv",
workExample: "423432fsd,51.509865,-0.118092,2011-01-01T10:55:11+00:00,7.2,68", // tslint:disable-next-line
workExample: "stationId,latitude,longitude,datetime,temperature,humidity423432fsd,51.509865,-0.118092,2011-01-01T10:55:11+00:00,7.2,68",
contentUrls: [ contentUrls: [
"https://testocnfiles.blob.core.windows.net/testfiles/testzkp.zip", "https://testocnfiles.blob.core.windows.net/testfiles/testzkp.zip"
], ],
links: [ links: [
{ {sample1: "http://data.ceda.ac.uk/badc/ukcp09/data/gridded-land-obs/gridded-land-obs-daily/"},
sample1: "http://data.ceda.ac.uk/badc/ukcp09/data/gridded-land-obs/gridded-land-obs-daily/", {sample2: "http://data.ceda.ac.uk/badc/ukcp09/data/gridded-land-obs/gridded-land-obs-averages-25km/"},
}, {fieldsDescription: "http://data.ceda.ac.uk/badc/ukcp09/"},
{
sample2: "http://data.ceda.ac.uk/badc/ukcp09/data/gridded-land-obs/gridded-land-obs-averages-25km/",
},
{
fieldsDescription: "http://data.ceda.ac.uk/badc/ukcp09/",
},
], ],
inLanguage: "en", inLanguage: "en",
tags: "weather, uk, 2011, temperature, humidity", tags: "weather, uk, 2011, temperature, humidity",

View File

@ -1,34 +0,0 @@
import DDO from "../ddo/DDO"
import ServiceAgreement from "../ocean/ServiceAgreements/ServiceAgreement"
import {Account, Asset, Logger, Ocean} from "../squid"
(async () => {
const ocean: Ocean = await Ocean.getInstance({
nodeUri: "http://localhost:8545",
aquariusUri: "http://localhost:5000",
parityUri: "http://localhost:9545",
secretStoreUri: "https://secret-store.dev-ocean.com",
threshold: 2,
password: "unittest",
address: "0xed243adfb84a6626eba46178ccb567481c6e655d",
})
const publisher: Account = (await ocean.getAccounts())[0]
const consumer: Account = (await ocean.getAccounts())[0]
const asset: Asset = new Asset(
"Fancy Car Data",
"nice data",
100, publisher)
const ddo: DDO = await ocean.register(asset)
Logger.log("asset did:", ddo.id)
const serviceAgreement: ServiceAgreement = await asset.purchase(consumer)
Logger.log("service agreement id:", serviceAgreement.getId())
const accessGranted: boolean =
await serviceAgreement.grantAccess(asset.getId(), "321721938712931283")
Logger.log("access granted:", accessGranted)
})()

View File

@ -1,29 +0,0 @@
import DDO from "../ddo/DDO"
import ServiceAgreement from "../ocean/ServiceAgreements/ServiceAgreement"
import {Account, Asset, Logger, Ocean} from "../squid"
(async () => {
const ocean: Ocean = await Ocean.getInstance({
nodeUri: "http://localhost:8545",
aquariusUri: "http://localhost:5000",
parityUri: "http://localhost:9545",
secretStoreUri: "https://secret-store.dev-ocean.com",
threshold: 2,
password: "unittest",
address: "0xed243adfb84a6626eba46178ccb567481c6e655d",
})
const publisher: Account = (await ocean.getAccounts())[0]
const consumer: Account = (await ocean.getAccounts())[1]
const asset: Asset = new Asset(
"Fancy Car Data",
"nice data",
100, publisher)
const ddo: DDO = await ocean.register(asset)
Logger.log(ddo.id)
const serviceAgreement: ServiceAgreement = await asset.purchase(consumer)
Logger.log(serviceAgreement.getId())
})()

View File

@ -1,5 +1,6 @@
import DDO from "../ddo/DDO" import DDO from "../ddo/DDO"
import {Account, Asset, Logger, Ocean} from "../squid" import MetaData from "../ddo/MetaData"
import {Account, Logger, Ocean} from "../squid"
(async () => { (async () => {
const ocean: Ocean = await Ocean.getInstance({ const ocean: Ocean = await Ocean.getInstance({
@ -13,11 +14,7 @@ import {Account, Asset, Logger, Ocean} from "../squid"
}) })
const publisher: Account = (await ocean.getAccounts())[0] const publisher: Account = (await ocean.getAccounts())[0]
const asset: Asset = new Asset(
"Fancy Car Data",
"nice data", 100,
publisher)
const ddo: DDO = await ocean.register(asset) const ddo: DDO = await ocean.registerAsset(new MetaData(), publisher)
Logger.log(ddo.id) Logger.log(ddo.id)
})() })()

View File

@ -1,7 +1,4 @@
import Contract from "web3-eth-contract" import Contract from "web3-eth-contract"
import ServiceAgreementTemplate from "../ocean/ServiceAgreements/ServiceAgreementTemplate"
import Access from "../ocean/ServiceAgreements/Templates/Access"
import FitchainCompute from "../ocean/ServiceAgreements/Templates/FitchainCompute"
import Logger from "../utils/Logger" import Logger from "../utils/Logger"
import Keeper from "./Keeper" import Keeper from "./Keeper"
import Web3Provider from "./Web3Provider" import Web3Provider from "./Web3Provider"
@ -18,74 +15,16 @@ export default class ContractHandler {
} }
} }
public static async prepareContracts() { public static set(name: string, contractInstance: Contract) {
ContractHandler.contracts.set(name, contractInstance)
}
const web3 = Web3Provider.getWeb3() public static has(name: string): boolean {
const deployerAddress = (await web3.eth.getAccounts())[0] return ContractHandler.contracts.has(name)
// deploy contracts
await ContractHandler.deployContracts(deployerAddress)
// register templates
await new ServiceAgreementTemplate(new Access()).register(deployerAddress)
await new ServiceAgreementTemplate(new FitchainCompute()).register(deployerAddress)
} }
private static contracts: Map<string, Contract> = new Map<string, Contract>() private static contracts: Map<string, Contract> = new Map<string, Contract>()
private static async deployContracts(deployerAddress: string) {
Logger.log("Trying to deploy contracts")
// deploy libs
/* not part of trilobite
const dll = await ContractHandler.deployContract("DLL", deployerAddress)
const attributeStore = await ContractHandler.deployContract("AttributeStore", deployerAddress)
*/
// deploy contracts
const token = await ContractHandler.deployContract("OceanToken", deployerAddress)
/* not part of trilobite
const plcrVoting = await ContractHandler.deployContract("PLCRVoting", deployerAddress, {
args: [token.options.address],
tokens: [
{
name: "DLL", address: dll.options.address,
}, {
name: "AttributeStore", address: attributeStore.options.address,
},
],
})
/* not part of trilobite
const registry = await ContractHandler.deployContract("OceanRegistry", deployerAddress, {
args: [token.options.address, plcrVoting.options.address],
})
*/
const market = await ContractHandler.deployContract("OceanMarket", deployerAddress, {
args: [token.options.address],
})
const sa = await ContractHandler.deployContract("ServiceAgreement", deployerAddress, {
args: [],
})
await ContractHandler.deployContract("AccessConditions", deployerAddress, {
args: [sa.options.address],
})
await ContractHandler.deployContract("PaymentConditions", deployerAddress, {
args: [sa.options.address, token.options.address],
})
await ContractHandler.deployContract("DIDRegistry", deployerAddress, {})
/* not part of trilobite
const dispute = await ContractHandler.deployContract("OceanDispute", deployerAddress, {
args: [market.options.address, registry.options.address, plcrVoting.options.address],
})
*/
await ContractHandler.deployContract("OceanAuth", deployerAddress, {
args: [market.options.address],
})
}
private static async load(what: string, where: string): Promise<Contract> { private static async load(what: string, where: string): Promise<Contract> {
const web3 = Web3Provider.getWeb3() const web3 = Web3Provider.getWeb3()
// Logger.log("Loading", what, "from", where) // Logger.log("Loading", what, "from", where)
@ -102,53 +41,4 @@ export default class ContractHandler {
ContractHandler.contracts.set(what, contract) ContractHandler.contracts.set(what, contract)
return ContractHandler.contracts.get(what) return ContractHandler.contracts.get(what)
} }
// todo: reactivate for tethys
private static replaceTokens(bytecode: string, tokens: any[]) {
for (const token of tokens) {
bytecode = bytecode.replace(
new RegExp(`_+${token.name}_+`, "g"),
token.address.replace("0x", ""))
}
// Logger.log(bytecode)
return bytecode.toString()
}
private static async deployContract(name: string, from: string, params?): Promise<Contract> {
// dont redeploy if there is already something loaded
if (ContractHandler.contracts.has(name)) {
return ContractHandler.contracts.get(name)
}
const web3 = Web3Provider.getWeb3()
let contractInstance: Contract
try {
Logger.log("Deploying", name)
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) :
artifact.bytecode,
arguments: params && params.args ? params.args : null,
}).send({
from,
gas: 3000000,
gasPrice: 10000000000,
})
ContractHandler.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
}
return contractInstance
}
} }

View File

@ -1,5 +1,6 @@
import OceanAuth from "./contracts/Auth" import OceanAuth from "./contracts/Auth"
import AccessConditions from "./contracts/conditions/AccessConditions" import AccessConditions from "./contracts/conditions/AccessConditions"
import DIDRegistry from "./contracts/DIDRegistry"
import OceanMarket from "./contracts/Market" import OceanMarket from "./contracts/Market"
import ServiceAgreement from "./contracts/ServiceAgreement" import ServiceAgreement from "./contracts/ServiceAgreement"
import OceanToken from "./contracts/Token" import OceanToken from "./contracts/Token"
@ -17,6 +18,7 @@ export default class Keeper {
Keeper.instance.token = await OceanToken.getInstance() Keeper.instance.token = await OceanToken.getInstance()
Keeper.instance.serviceAgreement = await ServiceAgreement.getInstance() Keeper.instance.serviceAgreement = await ServiceAgreement.getInstance()
Keeper.instance.accessConditions = await AccessConditions.getInstance() Keeper.instance.accessConditions = await AccessConditions.getInstance()
Keeper.instance.didRegistry = await DIDRegistry.getInstance()
} }
return Keeper.instance return Keeper.instance
} }
@ -28,6 +30,7 @@ export default class Keeper {
public auth: OceanAuth public auth: OceanAuth
public serviceAgreement: ServiceAgreement public serviceAgreement: ServiceAgreement
public accessConditions: AccessConditions public accessConditions: AccessConditions
public didRegistry: DIDRegistry
public async getNetworkName(): Promise<string> { public async getNetworkName(): Promise<string> {
return Web3Provider.getWeb3().eth.net.getId() return Web3Provider.getWeb3().eth.net.getId()

View File

@ -1,6 +1,5 @@
import {Receipt} from "web3-utils" import {Receipt} from "web3-utils"
import AccessStatus from "../../models/AccessStatus" import AccessStatus from "../../models/AccessStatus"
import Asset from "../../ocean/Asset"
import ContractBase from "./ContractBase" import ContractBase from "./ContractBase"
export default class OceanAuth extends ContractBase { export default class OceanAuth extends ContractBase {
@ -24,12 +23,6 @@ export default class OceanAuth extends ContractBase {
return this.call("getEncryptedAccessToken", [orderId], consumerAddress) return this.call("getEncryptedAccessToken", [orderId], consumerAddress)
} }
public async initiateAccessRequest(asset: Asset, publicKey: string,
timeout: number, buyerAddress: string): Promise<Receipt> {
const args = ["0x" + asset.getId(), asset.publisher.getId(), publicKey, timeout]
return this.send("initiateAccessRequest", buyerAddress, args)
}
public async getTempPubKey(orderId: string) { public async getTempPubKey(orderId: string) {
return this.call("getTempPubKey", [orderId]) return this.call("getTempPubKey", [orderId])
} }

View File

@ -101,5 +101,4 @@ export default abstract class ContractBase {
} }
return foundMethod return foundMethod
} }
} }

View File

@ -1,5 +1,6 @@
import {Receipt} from "web3-utils" import {Receipt} from "web3-utils"
import ValueType from "../../models/ValueType" import ValueType from "../../models/ValueType"
import Web3Provider from "../Web3Provider"
import ContractBase from "./ContractBase" import ContractBase from "./ContractBase"
export default class DIDRegistry extends ContractBase { export default class DIDRegistry extends ContractBase {
@ -14,7 +15,7 @@ export default class DIDRegistry extends ContractBase {
value: string, ownerAddress: string): Promise<Receipt> { value: string, ownerAddress: string): Promise<Receipt> {
return this.send("registerAttribute", return this.send("registerAttribute",
ownerAddress, ["0x" + did, type, key, value], ownerAddress, ["0x" + did, type, Web3Provider.getWeb3().utils.fromAscii(key), value],
) )
} }

View File

@ -2,7 +2,7 @@ import ContractBase from "./ContractBase"
export default class GenericContract extends ContractBase { export default class GenericContract extends ContractBase {
public static async getInstance(contractName: string) { public static async getInstance(contractName: string): Promise<ContractBase> {
const contract: GenericContract = new GenericContract(contractName) const contract: GenericContract = new GenericContract(contractName)
await contract.init() await contract.init()
return contract return contract

View File

@ -1,27 +0,0 @@
import AquariusProvider from "../aquarius/AquariusProvider"
import Account from "./Account"
import IdGenerator from "./IdGenerator"
import OceanBase from "./OceanBase"
import ServiceAgreement from "./ServiceAgreements/ServiceAgreement"
export default class Asset extends OceanBase {
constructor(public name: string,
public description: string,
public price: number,
public publisher: Account) {
super()
}
public async purchase(consumer: Account): Promise<ServiceAgreement> {
const did = `did:op:${this.getId()}`
const ddo = await AquariusProvider.getAquarius().retrieveDDO(did)
const serviceAgreementId: string = IdGenerator.generateId()
const serviceAgreement: ServiceAgreement = await ServiceAgreement.signServiceAgreement(this.getId(),
ddo, serviceAgreementId, consumer, this.publisher)
return serviceAgreement
}
}

View File

@ -1,18 +1,22 @@
import Aquarius from "../aquarius/Aquarius"
import AquariusProvider from "../aquarius/AquariusProvider" import AquariusProvider from "../aquarius/AquariusProvider"
import SearchQuery from "../aquarius/query/SearchQuery" import SearchQuery from "../aquarius/query/SearchQuery"
import ConfigProvider from "../ConfigProvider" import ConfigProvider from "../ConfigProvider"
import DDOCondition from "../ddo/Condition" import DDOCondition from "../ddo/Condition"
import DDO from "../ddo/DDO" import DDO from "../ddo/DDO"
import MetaData from "../ddo/MetaData"
import Parameter from "../ddo/Parameter" import Parameter from "../ddo/Parameter"
import Service from "../ddo/Service" import Service from "../ddo/Service"
import Keeper from "../keeper/Keeper" import Keeper from "../keeper/Keeper"
import Web3Provider from "../keeper/Web3Provider" import Web3Provider from "../keeper/Web3Provider"
import Config from "../models/Config" import Config from "../models/Config"
import ValuePair from "../models/ValuePair" import ValuePair from "../models/ValuePair"
import ValueType from "../models/ValueType"
import Logger from "../utils/Logger"
import Account from "./Account" import Account from "./Account"
import Asset from "./Asset"
import IdGenerator from "./IdGenerator" import IdGenerator from "./IdGenerator"
import Condition from "./ServiceAgreements/Condition" import Condition from "./ServiceAgreements/Condition"
import ServiceAgreement from "./ServiceAgreements/ServiceAgreement"
import ServiceAgreementTemplate from "./ServiceAgreements/ServiceAgreementTemplate" import ServiceAgreementTemplate from "./ServiceAgreements/ServiceAgreementTemplate"
import Access from "./ServiceAgreements/Templates/Access" import Access from "./ServiceAgreements/Templates/Access"
@ -24,6 +28,7 @@ export default class Ocean {
ConfigProvider.setConfig(config) ConfigProvider.setConfig(config)
Ocean.instance = new Ocean() Ocean.instance = new Ocean()
Ocean.instance.keeper = await Keeper.getInstance() Ocean.instance.keeper = await Keeper.getInstance()
Ocean.instance.aquarius = await AquariusProvider.getAquarius()
} }
return Ocean.instance return Ocean.instance
@ -31,8 +36,8 @@ export default class Ocean {
private static instance = null private static instance = null
// @ts-ignore
private keeper: Keeper private keeper: Keeper
private aquarius: Aquarius
private constructor() { private constructor() {
} }
@ -45,10 +50,14 @@ export default class Ocean {
return ethAccounts.map((address: string) => new Account(address)) return ethAccounts.map((address: string) => new Account(address))
} }
public async register(asset: Asset): Promise<DDO> { public async registerAsset(metadata: MetaData, publisher: Account): Promise<DDO> {
const {didRegistry} = this.keeper
const id: string = IdGenerator.generateId()
const did: string = `did:op:${id}`
const serviceDefinitionId: string = IdGenerator.generatePrefixedId()
const assetId: string = IdGenerator.generateId()
const did: string = `did:op:${assetId}`
const template = new Access() const template = new Access()
const serviceAgreementTemplate = new ServiceAgreementTemplate(template) const serviceAgreementTemplate = new ServiceAgreementTemplate(template)
@ -71,45 +80,69 @@ export default class Ocean {
} as DDOCondition } as DDOCondition
}) })
metadata.base.contentUrls = metadata.base.contentUrls.map((contentUrl) => {
Logger.log(contentUrl)
return "0x00000"
})
// create ddo itself // create ddo itself
const ddo: DDO = new DDO({ const ddo: DDO = new DDO({
id: did, id: did,
service: [ service: [
{ {
type: template.templateName, type: template.templateName,
// tslint:disable // tslint:disable-next-line
serviceEndpoint: "http://mybrizo.org/api/v1/brizo/services/consume?pubKey=${pubKey}&serviceId={serviceId}&url={url}", serviceEndpoint: "http://mybrizo.org/api/v1/brizo/services/consume?pubKey=${pubKey}&serviceId={serviceId}&url={url}",
purchaseEndpoint: "http://mybrizo.org/api/v1/brizo/services/access/purchase?", purchaseEndpoint: "http://mybrizo.org/api/v1/brizo/services/access/purchase?",
// the id of the service agreement? // the id of the service agreement?
serviceDefinitionId: IdGenerator.generatePrefixedId(), serviceDefinitionId,
// the id of the service agreement template // the id of the service agreement template
templateId: serviceAgreementTemplate.getId(), templateId: serviceAgreementTemplate.getId(),
conditions: ddoConditions, conditions: ddoConditions,
} as Service, } as Service,
{
metadata,
} as Service,
], ],
}) })
await AquariusProvider.getAquarius().storeDDO(ddo) const storedDdo = await this.aquarius.storeDDO(ddo)
asset.setId(assetId)
return ddo await didRegistry.registerAttribute(id, ValueType.DID, "Metadata", this.aquarius.getServiceEndpoint(did),
publisher.getId())
return storedDdo
}
public async purchase(did: string, consumer: Account): Promise<ServiceAgreement> {
const ddo = await AquariusProvider.getAquarius().retrieveDDO(did)
const id = did.replace("did:op:", "")
const serviceAgreementId: string = IdGenerator.generateId()
const serviceAgreement: ServiceAgreement = await ServiceAgreement.signServiceAgreement(id,
// todo get publisher from ddo
ddo, serviceAgreementId, consumer, new Account())
return serviceAgreement
} }
public async searchAssets(query: SearchQuery): Promise<any[]> { public async searchAssets(query: SearchQuery): Promise<any[]> {
return AquariusProvider.getAquarius().queryMetadata(query) return this.aquarius.queryMetadata(query)
} }
public async searchAssetsByText(text: string): Promise<any[]> { public async searchAssetsByText(text: string): Promise<any[]> {
return AquariusProvider.getAquarius().queryMetadataByText({ return this.aquarius.queryMetadataByText({
text, text,
page: 1, page: 1,
offset: 100, offset: 100,
query: { query: {
value: 1 value: 1,
}, },
sort: { sort: {
value: 1 value: 1,
} },
} as SearchQuery) } as SearchQuery)
} }
} }

View File

@ -12,12 +12,26 @@ import TemplateBase from "./Templates/TemplateBase"
export default class ServiceAgreementTemplate extends OceanBase { export default class ServiceAgreementTemplate extends OceanBase {
private static generateConditionsKey(serviceAgreementTemplateId: string, methodReflection: MethodReflection)
: string {
const values = [
{type: "bytes32", value: serviceAgreementTemplateId} as ValuePair,
{type: "address", value: methodReflection.address} as ValuePair,
{type: "bytes4", value: methodReflection.signature} as ValuePair,
]
return Web3Provider.getWeb3().utils.soliditySha3(...values).toString("hex")
}
public constructor(private template: TemplateBase) {
super(template.id)
}
public async register(templateOwnerAddress: string) public async register(templateOwnerAddress: string)
: Promise<boolean> { : Promise<boolean> {
const dependencyMatrix: number[] = const dependencyMatrix: number[] =
await Promise.all(this.template.Methods.map(async (method: Method) => { await Promise.all(this.template.Methods.map(async (method: Method) => {
// tslint:disable // tslint:disable-next-line
return method.dependency | method.timeout return method.dependency | method.timeout
})) }))
@ -40,6 +54,7 @@ export default class ServiceAgreementTemplate extends OceanBase {
const templateId = receipt.events.SetupAgreementTemplate.returnValues.serviceTemplateId const templateId = receipt.events.SetupAgreementTemplate.returnValues.serviceTemplateId
if (templateId !== this.template.id) { if (templateId !== this.template.id) {
// tslint:disable-next-line
throw new Error(`TemplateId missmatch on ${this.template.templateName}! Should be "${this.template.id}" but is ${templateId}`) throw new Error(`TemplateId missmatch on ${this.template.templateName}! Should be "${this.template.id}" but is ${templateId}`)
} }
@ -50,20 +65,6 @@ export default class ServiceAgreementTemplate extends OceanBase {
return receipt.status return receipt.status
} }
private static generateConditionsKey(serviceAgreementTemplateId: string, methodReflection: MethodReflection)
: string {
const values = [
{type: "bytes32", value: serviceAgreementTemplateId} as ValuePair,
{type: "address", value: methodReflection.address} as ValuePair,
{type: "bytes4", value: methodReflection.signature} as ValuePair,
]
return Web3Provider.getWeb3().utils.soliditySha3(...values).toString("hex")
}
public constructor(private template: TemplateBase) {
super(template.id)
}
/** /**
* gets the status of a service agreement template * gets the status of a service agreement template
*/ */
@ -78,16 +79,6 @@ export default class ServiceAgreementTemplate extends OceanBase {
return new Account(await serviceAgreement.getTemplateOwner(this.id)) return new Account(await serviceAgreement.getTemplateOwner(this.id))
} }
private async getMethodReflections(): Promise<MethodReflection[]> {
const methodReflections: MethodReflection[] =
await Promise.all(this.template.Methods.map(async (method: Method) => {
const methodReflection = await
ContractReflector.reflectContractMethod(method.path)
return methodReflection
}))
return methodReflections
}
public async getConditions(): Promise<Condition[]> { public async getConditions(): Promise<Condition[]> {
const methodReflections = await this.getMethodReflections() const methodReflections = await this.getMethodReflections()
@ -102,4 +93,13 @@ export default class ServiceAgreementTemplate extends OceanBase {
return conditions return conditions
} }
private async getMethodReflections(): Promise<MethodReflection[]> {
const methodReflections: MethodReflection[] =
await Promise.all(this.template.Methods.map(async (method: Method) => {
const methodReflection = await ContractReflector.reflectContractMethod(method.path)
return methodReflection
}))
return methodReflections
}
} }

View File

@ -4,7 +4,7 @@ import TemplateBase from "./TemplateBase"
export default class Access extends TemplateBase { export default class Access extends TemplateBase {
public templateName: string = "Access" public templateName: string = "Access"
public id: string = "0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563" public id: string = "0x044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d"
public Methods: Method[] = [ public Methods: Method[] = [
{ {
path: "PaymentConditions.lockPayment", path: "PaymentConditions.lockPayment",

View File

@ -4,7 +4,7 @@ import TemplateBase from "./TemplateBase"
export default class FitchainCompute extends TemplateBase { export default class FitchainCompute extends TemplateBase {
public templateName: string = "FitchainCompute" public templateName: string = "FitchainCompute"
public id: string = "0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6" public id: string = "0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6"
public Methods: Method[] = [ public Methods: Method[] = [
{ {
path: "PaymentConditions.lockPayment", path: "PaymentConditions.lockPayment",

View File

@ -1,5 +1,4 @@
import Account from "./ocean/Account" import Account from "./ocean/Account"
import Asset from "./ocean/Asset"
import Ocean from "./ocean/Ocean" import Ocean from "./ocean/Ocean"
import ServiceAgreement from "./ocean/ServiceAgreements/ServiceAgreement" import ServiceAgreement from "./ocean/ServiceAgreements/ServiceAgreement"
import Logger from "./utils/Logger" import Logger from "./utils/Logger"
@ -7,7 +6,6 @@ import Logger from "./utils/Logger"
export { export {
Ocean, Ocean,
ServiceAgreement, ServiceAgreement,
Asset,
Logger, Logger,
Account, Account,
} }

View File

@ -13,10 +13,6 @@ describe("Squid", () => {
assert(squid.Logger) assert(squid.Logger)
}) })
it("should expose Asset", async () => {
assert(squid.Asset)
})
it("should expose ServiceAgreement", async () => { it("should expose ServiceAgreement", async () => {
assert(squid.ServiceAgreement) assert(squid.ServiceAgreement)
}) })

View File

@ -80,11 +80,12 @@ describe("DDO", () => {
} as Service, } as Service,
{ {
type: "Consume", type: "Consume",
// tslint:disable // tslint:disable-next-line
serviceEndpoint: "http://mybrizo.org/api/v1/brizo/services/consume?pubKey=${pubKey}&serviceId={serviceId}&url={url}", serviceEndpoint: "http://mybrizo.org/api/v1/brizo/services/consume?pubKey=${pubKey}&serviceId={serviceId}&url={url}",
} as Service, } as Service,
{ {
type: "Compute", type: "Compute",
// tslint:disable-next-line
serviceEndpoint: "http://mybrizo.org/api/v1/brizo/services/compute?pubKey=${pubKey}&serviceId={serviceId}&algo={algo}&container={container}", serviceEndpoint: "http://mybrizo.org/api/v1/brizo/services/compute?pubKey=${pubKey}&serviceId={serviceId}&algo={algo}&container={container}",
} as Service, } as Service,
{ {
@ -105,44 +106,46 @@ describe("DDO", () => {
contentType: "text/csv", contentType: "text/csv",
workExample: "423432fsd,51.509865,-0.118092,2011-01-01T10:55:11+00:00,7.2,68", workExample: "423432fsd,51.509865,-0.118092,2011-01-01T10:55:11+00:00,7.2,68",
contentUrls: [ contentUrls: [
"https://testocnfiles.blob.core.windows.net/testfiles/testzkp.zip" "https://testocnfiles.blob.core.windows.net/testfiles/testzkp.zip",
], ],
links: [ links: [
{ {
// tslint:disable-next-line
sample1: "http://data.ceda.ac.uk/badc/ukcp09/data/gridded-land-obs/gridded-land-obs-daily/" sample1: "http://data.ceda.ac.uk/badc/ukcp09/data/gridded-land-obs/gridded-land-obs-daily/"
}, },
{ {
// tslint:disable-next-line
sample2: "http://data.ceda.ac.uk/badc/ukcp09/data/gridded-land-obs/gridded-land-obs-averages-25km/" sample2: "http://data.ceda.ac.uk/badc/ukcp09/data/gridded-land-obs/gridded-land-obs-averages-25km/"
}, },
{ {
fieldsDescription: "http://data.ceda.ac.uk/badc/ukcp09/" fieldsDescription: "http://data.ceda.ac.uk/badc/ukcp09/",
} },
], ],
inLanguage: "en", inLanguage: "en",
tags: "weather, uk, 2011, temperature, humidity", tags: "weather, uk, 2011, temperature, humidity",
price: 10 price: 10,
} as MetaDataBase, } as MetaDataBase,
curation: { curation: {
"rating": 0.93, rating: 0.93,
"numVotes": 123, numVotes: 123,
"schema": "Binary Votting" schema: "Binary Votting",
} as Curation, } as Curation,
additionalInformation: { additionalInformation: {
updateFrecuency: "yearly", updateFrecuency: "yearly",
structuredMarkup: [ structuredMarkup: [
{ {
"uri": "http://skos.um.es/unescothes/C01194/jsonld", uri: "http://skos.um.es/unescothes/C01194/jsonld",
"mediaType": "application/ld+json" mediaType: "application/ld+json",
} as StructuredMarkup, } as StructuredMarkup,
{ {
"uri": "http://skos.um.es/unescothes/C01194/turtle", uri: "http://skos.um.es/unescothes/C01194/turtle",
"mediaType": "text/turtle" mediaType: "text/turtle",
} as StructuredMarkup } as StructuredMarkup,
] ],
} as AdditionalInformation } as AdditionalInformation,
} as MetaData } as MetaData,
} },
] ],
}) })
describe("#serialize()", () => { describe("#serialize()", () => {
@ -171,11 +174,11 @@ describe("DDO", () => {
const service: Service = { const service: Service = {
serviceEndpoint: "http://", serviceEndpoint: "http://",
description: "nice service" description: "nice service",
} as Service } as Service
const ddo = new DDO({ const ddo = new DDO({
service: [service] service: [service],
}) })
assert(ddo) assert(ddo)
@ -197,8 +200,8 @@ describe("DDO", () => {
const ddo: DDO = DDO.deserialize(ddoString) const ddo: DDO = DDO.deserialize(ddoString)
assert(ddo) assert(ddo)
assert(ddo.id == testDDO.id) assert(ddo.id === testDDO.id)
assert(ddo.publicKey[0].publicKeyPem == testDDO.publicKey[0].publicKeyPem) assert(ddo.publicKey[0].publicKeyPem === testDDO.publicKey[0].publicKeyPem)
}) })
it("should properly deserialize from json file", async () => { it("should properly deserialize from json file", async () => {
@ -206,8 +209,8 @@ describe("DDO", () => {
const ddo: DDO = DDO.deserialize(JSON.stringify(jsonDDO)) const ddo: DDO = DDO.deserialize(JSON.stringify(jsonDDO))
assert(ddo) assert(ddo)
assert(ddo.id == jsonDDO.id) assert(ddo.id === jsonDDO.id)
assert(ddo.publicKey[0].publicKeyPem == jsonDDO.publicKey[0].publicKeyPem) assert(ddo.publicKey[0].publicKeyPem === jsonDDO.publicKey[0].publicKeyPem)
}) })
}) })
}) })

View File

@ -1,10 +1,10 @@
import {assert} from "chai" import {assert} from "chai"
import ConfigProvider from "../../src/ConfigProvider" import ConfigProvider from "../../src/ConfigProvider"
import ContractHandler from "../../src/keeper/ContractHandler"
import Account from "../../src/ocean/Account" import Account from "../../src/ocean/Account"
import Ocean from "../../src/ocean/Ocean" import Ocean from "../../src/ocean/Ocean"
import config from "../config" import config from "../config"
import ContractBaseMock from "../mocks/ContractBase.Mock" import ContractBaseMock from "../mocks/ContractBase.Mock"
import TestContractHandler from "./TestContractHandler"
const wrappedContract = new ContractBaseMock("OceanToken") const wrappedContract = new ContractBaseMock("OceanToken")
let accounts: Account[] let accounts: Account[]
@ -13,7 +13,7 @@ describe("ContractWrapperBase", () => {
before(async () => { before(async () => {
ConfigProvider.setConfig(config) ConfigProvider.setConfig(config)
await ContractHandler.prepareContracts() await TestContractHandler.prepareContracts()
await wrappedContract.initMock() await wrappedContract.initMock()
const ocean: Ocean = await Ocean.getInstance(config) const ocean: Ocean = await Ocean.getInstance(config)
accounts = await ocean.getAccounts() accounts = await ocean.getAccounts()

View File

@ -7,7 +7,6 @@ describe("ContractHandler", () => {
before(async () => { before(async () => {
ConfigProvider.setConfig(config) ConfigProvider.setConfig(config)
await ContractHandler.prepareContracts()
}) })
describe("#get()", () => { describe("#get()", () => {

View File

@ -1,6 +1,5 @@
import {assert} from "chai" import {assert} from "chai"
import ConfigProvider from "../../src/ConfigProvider" import ConfigProvider from "../../src/ConfigProvider"
import ContractHandler from "../../src/keeper/ContractHandler"
import DIDRegistry from "../../src/keeper/contracts/DIDRegistry" import DIDRegistry from "../../src/keeper/contracts/DIDRegistry"
import Web3Provider from "../../src/keeper/Web3Provider" import Web3Provider from "../../src/keeper/Web3Provider"
import ValueType from "../../src/models/ValueType" import ValueType from "../../src/models/ValueType"
@ -9,6 +8,7 @@ import IdGenerator from "../../src/ocean/IdGenerator"
import Ocean from "../../src/ocean/Ocean" import Ocean from "../../src/ocean/Ocean"
import Logger from "../../src/utils/Logger" import Logger from "../../src/utils/Logger"
import config from "../config" import config from "../config"
import TestContractHandler from "./TestContractHandler"
let ocean: Ocean let ocean: Ocean
let didRegistry: DIDRegistry let didRegistry: DIDRegistry
@ -17,7 +17,7 @@ describe("DIDRegistry", () => {
before(async () => { before(async () => {
ConfigProvider.setConfig(config) ConfigProvider.setConfig(config)
await ContractHandler.prepareContracts() await TestContractHandler.prepareContracts()
ocean = await Ocean.getInstance(config) ocean = await Ocean.getInstance(config)
didRegistry = await DIDRegistry.getInstance() didRegistry = await DIDRegistry.getInstance()
}) })

View File

@ -1,8 +1,8 @@
import {assert} from "chai" import {assert} from "chai"
import ConfigProvider from "../../src/ConfigProvider" import ConfigProvider from "../../src/ConfigProvider"
import ContractHandler from "../../src/keeper/ContractHandler"
import Keeper from "../../src/keeper/Keeper" import Keeper from "../../src/keeper/Keeper"
import config from "../config" import config from "../config"
import TestContractHandler from "./TestContractHandler"
let keeper: Keeper let keeper: Keeper
@ -10,7 +10,7 @@ describe("Keeper", () => {
before(async () => { before(async () => {
ConfigProvider.setConfig(config) ConfigProvider.setConfig(config)
await ContractHandler.prepareContracts() await TestContractHandler.prepareContracts()
keeper = await Keeper.getInstance() keeper = await Keeper.getInstance()
}) })

View File

@ -0,0 +1,124 @@
import Contract from "web3-eth-contract"
import ContractHandler from "../../src/keeper/ContractHandler"
import Web3Provider from "../../src/keeper/Web3Provider"
import ServiceAgreementTemplate from "../../src/ocean/ServiceAgreements/ServiceAgreementTemplate"
import Access from "../../src/ocean/ServiceAgreements/Templates/Access"
import FitchainCompute from "../../src/ocean/ServiceAgreements/Templates/FitchainCompute"
import Logger from "../../src/utils/Logger"
export default class TestContractHandler extends ContractHandler {
public static async prepareContracts() {
const web3 = Web3Provider.getWeb3()
const deployerAddress = (await web3.eth.getAccounts())[0]
// deploy contracts
await TestContractHandler.deployContracts(deployerAddress)
// register templates
await new ServiceAgreementTemplate(new Access()).register(deployerAddress)
await new ServiceAgreementTemplate(new FitchainCompute()).register(deployerAddress)
}
private static async deployContracts(deployerAddress: string) {
Logger.log("Trying to deploy contracts")
// deploy libs
/* not part of trilobite
const dll = await ContractHandler.deployContract("DLL", deployerAddress)
const attributeStore = await ContractHandler.deployContract("AttributeStore", deployerAddress)
*/
// deploy contracts
const token = await TestContractHandler.deployContract("OceanToken", deployerAddress)
/* not part of trilobite
const plcrVoting = await ContractHandler.deployContract("PLCRVoting", deployerAddress, {
args: [token.options.address],
tokens: [
{
name: "DLL", address: dll.options.address,
}, {
name: "AttributeStore", address: attributeStore.options.address,
},
],
})
/* not part of trilobite
const registry = await ContractHandler.deployContract("OceanRegistry", deployerAddress, {
args: [token.options.address, plcrVoting.options.address],
})
*/
const market = await TestContractHandler.deployContract("OceanMarket", deployerAddress, {
args: [token.options.address],
})
const sa = await TestContractHandler.deployContract("ServiceAgreement", deployerAddress, {
args: [],
})
await TestContractHandler.deployContract("AccessConditions", deployerAddress, {
args: [sa.options.address],
})
await TestContractHandler.deployContract("PaymentConditions", deployerAddress, {
args: [sa.options.address, token.options.address],
})
await TestContractHandler.deployContract("DIDRegistry", deployerAddress, {})
/* not part of trilobite
const dispute = await ContractHandler.deployContract("OceanDispute", deployerAddress, {
args: [market.options.address, registry.options.address, plcrVoting.options.address],
})
*/
await TestContractHandler.deployContract("OceanAuth", deployerAddress, {
args: [market.options.address],
})
}
private static async deployContract(name: string, from: string, params?): Promise<Contract> {
// dont redeploy if there is already something loaded
if (ContractHandler.has(name)) {
return ContractHandler.get(name)
}
const web3 = Web3Provider.getWeb3()
let contractInstance: Contract
try {
Logger.log("Deploying", name)
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 ?
TestContractHandler.replaceTokens(artifact.bytecode.toString(), params.tokens) :
artifact.bytecode,
arguments: params && params.args ? params.args : null,
}).send({
from,
gas: 3000000,
gasPrice: 10000000000,
})
TestContractHandler.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
}
return contractInstance
}
private static replaceTokens(bytecode: string, tokens: any[]) {
for (const token of tokens) {
bytecode = bytecode.replace(
new RegExp(`_+${token.name}_+`, "g"),
token.address.replace("0x", ""))
}
// Logger.log(bytecode)
return bytecode.toString()
}
}

View File

@ -1,10 +1,10 @@
import {assert} from "chai" import {assert} from "chai"
import ConfigProvider from "../../src/ConfigProvider" import ConfigProvider from "../../src/ConfigProvider"
import ContractHandler from "../../src/keeper/ContractHandler"
import Web3Provider from "../../src/keeper/Web3Provider" import Web3Provider from "../../src/keeper/Web3Provider"
import Account from "../../src/ocean/Account" import Account from "../../src/ocean/Account"
import Ocean from "../../src/ocean/Ocean" import Ocean from "../../src/ocean/Ocean"
import config from "../config" import config from "../config"
import TestContractHandler from "../keeper/TestContractHandler"
let ocean: Ocean let ocean: Ocean
let accounts: Account[] let accounts: Account[]
@ -13,7 +13,7 @@ describe("Account", () => {
before(async () => { before(async () => {
ConfigProvider.setConfig(config) ConfigProvider.setConfig(config)
await ContractHandler.prepareContracts() await TestContractHandler.prepareContracts()
ocean = await Ocean.getInstance(config) ocean = await Ocean.getInstance(config)
accounts = await ocean.getAccounts() accounts = await ocean.getAccounts()

View File

@ -1,65 +0,0 @@
import {assert} from "chai"
import AquariusConnectorProvider from "../../src/aquarius/AquariusConnectorProvider"
import AquariusProvider from "../../src/aquarius/AquariusProvider"
import ConfigProvider from "../../src/ConfigProvider"
import DDO from "../../src/ddo/DDO"
import ContractHandler from "../../src/keeper/ContractHandler"
import Account from "../../src/ocean/Account"
import Asset from "../../src/ocean/Asset"
import Ocean from "../../src/ocean/Ocean"
import ServiceAgreement from "../../src/ocean/ServiceAgreements/ServiceAgreement"
import SecretStoreProvider from "../../src/secretstore/SecretStoreProvider"
import config from "../config"
import AquariusMock from "../mocks/Aquarius.mock"
import AquariusConnectorMock from "../mocks/AquariusConnector.mock"
import SecretStoreMock from "../mocks/SecretStore.mock"
const testName = "Test Asset 2"
const testDescription = "This asset is pure owange"
const testPrice = 100
let ocean: Ocean
let testAsset: Asset
let accounts: Account[]
let testPublisher: Account
let ddo: DDO
describe("Asset", () => {
before(async () => {
ConfigProvider.setConfig(config)
AquariusProvider.setAquarius(new AquariusMock(config))
SecretStoreProvider.setSecretStore(new SecretStoreMock(config))
await ContractHandler.prepareContracts()
ocean = await Ocean.getInstance(config)
accounts = await ocean.getAccounts()
testPublisher = accounts[0]
testAsset = new Asset(testName, testDescription, testPrice, testPublisher)
ddo = await ocean.register(testAsset)
// @ts-ignore
AquariusConnectorProvider.setConnector(new AquariusConnectorMock(ddo))
})
describe("#purchase()", () => {
it("should purchase an asset", async () => {
const consumerAccount = accounts[5]
const serviceAgreement: ServiceAgreement = await testAsset.purchase(consumerAccount)
assert(serviceAgreement)
})
it("should purchase an asset from two different customers", async () => {
const consumerAccount1 = accounts[5]
const serviceAgreement1: ServiceAgreement = await testAsset.purchase(consumerAccount1)
assert(serviceAgreement1)
const consumerAccount2 = accounts[6]
const serviceAgreement2: ServiceAgreement = await testAsset.purchase(consumerAccount2)
assert(serviceAgreement2)
})
})
})

View File

@ -3,12 +3,12 @@ import AquariusProvider from "../../src/aquarius/AquariusProvider"
import SearchQuery from "../../src/aquarius/query/SearchQuery" import SearchQuery from "../../src/aquarius/query/SearchQuery"
import ConfigProvider from "../../src/ConfigProvider" import ConfigProvider from "../../src/ConfigProvider"
import DDO from "../../src/ddo/DDO" import DDO from "../../src/ddo/DDO"
import ContractHandler from "../../src/keeper/ContractHandler" import MetaData from "../../src/ddo/MetaData"
import Account from "../../src/ocean/Account" import Account from "../../src/ocean/Account"
import Asset from "../../src/ocean/Asset"
import Ocean from "../../src/ocean/Ocean" import Ocean from "../../src/ocean/Ocean"
import SecretStoreProvider from "../../src/secretstore/SecretStoreProvider" import SecretStoreProvider from "../../src/secretstore/SecretStoreProvider"
import config from "../config" import config from "../config"
import TestContractHandler from "../keeper/TestContractHandler"
import AquariusMock from "../mocks/Aquarius.mock" import AquariusMock from "../mocks/Aquarius.mock"
import SecretStoreMock from "../mocks/SecretStore.mock" import SecretStoreMock from "../mocks/SecretStore.mock"
@ -16,17 +16,13 @@ let ocean: Ocean
let accounts: Account[] let accounts: Account[]
let testPublisher: Account let testPublisher: Account
const name = "Test Asset 3" + Math.random().toString()
const description = "This asset is pure owange"
const price = 100
describe("Ocean", () => { describe("Ocean", () => {
before(async () => { before(async () => {
ConfigProvider.setConfig(config) ConfigProvider.setConfig(config)
AquariusProvider.setAquarius(new AquariusMock(config)) AquariusProvider.setAquarius(new AquariusMock(config))
SecretStoreProvider.setSecretStore(new SecretStoreMock(config)) SecretStoreProvider.setSecretStore(new SecretStoreMock(config))
await ContractHandler.prepareContracts() await TestContractHandler.prepareContracts()
ocean = await Ocean.getInstance(config) ocean = await Ocean.getInstance(config)
accounts = await ocean.getAccounts() accounts = await ocean.getAccounts()
@ -56,13 +52,14 @@ describe("Ocean", () => {
}) })
describe("#register()", () => { describe("#registerAsset()", () => {
it("should register an asset", async () => { it("should register an asset", async () => {
const asset: Asset = new Asset(name, description, price, testPublisher) const metaData: MetaData = new MetaData()
const ddo: DDO = await ocean.register(asset) const ddo: DDO = await ocean.registerAsset(metaData, testPublisher)
assert(ddo)
assert(ddo.id.startsWith("did:op:")) assert(ddo.id.startsWith("did:op:"))
}) })
}) })

View File

@ -5,7 +5,6 @@ import DDOCondition from "../../src/ddo/Condition"
import DDO from "../../src/ddo/DDO" import DDO from "../../src/ddo/DDO"
import Parameter from "../../src/ddo/Parameter" import Parameter from "../../src/ddo/Parameter"
import Service from "../../src/ddo/Service" import Service from "../../src/ddo/Service"
import ContractHandler from "../../src/keeper/ContractHandler"
import Account from "../../src/ocean/Account" import Account from "../../src/ocean/Account"
import IdGenerator from "../../src/ocean/IdGenerator" import IdGenerator from "../../src/ocean/IdGenerator"
import Ocean from "../../src/ocean/Ocean" import Ocean from "../../src/ocean/Ocean"
@ -14,6 +13,7 @@ import ServiceAgreement from "../../src/ocean/ServiceAgreements/ServiceAgreement
import ServiceAgreementTemplate from "../../src/ocean/ServiceAgreements/ServiceAgreementTemplate" import ServiceAgreementTemplate from "../../src/ocean/ServiceAgreements/ServiceAgreementTemplate"
import Access from "../../src/ocean/ServiceAgreements/Templates/Access" import Access from "../../src/ocean/ServiceAgreements/Templates/Access"
import config from "../config" import config from "../config"
import TestContractHandler from "../keeper/TestContractHandler"
import AquariusConnectorMock from "../mocks/AquariusConnector.mock" import AquariusConnectorMock from "../mocks/AquariusConnector.mock"
let ocean: Ocean let ocean: Ocean
@ -27,7 +27,7 @@ describe("ServiceAgreement", () => {
before(async () => { before(async () => {
ConfigProvider.setConfig(config) ConfigProvider.setConfig(config)
await ContractHandler.prepareContracts() await TestContractHandler.prepareContracts()
ocean = await Ocean.getInstance(config) ocean = await Ocean.getInstance(config)
accounts = await ocean.getAccounts() accounts = await ocean.getAccounts()

View File

@ -1,6 +1,5 @@
import {assert} from "chai" import {assert} from "chai"
import ConfigProvider from "../../src/ConfigProvider" import ConfigProvider from "../../src/ConfigProvider"
import ContractHandler from "../../src/keeper/ContractHandler"
import Account from "../../src/ocean/Account" import Account from "../../src/ocean/Account"
import IdGenerator from "../../src/ocean/IdGenerator" import IdGenerator from "../../src/ocean/IdGenerator"
import Ocean from "../../src/ocean/Ocean" import Ocean from "../../src/ocean/Ocean"
@ -8,6 +7,7 @@ import ServiceAgreementTemplate from "../../src/ocean/ServiceAgreements/ServiceA
import Access from "../../src/ocean/ServiceAgreements/Templates/Access" import Access from "../../src/ocean/ServiceAgreements/Templates/Access"
import TemplateBase from "../../src/ocean/ServiceAgreements/Templates/TemplateBase" import TemplateBase from "../../src/ocean/ServiceAgreements/Templates/TemplateBase"
import config from "../config" import config from "../config"
import TestContractHandler from "../keeper/TestContractHandler"
let ocean: Ocean let ocean: Ocean
let accounts: Account[] let accounts: Account[]
@ -16,7 +16,7 @@ describe("ServiceAgreementTemplate", () => {
before(async () => { before(async () => {
ConfigProvider.setConfig(config) ConfigProvider.setConfig(config)
await ContractHandler.prepareContracts() await TestContractHandler.prepareContracts()
ocean = await Ocean.getInstance(config) ocean = await Ocean.getInstance(config)
accounts = await ocean.getAccounts() accounts = await ocean.getAccounts()
}) })