1
0
mirror of https://github.com/oceanprotocol/ocean.js.git synced 2024-11-26 20:39:05 +01:00

add startOrder

This commit is contained in:
alexcos20 2020-09-11 02:41:20 -07:00
parent 57e8014060
commit 60fc9530ae
5 changed files with 197 additions and 56 deletions

View File

@ -5,7 +5,7 @@ import defaultFactoryABI from '@oceanprotocol/contracts/artifacts/DTFactory.json
import defaultDatatokensABI from '@oceanprotocol/contracts/artifacts/DataTokenTemplate.json' import defaultDatatokensABI from '@oceanprotocol/contracts/artifacts/DataTokenTemplate.json'
import wordListDefault from '../data/words.json' import wordListDefault from '../data/words.json'
import { TransactionReceipt } from 'web3-core'
/** /**
* Provides a interface to DataTokens * Provides a interface to DataTokens
*/ */
@ -350,4 +350,71 @@ export class DataTokens {
public fromWei(amount: string): string { public fromWei(amount: string): string {
return this.web3.utils.fromWei(amount) return this.web3.utils.fromWei(amount)
} }
/** Calculate total fee
* @param {String} dataTokenAddress
* @param {String} amount
* @param {String} mpFeePercentage
* @param {String} address
* @return {Promise<string>} string
*/
public async calculateTotalFee(
dataTokenAddress: string,
amount: string,
mpFeePercentage: string,
address: string
): Promise<string> {
const datatoken = new this.web3.eth.Contract(this.datatokensABI, dataTokenAddress, {
from: address
})
const totalFee = await datatoken.methods
.calculateTotalFee(
this.web3.utils.toWei(amount),
this.web3.utils.toWei(mpFeePercentage)
)
.call()
return this.web3.utils.fromWei(totalFee)
}
/** Start Order
* @param {String} dataTokenAddress
* @param {String} providerAddress
* @param {String} amount
* @param {String} did
* @param {Number} serviceId
* @param {String} mpFeeAddress
* @param {String} mpFeePercentage
* @param {String} address
* @return {Promise<string>} string
*/
public async startOrder(
dataTokenAddress: string,
providerAddress: string,
amount: string,
did: string,
serviceId: number,
mpFeeAddress: string,
mpFeePercentage: string,
address: string
): Promise<TransactionReceipt> {
const datatoken = new this.web3.eth.Contract(this.datatokensABI, dataTokenAddress, {
from: address
})
try {
const trxReceipt = await datatoken.methods
.startOrder(
providerAddress,
this.web3.utils.toWei(amount),
String(did),
String(serviceId),
mpFeeAddress,
this.web3.utils.toWei(mpFeePercentage)
)
.send({ from: address })
return trxReceipt
} catch (e) {
console.error(e)
return null
}
}
} }

View File

@ -11,9 +11,11 @@ import {
import { EditableMetadata } from '../ddo/interfaces/EditableMetadata' import { EditableMetadata } from '../ddo/interfaces/EditableMetadata'
import Account from './Account' import Account from './Account'
import DID from './DID' import DID from './DID'
import { SubscribablePromise } from '../utils' import { SubscribablePromise, didZeroX } from '../utils'
import { Instantiable, InstantiableConfig } from '../Instantiable.abstract' import { Instantiable, InstantiableConfig } from '../Instantiable.abstract'
import { WebServiceConnector } from './utils/WebServiceConnector' import { WebServiceConnector } from './utils/WebServiceConnector'
import { DataTokens } from '../lib'
import BigNumber from 'bignumber.js'
export enum CreateProgressStep { export enum CreateProgressStep {
CreatingDataToken, CreatingDataToken,
@ -396,11 +398,65 @@ export class Assets extends Instantiable {
} }
} }
/**
* Initialize a service
* Can be used to compute totalCost for ordering a service
* @param {String} did
* @param {String} serviceType
* @param {String} consumerAddress
* @param {Number} serviceIndex
* @param {String} mpFeePercent will be converted to Wei
* @param {String} mpAddress mp fee collector address
* @return {Promise<any>} Order details
*/
public async initialize(
did: string,
serviceType: string,
consumerAddress: string,
serviceIndex = -1,
mpFeePercent?: string
): Promise<any> {
const res = await this.ocean.provider.initialize(
did,
serviceIndex,
serviceType,
consumerAddress
)
if (res === null) return null
const providerData = JSON.parse(res)
const { datatokens } = this.ocean
const dtCost = new BigNumber(this.web3.utils.fromWei(String(providerData.numTokens)))
const totalFee = new BigNumber(
await datatokens.calculateTotalFee(
providerData.dataToken,
this.web3.utils.fromWei(String(providerData.numTokens)),
mpFeePercent,
consumerAddress
)
)
providerData.totalFee = totalFee.toString()
providerData.dtCost = dtCost.toString()
providerData.totalCost = dtCost.plus(totalFee).toString()
return providerData
}
/**
* Orders & pays for a service
* @param {String} did
* @param {String} serviceType
* @param {String} consumerAddress
* @param {Number} serviceIndex
* @param {String} mpFeePercent will be converted to Wei
* @param {String} mpAddress mp fee collector address
* @return {Promise<String>} transactionHash of the payment
*/
public async order( public async order(
did: string, did: string,
serviceType: string, serviceType: string,
consumerAddress: string, consumerAddress: string,
serviceIndex = -1 serviceIndex = -1,
mpFeePercent?: string,
mpAddress?: string
): Promise<string> { ): Promise<string> {
if (serviceIndex === -1) { if (serviceIndex === -1) {
const service = await this.getServiceByType(did, serviceType) const service = await this.getServiceByType(did, serviceType)
@ -409,12 +465,53 @@ export class Assets extends Instantiable {
const service = await this.getServiceByIndex(did, serviceIndex) const service = await this.getServiceByIndex(did, serviceIndex)
serviceType = service.type serviceType = service.type
} }
return await this.ocean.provider.initialize( if (!mpFeePercent) mpFeePercent = '0'
did, if (!mpAddress) mpAddress = '0x000000000000000000000000000000000000dEaD'
serviceIndex, const { datatokens } = this.ocean
serviceType, try {
consumerAddress const providerData = await this.initialize(
) did,
serviceType,
consumerAddress,
serviceIndex,
mpFeePercent
)
if (!providerData) return null
const balance = new BigNumber(
await datatokens.balance(providerData.dataToken, consumerAddress)
)
const totalCost = new BigNumber(providerData.totalCost)
if (balance.isLessThanOrEqualTo(totalCost)) {
console.error('Not enough funds')
return null
}
console.log(
'Balance:' +
balance.toString() +
'| dtCost:' +
providerData.dtCost.toString() +
'|Fees:' +
providerData.totalFee.toString() +
'|Total:' +
providerData.totalCost.toString()
)
const txid = await datatokens.startOrder(
providerData.dataToken,
providerData.to,
String(providerData.numTokens),
didZeroX(did),
serviceIndex,
mpAddress,
mpFeePercent,
consumerAddress
)
if (txid) return txid.transactionHash
else return null
} catch (e) {
console.error(e)
return null
}
} }
// marketplace flow // marketplace flow

View File

@ -87,7 +87,7 @@ export class Compute extends Instantiable {
algorithmDataToken?: string algorithmDataToken?: string
): Promise<ComputeJob> { ): Promise<ComputeJob> {
output = this.checkOutput(consumerAccount, output) output = this.checkOutput(consumerAccount, output)
if (did) { if (did && txId) {
const computeJobsList = await this.ocean.provider.compute( const computeJobsList = await this.ocean.provider.compute(
'post', 'post',
did, did,
@ -349,7 +349,9 @@ export class Compute extends Instantiable {
datasetDid: string, datasetDid: string,
serviceIndex: number, serviceIndex: number,
algorithmDid?: string, algorithmDid?: string,
algorithmMeta?: MetadataAlgorithm algorithmMeta?: MetadataAlgorithm,
mpFeePercent?: string,
mpAddress?: string
): SubscribablePromise<OrderProgressStep, string> { ): SubscribablePromise<OrderProgressStep, string> {
return new SubscribablePromise(async (observer) => { return new SubscribablePromise(async (observer) => {
const ddo: DDO = await this.ocean.assets.resolve(datasetDid) const ddo: DDO = await this.ocean.assets.resolve(datasetDid)
@ -380,7 +382,10 @@ export class Compute extends Instantiable {
const order = await this.ocean.assets.order( const order = await this.ocean.assets.order(
datasetDid, datasetDid,
service.type, service.type,
consumerAccount consumerAccount,
-1,
mpFeePercent,
mpAddress
) )
return order return order
}) })

View File

@ -270,16 +270,9 @@ describe('Compute flow', () => {
algorithmMeta algorithmMeta
) )
assert(order != null) assert(order != null)
const computeOrder = JSON.parse(order)
const tx = await datatoken.transferWei(
computeOrder.dataToken,
computeOrder.to,
String(computeOrder.numTokens),
computeOrder.from
)
const response = await ocean.compute.start( const response = await ocean.compute.start(
ddo.id, ddo.id,
tx.transactionHash, order,
tokenAddress, tokenAddress,
bob, bob,
undefined, undefined,
@ -293,6 +286,7 @@ describe('Compute flow', () => {
}) })
it('Bob should get status of a compute job', async () => { it('Bob should get status of a compute job', async () => {
assert(jobId != null)
const response = await ocean.compute.status(bob, ddo.id, jobId) const response = await ocean.compute.status(bob, ddo.id, jobId)
assert(response[0].jobId === jobId) assert(response[0].jobId === jobId)
}) })
@ -302,6 +296,7 @@ describe('Compute flow', () => {
assert(response.length > 0) assert(response.length > 0)
}) })
it('Bob should stop compute job', async () => { it('Bob should stop compute job', async () => {
assert(jobId != null)
await ocean.compute.stop(bob, ddo.id, jobId) await ocean.compute.stop(bob, ddo.id, jobId)
const response = await ocean.compute.status(bob, ddo.id, jobId) const response = await ocean.compute.status(bob, ddo.id, jobId)
assert(response[0].stopreq === 1) assert(response[0].stopreq === 1)
@ -338,13 +333,7 @@ describe('Compute flow', () => {
serviceAlgo.type, serviceAlgo.type,
bob.getId() bob.getId()
) )
const algoOrder = JSON.parse(orderalgo) assert(orderalgo != null)
const algoTx = await datatoken.transferWei(
algoOrder.dataToken,
algoOrder.to,
String(algoOrder.numTokens),
algoOrder.from
)
const order = await ocean.compute.order( const order = await ocean.compute.order(
bob.getId(), bob.getId(),
ddo.id, ddo.id,
@ -353,16 +342,9 @@ describe('Compute flow', () => {
undefined undefined
) )
assert(order != null) assert(order != null)
const computeOrder = JSON.parse(order)
const tx = await datatoken.transferWei(
computeOrder.dataToken,
computeOrder.to,
String(computeOrder.numTokens),
computeOrder.from
)
const response = await ocean.compute.start( const response = await ocean.compute.start(
ddo.id, ddo.id,
tx.transactionHash, order,
tokenAddress, tokenAddress,
bob, bob,
algorithmAsset.id, algorithmAsset.id,
@ -370,7 +352,7 @@ describe('Compute flow', () => {
output, output,
computeService.index, computeService.index,
computeService.type, computeService.type,
algoTx.transactionHash, orderalgo,
algorithmAsset.dataToken algorithmAsset.dataToken
) )
jobId = response.jobId jobId = response.jobId

View File

@ -159,26 +159,16 @@ describe('Marketplace flow', () => {
}) })
it('Bob consumes asset 1', async () => { it('Bob consumes asset 1', async () => {
await ocean.assets await ocean.assets.order(ddo.id, accessService.type, bob.getId()).then(async (tx) => {
.order(ddo.id, accessService.type, bob.getId()) assert(tx != null)
.then(async (res: any) => { await ocean.assets.download(
res = JSON.parse(res) ddo.id,
return await datatoken.transferWei( tx,
res.dataToken, tokenAddress,
res.to, bob,
String(res.numTokens), './node_modules/my-datasets'
res.from )
) })
})
.then(async (tx) => {
await ocean.assets.download(
ddo.id,
tx.transactionHash,
tokenAddress,
bob,
'./node_modules/my-datasets'
)
})
}) })
it('owner can list there assets', async () => { it('owner can list there assets', async () => {
const assets = await ocean.assets.ownerAssets(alice.getId()) const assets = await ocean.assets.ownerAssets(alice.getId())