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

Change linter config.

This commit is contained in:
Pedro Gutiérrez 2019-09-09 12:18:54 +02:00 committed by Matthias Kretschmann
parent 13e43d7b40
commit 3d7d1f3972
Signed by: m
GPG Key ID: 606EEEF3C479A91F
81 changed files with 460 additions and 1699 deletions

View File

@ -1,5 +1,6 @@
{ {
"semi": false, "semi": false,
"singleQuote": true, "singleQuote": true,
"printWidth": 120,
"trailingComma": "none" "trailingComma": "none"
} }

View File

@ -44,12 +44,7 @@ if (process.env.SEED_WORDS) {
const seedphrase = process.env.SEED_WORDS const seedphrase = process.env.SEED_WORDS
// @ts-ignore // @ts-ignore
configJson.web3Provider = new HDWalletProvider( configJson.web3Provider = new HDWalletProvider(seedphrase, configJson.nodeUri, 0, 5)
seedphrase,
configJson.nodeUri,
0,
5
)
} }
export const config: Config & { forceVerbose: Config } = configJson as any export const config: Config & { forceVerbose: Config } = configJson as any

View File

@ -32,49 +32,35 @@ describe('Asset Owners', () => {
it('should set the provider of an asset', async () => { it('should set the provider of an asset', async () => {
const ddo = await ocean.assets.create(metadata as any, account1) const ddo = await ocean.assets.create(metadata as any, account1)
const isProvider = await ocean.keeper.didRegistry.isDIDProvider( const isProvider = await ocean.keeper.didRegistry.isDIDProvider(ddo.id, config.brizoAddress)
ddo.id,
config.brizoAddress
)
assert.isTrue(isProvider) assert.isTrue(isProvider)
}) })
it('should get the assets owned by a user', async () => { it('should get the assets owned by a user', async () => {
const { length: initialLength } = await ocean.assets.ownerAssets( const { length: initialLength } = await ocean.assets.ownerAssets(account2.getId())
account2.getId()
)
await ocean.assets.create(metadata as any, account1) await ocean.assets.create(metadata as any, account1)
await ocean.assets.create(metadata as any, account1) await ocean.assets.create(metadata as any, account1)
await ocean.assets.create(metadata as any, account2) await ocean.assets.create(metadata as any, account2)
const { length: finalLength } = await ocean.assets.ownerAssets( const { length: finalLength } = await ocean.assets.ownerAssets(account2.getId())
account2.getId()
)
assert.equal(finalLength - initialLength, 1) assert.equal(finalLength - initialLength, 1)
}) })
it('should get the assets that can be consumed by a user', async () => { it('should get the assets that can be consumed by a user', async () => {
const { length: initialLength } = await ocean.assets.consumerAssets( const { length: initialLength } = await ocean.assets.consumerAssets(account2.getId())
account2.getId()
)
const ddo = await ocean.assets.create(metadata as any, account1) const ddo = await ocean.assets.create(metadata as any, account1)
const { length: finalLength1 } = await ocean.assets.consumerAssets( const { length: finalLength1 } = await ocean.assets.consumerAssets(account2.getId())
account2.getId()
)
assert.equal(finalLength1 - initialLength, 0) assert.equal(finalLength1 - initialLength, 0)
// Granting access // Granting access
try { try {
await account2.requestTokens( await account2.requestTokens(+metadata.main.price * 10 ** -(await ocean.keeper.token.decimals()))
+metadata.main.price *
10 ** -(await ocean.keeper.token.decimals())
)
} catch {} } catch {}
const { index } = ddo.findServiceByType('access') const { index } = ddo.findServiceByType('access')
@ -82,9 +68,7 @@ describe('Asset Owners', () => {
await ocean.assets.order(ddo.id, index, account2) await ocean.assets.order(ddo.id, index, account2)
// Access granted // Access granted
const { length: finalLength2 } = await ocean.assets.consumerAssets( const { length: finalLength2 } = await ocean.assets.consumerAssets(account2.getId())
account2.getId()
)
assert.equal(finalLength2 - initialLength, 1) assert.equal(finalLength2 - initialLength, 1)
}) })
}) })

View File

@ -36,53 +36,29 @@ describe('Consume Asset', () => {
assert.isDefined(ddo, 'Register has not returned a DDO') assert.isDefined(ddo, 'Register has not returned a DDO')
assert.match(ddo.id, /^did:op:[a-f0-9]{64}$/, 'DDO id is not valid') assert.match(ddo.id, /^did:op:[a-f0-9]{64}$/, 'DDO id is not valid')
assert.isAtLeast( assert.isAtLeast(ddo.authentication.length, 1, 'Default authentication not added')
ddo.authentication.length, assert.isDefined(ddo.findServiceByType('access'), "DDO access service doesn't exist")
1,
'Default authentication not added'
)
assert.isDefined(
ddo.findServiceByType('access'),
"DDO access service doesn't exist"
)
}) })
it('should be able to request tokens for consumer', async () => { it('should be able to request tokens for consumer', async () => {
const initialBalance = (await consumer.getBalance()).ocn const initialBalance = (await consumer.getBalance()).ocn
const claimedTokens = const claimedTokens = +metadata.main.price * 10 ** -(await ocean.keeper.token.decimals())
+metadata.main.price * 10 ** -(await ocean.keeper.token.decimals())
try { try {
await consumer.requestTokens(claimedTokens) await consumer.requestTokens(claimedTokens)
} catch {} } catch {}
assert.equal( assert.equal((await consumer.getBalance()).ocn, initialBalance + claimedTokens, 'OCN Tokens not delivered')
(await consumer.getBalance()).ocn,
initialBalance + claimedTokens,
'OCN Tokens not delivered'
)
}) })
it('should sign the service agreement', async () => { it('should sign the service agreement', async () => {
const accessService = ddo.findServiceByType('access') const accessService = ddo.findServiceByType('access')
serviceAgreementSignatureResult = await ocean.agreements.prepare( serviceAgreementSignatureResult = await ocean.agreements.prepare(ddo.id, accessService.index, consumer)
ddo.id,
accessService.index,
consumer
)
const { agreementId, signature } = serviceAgreementSignatureResult const { agreementId, signature } = serviceAgreementSignatureResult
assert.match( assert.match(agreementId, /^0x[a-f0-9]{64}$/, 'Service agreement ID seems not valid')
agreementId, assert.match(signature, /^0x[a-f0-9]{130}$/, 'Service agreement signature seems not valid')
/^0x[a-f0-9]{64}$/,
'Service agreement ID seems not valid'
)
assert.match(
signature,
/^0x[a-f0-9]{130}$/,
'Service agreement signature seems not valid'
)
}) })
it('should execute the service agreement', async () => { it('should execute the service agreement', async () => {
@ -101,9 +77,7 @@ describe('Consume Asset', () => {
}) })
it('should get the agreement conditions status not fulfilled', async () => { it('should get the agreement conditions status not fulfilled', async () => {
const status = await ocean.agreements.status( const status = await ocean.agreements.status(serviceAgreementSignatureResult.agreementId)
serviceAgreementSignatureResult.agreementId
)
assert.deepEqual(status, { assert.deepEqual(status, {
lockReward: ConditionState.Unfulfilled, lockReward: ConditionState.Unfulfilled,
@ -144,9 +118,7 @@ describe('Consume Asset', () => {
}) })
it('should get the agreement conditions status fulfilled', async () => { it('should get the agreement conditions status fulfilled', async () => {
const status = await ocean.agreements.status( const status = await ocean.agreements.status(serviceAgreementSignatureResult.agreementId)
serviceAgreementSignatureResult.agreementId
)
assert.deepEqual(status, { assert.deepEqual(status, {
lockReward: ConditionState.Fulfilled, lockReward: ConditionState.Fulfilled,
@ -175,11 +147,7 @@ describe('Consume Asset', () => {
}) })
}) })
assert.deepEqual( assert.deepEqual(files, ['README.md', 'package.json'], 'Stored files are not correct.')
files,
['README.md', 'package.json'],
'Stored files are not correct.'
)
}) })
it('should consume and store one asset', async () => { it('should consume and store one asset', async () => {

View File

@ -41,9 +41,7 @@ describe('Consume Asset (Brizo)', () => {
it('should regiester an asset', async () => { it('should regiester an asset', async () => {
const steps = [] const steps = []
ddo = await ocean.assets ddo = await ocean.assets.create(metadata as any, publisher).next(step => steps.push(step))
.create(metadata as any, publisher)
.next(step => steps.push(step))
assert.instanceOf(ddo, DDO) assert.instanceOf(ddo, DDO)
assert.deepEqual(steps, [0, 1, 2, 3, 4, 5, 6, 7]) assert.deepEqual(steps, [0, 1, 2, 3, 4, 5, 6, 7])
@ -53,16 +51,11 @@ describe('Consume Asset (Brizo)', () => {
const accessService = ddo.findServiceByType('access') const accessService = ddo.findServiceByType('access')
try { try {
await consumer.requestTokens( await consumer.requestTokens(+metadata.main.price * 10 ** -(await ocean.keeper.token.decimals()))
+metadata.main.price *
10 ** -(await ocean.keeper.token.decimals())
)
} catch {} } catch {}
const steps = [] const steps = []
agreementId = await ocean.assets agreementId = await ocean.assets.order(ddo.id, accessService.index, consumer).next(step => steps.push(step))
.order(ddo.id, accessService.index, consumer)
.next(step => steps.push(step))
assert.isDefined(agreementId) assert.isDefined(agreementId)
assert.deepEqual(steps, [0, 1, 2, 3]) assert.deepEqual(steps, [0, 1, 2, 3])
@ -72,13 +65,7 @@ describe('Consume Asset (Brizo)', () => {
const accessService = ddo.findServiceByType('access') const accessService = ddo.findServiceByType('access')
const folder = '/tmp/ocean/squid-js' const folder = '/tmp/ocean/squid-js'
const path = await ocean.assets.consume( const path = await ocean.assets.consume(agreementId, ddo.id, accessService.index, consumer, folder)
agreementId,
ddo.id,
accessService.index,
consumer,
folder
)
assert.include(path, folder, 'The storage path is not correct.') assert.include(path, folder, 'The storage path is not correct.')
@ -88,10 +75,6 @@ describe('Consume Asset (Brizo)', () => {
}) })
}) })
assert.deepEqual( assert.deepEqual(files, ['README.md', 'package.json'], 'Stored files are not correct.')
files,
['README.md', 'package.json'],
'Stored files are not correct.'
)
}) })
}) })

View File

@ -51,17 +51,10 @@ xdescribe('Consume Asset (Large size)', () => {
const accessService = ddo.findServiceByType('access') const accessService = ddo.findServiceByType('access')
try { try {
await consumer.requestTokens( await consumer.requestTokens(+metadata.main.price * 10 ** -(await ocean.keeper.token.decimals()))
+metadata.main.price *
10 ** -(await ocean.keeper.token.decimals())
)
} catch {} } catch {}
agreementId = await ocean.assets.order( agreementId = await ocean.assets.order(ddo.id, accessService.index, consumer)
ddo.id,
accessService.index,
consumer
)
assert.isDefined(agreementId) assert.isDefined(agreementId)
}) })
@ -70,13 +63,7 @@ xdescribe('Consume Asset (Large size)', () => {
const accessService = ddo.findServiceByType('access') const accessService = ddo.findServiceByType('access')
const folder = '/tmp/ocean/squid-js' const folder = '/tmp/ocean/squid-js'
const path = await ocean.assets.consume( const path = await ocean.assets.consume(agreementId, ddo.id, accessService.index, consumer, folder)
agreementId,
ddo.id,
accessService.index,
consumer,
folder
)
assert.include(path, folder, 'The storage path is not correct.') assert.include(path, folder, 'The storage path is not correct.')

View File

@ -4,11 +4,7 @@ import { config } from '../config'
import { Ocean, templates, conditions, utils, Account, Keeper } from '../../src' // @oceanprotocol/squid import { Ocean, templates, conditions, utils, Account, Keeper } from '../../src' // @oceanprotocol/squid
const { const { LockRewardCondition, EscrowReward, AccessSecretStoreCondition } = conditions
LockRewardCondition,
EscrowReward,
AccessSecretStoreCondition
} = conditions
describe('Register Escrow Access Secret Store Template', () => { describe('Register Escrow Access Secret Store Template', () => {
let ocean: Ocean let ocean: Ocean
@ -40,8 +36,7 @@ describe('Register Escrow Access Secret Store Template', () => {
consumer = (await ocean.accounts.list())[2] consumer = (await ocean.accounts.list())[2]
// Conditions // Conditions
accessSecretStoreCondition = accessSecretStoreCondition = keeper.conditions.accessSecretStoreCondition
keeper.conditions.accessSecretStoreCondition
lockRewardCondition = keeper.conditions.lockRewardCondition lockRewardCondition = keeper.conditions.lockRewardCondition
escrowReward = keeper.conditions.escrowReward escrowReward = keeper.conditions.escrowReward
@ -52,21 +47,13 @@ describe('Register Escrow Access Secret Store Template', () => {
describe('Propose and approve template', () => { describe('Propose and approve template', () => {
it('should propose the template', async () => { it('should propose the template', async () => {
await keeper.templateStoreManager.proposeTemplate( await keeper.templateStoreManager.proposeTemplate(template.getAddress(), consumer.getId(), true)
template.getAddress(),
consumer.getId(),
true
)
// TODO: Use a event to detect template mined // TODO: Use a event to detect template mined
await new Promise(resolve => setTimeout(resolve, 2 * 1000)) await new Promise(resolve => setTimeout(resolve, 2 * 1000))
}) })
it('should approve the template', async () => { it('should approve the template', async () => {
await keeper.templateStoreManager.approveTemplate( await keeper.templateStoreManager.approveTemplate(template.getAddress(), templateManagerOwner.getId(), true)
template.getAddress(),
templateManagerOwner.getId(),
true
)
// TODO: Use a event to detect template mined // TODO: Use a event to detect template mined
await new Promise(resolve => setTimeout(resolve, 2 * 1000)) await new Promise(resolve => setTimeout(resolve, 2 * 1000))
}) })
@ -81,21 +68,11 @@ describe('Register Escrow Access Secret Store Template', () => {
let conditionIdEscrow: string let conditionIdEscrow: string
it('should register a DID', async () => { it('should register a DID', async () => {
await keeper.didRegistry.registerAttribute( await keeper.didRegistry.registerAttribute(did, checksum, [], url, publisher.getId())
did,
checksum,
[],
url,
publisher.getId()
)
}) })
it('should generate the condition IDs', async () => { it('should generate the condition IDs', async () => {
conditionIdAccess = await accessSecretStoreCondition.generateIdHash( conditionIdAccess = await accessSecretStoreCondition.generateIdHash(agreementId, did, consumer.getId())
agreementId,
did,
consumer.getId()
)
conditionIdLock = await lockRewardCondition.generateIdHash( conditionIdLock = await lockRewardCondition.generateIdHash(
agreementId, agreementId,
await escrowReward.getAddress(), await escrowReward.getAddress(),
@ -131,20 +108,10 @@ describe('Register Escrow Access Secret Store Template', () => {
assert.equal(conditionInstances.length, 3, 'Expected 3 conditions.') assert.equal(conditionInstances.length, 3, 'Expected 3 conditions.')
const conditionClasses = [ const conditionClasses = [AccessSecretStoreCondition, EscrowReward, LockRewardCondition]
AccessSecretStoreCondition,
EscrowReward,
LockRewardCondition
]
conditionClasses.forEach(conditionClass => { conditionClasses.forEach(conditionClass => {
if ( if (!conditionInstances.find(condition => condition instanceof conditionClass)) {
!conditionInstances.find( throw new Error(`${conditionClass.name} is not part of the conditions.`)
condition => condition instanceof conditionClass
)
) {
throw new Error(
`${conditionClass.name} is not part of the conditions.`
)
} }
}) })
}) })
@ -164,10 +131,7 @@ describe('Register Escrow Access Secret Store Template', () => {
}) })
it('should not grant the access to the consumer', async () => { it('should not grant the access to the consumer', async () => {
const accessGranted = await accessSecretStoreCondition.checkPermissions( const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
consumer.getId(),
did
)
assert.isFalse(accessGranted, 'Consumer has been granted.') assert.isFalse(accessGranted, 'Consumer has been granted.')
}) })
@ -177,11 +141,7 @@ describe('Register Escrow Access Secret Store Template', () => {
await consumer.requestTokens(escrowAmount) await consumer.requestTokens(escrowAmount)
} catch {} } catch {}
await keeper.token.approve( await keeper.token.approve(lockRewardCondition.getAddress(), escrowAmount, consumer.getId())
lockRewardCondition.getAddress(),
escrowAmount,
consumer.getId()
)
const fulfill = await lockRewardCondition.fulfill( const fulfill = await lockRewardCondition.fulfill(
agreementId, agreementId,
@ -219,10 +179,7 @@ describe('Register Escrow Access Secret Store Template', () => {
}) })
it('should grant the access to the consumer', async () => { it('should grant the access to the consumer', async () => {
const accessGranted = await accessSecretStoreCondition.checkPermissions( const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
consumer.getId(),
did
)
assert.isTrue(accessGranted, 'Consumer has not been granted.') assert.isTrue(accessGranted, 'Consumer has not been granted.')
}) })
@ -235,31 +192,17 @@ describe('Register Escrow Access Secret Store Template', () => {
it('should register a DID', async () => { it('should register a DID', async () => {
// This part is executed inside Ocean.assets.create() // This part is executed inside Ocean.assets.create()
await keeper.didRegistry.registerAttribute( await keeper.didRegistry.registerAttribute(did, checksum, [], url, publisher.getId())
did,
checksum,
[],
url,
publisher.getId()
)
}) })
it('should create a new agreement (short way)', async () => { it('should create a new agreement (short way)', async () => {
agreementId = await template.createFullAgreement( agreementId = await template.createFullAgreement(did, escrowAmount, consumer.getId(), publisher.getId())
did,
escrowAmount,
consumer.getId(),
publisher.getId()
)
assert.match(agreementId, /^0x[a-f0-9]{64}$/i) assert.match(agreementId, /^0x[a-f0-9]{64}$/i)
}) })
it('should not grant the access to the consumer', async () => { it('should not grant the access to the consumer', async () => {
const accessGranted = await accessSecretStoreCondition.checkPermissions( const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
consumer.getId(),
did
)
assert.isFalse(accessGranted, 'Consumer has been granted.') assert.isFalse(accessGranted, 'Consumer has been granted.')
}) })
@ -269,20 +212,11 @@ describe('Register Escrow Access Secret Store Template', () => {
await consumer.requestTokens(escrowAmount) await consumer.requestTokens(escrowAmount)
} catch {} } catch {}
await ocean.agreements.conditions.lockReward( await ocean.agreements.conditions.lockReward(agreementId, escrowAmount, consumer)
agreementId,
escrowAmount,
consumer
)
}) })
it('should fulfill the conditions from publisher side', async () => { it('should fulfill the conditions from publisher side', async () => {
await ocean.agreements.conditions.grantAccess( await ocean.agreements.conditions.grantAccess(agreementId, did, consumer.getId(), publisher)
agreementId,
did,
consumer.getId(),
publisher
)
await ocean.agreements.conditions.releaseReward( await ocean.agreements.conditions.releaseReward(
agreementId, agreementId,
escrowAmount, escrowAmount,
@ -294,10 +228,7 @@ describe('Register Escrow Access Secret Store Template', () => {
}) })
it('should grant the access to the consumer', async () => { it('should grant the access to the consumer', async () => {
const accessGranted = await accessSecretStoreCondition.checkPermissions( const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
consumer.getId(),
did
)
assert.isTrue(accessGranted, 'Consumer has not been granted.') assert.isTrue(accessGranted, 'Consumer has not been granted.')
}) })

View File

@ -4,11 +4,7 @@ import { config } from '../config'
import { Ocean, templates, conditions, utils, Account, Keeper } from '../../src' // @oceanprotocol/squid import { Ocean, templates, conditions, utils, Account, Keeper } from '../../src' // @oceanprotocol/squid
const { const { LockRewardCondition, EscrowReward, ComputeExecutionCondition } = conditions
LockRewardCondition,
EscrowReward,
ComputeExecutionCondition
} = conditions
describe('Register Escrow Compute Execution Template', () => { describe('Register Escrow Compute Execution Template', () => {
let ocean: Ocean let ocean: Ocean
@ -51,21 +47,13 @@ describe('Register Escrow Compute Execution Template', () => {
describe('Propose and approve template', () => { describe('Propose and approve template', () => {
it('should propose the template', async () => { it('should propose the template', async () => {
await keeper.templateStoreManager.proposeTemplate( await keeper.templateStoreManager.proposeTemplate(template.getAddress(), consumer.getId(), true)
template.getAddress(),
consumer.getId(),
true
)
// TODO: Use a event to detect template mined // TODO: Use a event to detect template mined
await new Promise(resolve => setTimeout(resolve, 2 * 1000)) await new Promise(resolve => setTimeout(resolve, 2 * 1000))
}) })
it('should approve the template', async () => { it('should approve the template', async () => {
await keeper.templateStoreManager.approveTemplate( await keeper.templateStoreManager.approveTemplate(template.getAddress(), templateManagerOwner.getId(), true)
template.getAddress(),
templateManagerOwner.getId(),
true
)
// TODO: Use a event to detect template mined // TODO: Use a event to detect template mined
await new Promise(resolve => setTimeout(resolve, 2 * 1000)) await new Promise(resolve => setTimeout(resolve, 2 * 1000))
}) })
@ -80,21 +68,11 @@ describe('Register Escrow Compute Execution Template', () => {
let conditionIdEscrow: string let conditionIdEscrow: string
it('should register a DID', async () => { it('should register a DID', async () => {
await keeper.didRegistry.registerAttribute( await keeper.didRegistry.registerAttribute(did, checksum, [], url, publisher.getId())
did,
checksum,
[],
url,
publisher.getId()
)
}) })
it('should generate the condition IDs', async () => { it('should generate the condition IDs', async () => {
conditionIdCompute = await computeExecutionCondition.generateIdHash( conditionIdCompute = await computeExecutionCondition.generateIdHash(agreementId, did, consumer.getId())
agreementId,
did,
consumer.getId()
)
conditionIdLock = await lockRewardCondition.generateIdHash( conditionIdLock = await lockRewardCondition.generateIdHash(
agreementId, agreementId,
await escrowReward.getAddress(), await escrowReward.getAddress(),
@ -130,20 +108,10 @@ describe('Register Escrow Compute Execution Template', () => {
assert.equal(conditionInstances.length, 3, 'Expected 3 conditions.') assert.equal(conditionInstances.length, 3, 'Expected 3 conditions.')
const conditionClasses = [ const conditionClasses = [ComputeExecutionCondition, EscrowReward, LockRewardCondition]
ComputeExecutionCondition,
EscrowReward,
LockRewardCondition
]
conditionClasses.forEach(conditionClass => { conditionClasses.forEach(conditionClass => {
if ( if (!conditionInstances.find(condition => condition instanceof conditionClass)) {
!conditionInstances.find( throw new Error(`${conditionClass.name} is not part of the conditions.`)
condition => condition instanceof conditionClass
)
) {
throw new Error(
`${conditionClass.name} is not part of the conditions.`
)
} }
}) })
}) })
@ -163,10 +131,7 @@ describe('Register Escrow Compute Execution Template', () => {
}) })
it('should not trigger the compute', async () => { it('should not trigger the compute', async () => {
const computeTriggered = await computeExecutionCondition.wasComputeTriggered( const computeTriggered = await computeExecutionCondition.wasComputeTriggered(did, consumer.getId())
did,
consumer.getId()
)
assert.isFalse(computeTriggered, 'Compute has been triggered.') assert.isFalse(computeTriggered, 'Compute has been triggered.')
}) })
@ -176,11 +141,7 @@ describe('Register Escrow Compute Execution Template', () => {
await consumer.requestTokens(escrowAmount) await consumer.requestTokens(escrowAmount)
} catch {} } catch {}
await keeper.token.approve( await keeper.token.approve(lockRewardCondition.getAddress(), escrowAmount, consumer.getId())
lockRewardCondition.getAddress(),
escrowAmount,
consumer.getId()
)
const fulfill = await lockRewardCondition.fulfill( const fulfill = await lockRewardCondition.fulfill(
agreementId, agreementId,
@ -218,10 +179,7 @@ describe('Register Escrow Compute Execution Template', () => {
}) })
it('should grant the access to the consumer', async () => { it('should grant the access to the consumer', async () => {
const computeTriggered = await computeExecutionCondition.wasComputeTriggered( const computeTriggered = await computeExecutionCondition.wasComputeTriggered(did, consumer.getId())
did,
consumer.getId()
)
assert.isTrue(computeTriggered, 'Compute has not been triggered.') assert.isTrue(computeTriggered, 'Compute has not been triggered.')
}) })
@ -234,31 +192,17 @@ describe('Register Escrow Compute Execution Template', () => {
it('should register a DID', async () => { it('should register a DID', async () => {
// This part is executed inside Ocean.assets.create() // This part is executed inside Ocean.assets.create()
await keeper.didRegistry.registerAttribute( await keeper.didRegistry.registerAttribute(did, checksum, [], url, publisher.getId())
did,
checksum,
[],
url,
publisher.getId()
)
}) })
it('should create a new agreement (short way)', async () => { it('should create a new agreement (short way)', async () => {
agreementId = await template.createFullAgreement( agreementId = await template.createFullAgreement(did, escrowAmount, consumer.getId(), publisher.getId())
did,
escrowAmount,
consumer.getId(),
publisher.getId()
)
assert.match(agreementId, /^0x[a-f0-9]{64}$/i) assert.match(agreementId, /^0x[a-f0-9]{64}$/i)
}) })
it('should not grant the access to the consumer', async () => { it('should not grant the access to the consumer', async () => {
const computeTriggered = await computeExecutionCondition.wasComputeTriggered( const computeTriggered = await computeExecutionCondition.wasComputeTriggered(did, consumer.getId())
did,
consumer.getId()
)
assert.isFalse(computeTriggered, 'Compute has been triggered.') assert.isFalse(computeTriggered, 'Compute has been triggered.')
}) })
@ -268,20 +212,11 @@ describe('Register Escrow Compute Execution Template', () => {
await consumer.requestTokens(escrowAmount) await consumer.requestTokens(escrowAmount)
} catch {} } catch {}
await ocean.agreements.conditions.lockReward( await ocean.agreements.conditions.lockReward(agreementId, escrowAmount, consumer)
agreementId,
escrowAmount,
consumer
)
}) })
it('should fulfill the conditions from computing side', async () => { it('should fulfill the conditions from computing side', async () => {
await ocean.agreements.conditions.grantServiceExecution( await ocean.agreements.conditions.grantServiceExecution(agreementId, did, consumer.getId(), publisher)
agreementId,
did,
consumer.getId(),
publisher
)
await ocean.agreements.conditions.releaseReward( await ocean.agreements.conditions.releaseReward(
agreementId, agreementId,
escrowAmount, escrowAmount,
@ -293,10 +228,7 @@ describe('Register Escrow Compute Execution Template', () => {
}) })
it('should grant the access to the consumer', async () => { it('should grant the access to the consumer', async () => {
const computeTriggered = await computeExecutionCondition.wasComputeTriggered( const computeTriggered = await computeExecutionCondition.wasComputeTriggered(did, consumer.getId())
did,
consumer.getId()
)
assert.isTrue(computeTriggered, 'Compute has not been triggered.') assert.isTrue(computeTriggered, 'Compute has not been triggered.')
}) })

View File

@ -15,8 +15,7 @@ describe('Search Asset', () => {
.toString(36) .toString(36)
.substr(2) .substr(2)
let price let price
const metadataGenerator = (name: string) => const metadataGenerator = (name: string) => generateMetadata(`${name}${testHash}`, price)
generateMetadata(`${name}${testHash}`, price)
let test1length let test1length
let test2length let test2length
@ -35,10 +34,8 @@ describe('Search Asset', () => {
assert.isArray(ddos, 'A search should return an array') assert.isArray(ddos, 'A search should return an array')
test1length = ddos.length test1length = ddos.length
test2length = (await ocean.assets.search(`Test2${testHash}`)).results test2length = (await ocean.assets.search(`Test2${testHash}`)).results.length
.length test3length = (await ocean.assets.search(`Test3${testHash}`)).results.length
test3length = (await ocean.assets.search(`Test3${testHash}`)).results
.length
if (!ocean.keeper.dispenser) { if (!ocean.keeper.dispenser) {
price = 0 price = 0
@ -46,46 +43,20 @@ describe('Search Asset', () => {
}) })
it('should register an asset', async () => { it('should register an asset', async () => {
assert.instanceOf( assert.instanceOf(await ocean.assets.create(metadataGenerator('Test1') as any, publisher), DDO)
await ocean.assets.create( assert.instanceOf(await ocean.assets.create(metadataGenerator('Test2') as any, publisher), DDO)
metadataGenerator('Test1') as any, assert.instanceOf(await ocean.assets.create(metadataGenerator('Test2') as any, publisher), DDO)
publisher assert.instanceOf(await ocean.assets.create(metadataGenerator('Test3') as any, publisher), DDO)
),
DDO
)
assert.instanceOf(
await ocean.assets.create(
metadataGenerator('Test2') as any,
publisher
),
DDO
)
assert.instanceOf(
await ocean.assets.create(
metadataGenerator('Test2') as any,
publisher
),
DDO
)
assert.instanceOf(
await ocean.assets.create(
metadataGenerator('Test3') as any,
publisher
),
DDO
)
}) })
it('should search by text and see the increment of DDOs', async () => { it('should search by text and see the increment of DDOs', async () => {
assert.equal( assert.equal(
(await ocean.assets.search(`Test2${testHash}`)).results.length - (await ocean.assets.search(`Test2${testHash}`)).results.length - test2length,
test2length,
2, 2,
'Something was wrong searching the assets' 'Something was wrong searching the assets'
) )
assert.equal( assert.equal(
(await ocean.assets.search(`Test3${testHash}`)).results.length - (await ocean.assets.search(`Test3${testHash}`)).results.length - test3length,
test3length,
1, 1,
'Something was wrong searching the assets' 'Something was wrong searching the assets'
) )
@ -94,14 +65,8 @@ describe('Search Asset', () => {
it('should return a list of DDOs', async () => { it('should return a list of DDOs', async () => {
const { results: ddos } = await ocean.assets.search(`Test1${testHash}`) const { results: ddos } = await ocean.assets.search(`Test1${testHash}`)
assert.equal( assert.equal(ddos.length - test1length, 1, 'Something was wrong searching the assets')
ddos.length - test1length, ddos.map(ddo => assert.instanceOf(ddo, DDO, 'The DDO is not an instance of a DDO'))
1,
'Something was wrong searching the assets'
)
ddos.map(ddo =>
assert.instanceOf(ddo, DDO, 'The DDO is not an instance of a DDO')
)
}) })
it('should be able to do a query to get a list of DDOs', async () => { it('should be able to do a query to get a list of DDOs', async () => {
@ -117,8 +82,6 @@ describe('Search Asset', () => {
}) })
assert.equal(ddos.length, 1, 'Something was wrong searching the assets') assert.equal(ddos.length, 1, 'Something was wrong searching the assets')
ddos.map(ddo => ddos.map(ddo => assert.instanceOf(ddo, DDO, 'The DDO is not an instance of a DDO'))
assert.instanceOf(ddo, DDO, 'The DDO is not an instance of a DDO')
)
}) })
}) })

View File

@ -21,11 +21,7 @@ describe('Secret Store', () => {
}) })
it('should encrypt a text', async () => { it('should encrypt a text', async () => {
encryptedContent = await ocean.secretStore.encrypt( encryptedContent = await ocean.secretStore.encrypt(did.getId(), content, account)
did.getId(),
content,
account
)
assert.isDefined(encryptedContent) assert.isDefined(encryptedContent)
assert.match(encryptedContent, /^0x[a-f0-9]{76}$/i) assert.match(encryptedContent, /^0x[a-f0-9]{76}$/i)

View File

@ -76,11 +76,7 @@ describe('Signature', () => {
ddo, ddo,
0, 0,
agreementId, agreementId,
[ [`0x${'1'.repeat(64)}`, `0x${'2'.repeat(64)}`, `0x${'3'.repeat(64)}`],
`0x${'1'.repeat(64)}`,
`0x${'2'.repeat(64)}`,
`0x${'3'.repeat(64)}`
],
consumer consumer
) )

View File

@ -13,23 +13,19 @@ const metadata: Partial<MetaData> = {
{ {
index: 0, index: 0,
contentType: 'application/json', contentType: 'application/json',
url: url: 'https://raw.githubusercontent.com/oceanprotocol/squid-js/master/package.json'
'https://raw.githubusercontent.com/oceanprotocol/squid-js/master/package.json'
}, },
{ {
index: 1, index: 1,
contentType: 'text/plain', contentType: 'text/plain',
url: url: 'https://raw.githubusercontent.com/oceanprotocol/squid-js/master/README.md'
'https://raw.githubusercontent.com/oceanprotocol/squid-js/master/README.md'
} }
] ]
}, },
additionalInformation: { additionalInformation: {
description: description: 'Weather information of UK including temperature and humidity',
'Weather information of UK including temperature and humidity',
copyrightHolder: 'Met Office', copyrightHolder: 'Met Office',
workExample: workExample: '423432fsd,51.509865,-0.118092,2011-01-01T10:55:11+00:00,7.2,68',
'423432fsd,51.509865,-0.118092,2011-01-01T10:55:11+00:00,7.2,68',
links: [ links: [
{ {
name: 'Sample of Asset Data', name: 'Sample of Asset Data',
@ -48,10 +44,7 @@ const metadata: Partial<MetaData> = {
} }
} }
export const generateMetadata = ( export const generateMetadata = (name: string, price?: number): Partial<MetaData> => ({
name: string,
price?: number
): Partial<MetaData> => ({
...metadata, ...metadata,
main: { main: {
...metadata.main, ...metadata.main,
@ -63,5 +56,4 @@ export const generateMetadata = (
} }
}) })
export const getMetadata = (price?: number) => export const getMetadata = (price?: number) => generateMetadata('TestAsset', price)
generateMetadata('TestAsset', price)

View File

@ -6,9 +6,7 @@ module.exports = class AddVendorsPlugin {
} }
apply(compiler) { apply(compiler) {
compiler.hooks.emit.tapAsync( compiler.hooks.emit.tapAsync(`AddVendorsPlugin ${this.base}`, (compilation, callback) => {
`AddVendorsPlugin ${this.base}`,
(compilation, callback) => {
const main = compilation.assets[`main.${this.base}`] const main = compilation.assets[`main.${this.base}`]
const mainMap = compilation.assets[`main.${this.base}.map`] const mainMap = compilation.assets[`main.${this.base}.map`]
const vendor = compilation.assets[`vendors.${this.base}`] const vendor = compilation.assets[`vendors.${this.base}`]
@ -25,7 +23,6 @@ module.exports = class AddVendorsPlugin {
compilation.assets[`${this.base}.map`] = mainMap compilation.assets[`${this.base}.map`] = mainMap
} }
callback() callback()
} })
)
} }
} }

View File

@ -15,10 +15,7 @@ const outPath = './dist/squid-js.json'
const files = ['./src/squid.ts'] const files = ['./src/squid.ts']
// specifically point to tsconfig, otherwise TypeDoc fails // specifically point to tsconfig, otherwise TypeDoc fails
const config = typescript.findConfigFile( const config = typescript.findConfigFile('./tsconfig.js', typescript.sys.fileExists)
'./tsconfig.js',
typescript.sys.fileExists
)
const generateJson = () => { const generateJson = () => {
const spinnerTypedoc = ora('Generating TypeDoc json...').start() const spinnerTypedoc = ora('Generating TypeDoc json...').start()

View File

@ -11,9 +11,7 @@ export interface InstantiableConfig {
logger?: Logger logger?: Logger
} }
export function generateIntantiableConfigFromConfig( export function generateIntantiableConfigFromConfig(config: Config): Partial<InstantiableConfig> {
config: Config
): Partial<InstantiableConfig> {
const logLevel = const logLevel =
typeof config.verbose !== 'number' typeof config.verbose !== 'number'
? config.verbose ? config.verbose
@ -68,9 +66,7 @@ export abstract class Instantiable {
public static async getInstance(...args: any[]): Promise<any> public static async getInstance(...args: any[]): Promise<any>
public static async getInstance(config: InstantiableConfig): Promise<any> { public static async getInstance(config: InstantiableConfig): Promise<any> {
LoggerInstance.warn( LoggerInstance.warn('getInstance() methods has needs to be added to child class.')
'getInstance() methods has needs to be added to child class.'
)
} }
protected static setInstanceConfig<T extends Instantiable>( protected static setInstanceConfig<T extends Instantiable>(

View File

@ -40,33 +40,20 @@ export class Aquarius extends Instantiable {
public async getAccessUrl(accessToken: any, payload: any): Promise<string> { public async getAccessUrl(accessToken: any, payload: any): Promise<string> {
const accessUrl: string = await this.ocean.utils.fetch const accessUrl: string = await this.ocean.utils.fetch
.post( .post(`${accessToken.service_endpoint}/${accessToken.resource_id}`, payload)
`${accessToken.service_endpoint}/${accessToken.resource_id}`,
payload
)
.then((response: any): string => { .then((response: any): string => {
if (response.ok) { if (response.ok) {
return response.text() return response.text()
} }
this.logger.error( this.logger.error('Failed: ', response.status, response.statusText)
'Failed: ',
response.status,
response.statusText
)
return null return null
}) })
.then((consumptionUrl: string): string => { .then((consumptionUrl: string): string => {
this.logger.error( this.logger.error('Success accessing consume endpoint: ', consumptionUrl)
'Success accessing consume endpoint: ',
consumptionUrl
)
return consumptionUrl return consumptionUrl
}) })
.catch(error => { .catch(error => {
this.logger.error( this.logger.error('Error fetching the data asset consumption url: ', error)
'Error fetching the data asset consumption url: ',
error
)
return null return null
}) })
@ -85,11 +72,7 @@ export class Aquarius extends Instantiable {
if (response.ok) { if (response.ok) {
return response.json() as DDO[] return response.json() as DDO[]
} }
this.logger.error( this.logger.error('queryMetadata failed:', response.status, response.statusText)
'queryMetadata failed:',
response.status,
response.statusText
)
return this.transformResult() return this.transformResult()
}) })
.then(results => { .then(results => {
@ -111,10 +94,7 @@ export class Aquarius extends Instantiable {
public async queryMetadataByText(query: SearchQuery): Promise<QueryResult> { public async queryMetadataByText(query: SearchQuery): Promise<QueryResult> {
const fullUrl = new URL(`${this.url}${apiPath}/query`) const fullUrl = new URL(`${this.url}${apiPath}/query`)
fullUrl.searchParams.append('text', query.text) fullUrl.searchParams.append('text', query.text)
fullUrl.searchParams.append( fullUrl.searchParams.append('sort', decodeURIComponent(JSON.stringify(query.sort)))
'sort',
decodeURIComponent(JSON.stringify(query.sort))
)
fullUrl.searchParams.append('offset', query.offset.toString()) fullUrl.searchParams.append('offset', query.offset.toString())
fullUrl.searchParams.append('page', query.page.toString()) fullUrl.searchParams.append('page', query.page.toString())
const result: QueryResult = await this.ocean.utils.fetch const result: QueryResult = await this.ocean.utils.fetch
@ -123,21 +103,14 @@ export class Aquarius extends Instantiable {
if (response.ok) { if (response.ok) {
return response.json() as DDO[] return response.json() as DDO[]
} }
this.logger.log( this.logger.log('queryMetadataByText failed:', response.status, response.statusText)
'queryMetadataByText failed:',
response.status,
response.statusText
)
return this.transformResult() return this.transformResult()
}) })
.then(results => { .then(results => {
return this.transformResult(results) return this.transformResult(results)
}) })
.catch(error => { .catch(error => {
this.logger.error( this.logger.error('Error fetching querying metadata by text: ', error)
'Error fetching querying metadata by text: ',
error
)
return this.transformResult() return this.transformResult()
}) })
@ -157,12 +130,7 @@ export class Aquarius extends Instantiable {
if (response.ok) { if (response.ok) {
return response.json() return response.json()
} }
this.logger.error( this.logger.error('storeDDO failed:', response.status, response.statusText, ddo)
'storeDDO failed:',
response.status,
response.statusText,
ddo
)
return null as DDO return null as DDO
}) })
.then((response: DDO) => { .then((response: DDO) => {
@ -181,25 +149,16 @@ export class Aquarius extends Instantiable {
* @param {DID | string} did DID of the asset. * @param {DID | string} did DID of the asset.
* @return {Promise<DDO>} DDO of the asset. * @return {Promise<DDO>} DDO of the asset.
*/ */
public async retrieveDDO( public async retrieveDDO(did: DID | string, metadataServiceEndpoint?: string): Promise<DDO> {
did: DID | string,
metadataServiceEndpoint?: string
): Promise<DDO> {
did = did && DID.parse(did) did = did && DID.parse(did)
const fullUrl = const fullUrl = metadataServiceEndpoint || `${this.url}${apiPath}/${did.getDid()}`
metadataServiceEndpoint || `${this.url}${apiPath}/${did.getDid()}`
const result = await this.ocean.utils.fetch const result = await this.ocean.utils.fetch
.get(fullUrl) .get(fullUrl)
.then((response: any) => { .then((response: any) => {
if (response.ok) { if (response.ok) {
return response.json() return response.json()
} }
this.logger.log( this.logger.log('retrieveDDO failed:', response.status, response.statusText, did)
'retrieveDDO failed:',
response.status,
response.statusText,
did
)
return null as DDO return null as DDO
}) })
.then((response: DDO) => { .then((response: DDO) => {
@ -222,12 +181,7 @@ export class Aquarius extends Instantiable {
} }
private transformResult( private transformResult(
{ { results, page, total_pages: totalPages, total_results: totalResults }: any = {
results,
page,
total_pages: totalPages,
total_results: totalResults
}: any = {
result: [], result: [],
page: 0, page: 0,
total_pages: 0, // eslint-disable-line @typescript-eslint/camelcase total_pages: 0, // eslint-disable-line @typescript-eslint/camelcase

View File

@ -35,12 +35,7 @@ export class Brizo extends Instantiable {
return `${this.url}${apiPath}/publish` return `${this.url}${apiPath}/publish`
} }
public getComputeEndpoint( public getComputeEndpoint(pubKey: string, serviceIndex: number, _notUsed: string, container: string) {
pubKey: string,
serviceIndex: number,
_notUsed: string,
container: string
) {
return `${this.url}${apiPath}/compute` return `${this.url}${apiPath}/compute`
} }
@ -60,10 +55,7 @@ export class Brizo extends Instantiable {
} }
try { try {
return await this.ocean.utils.fetch.post( return await this.ocean.utils.fetch.post(this.getPurchaseEndpoint(), decodeURI(JSON.stringify(args)))
this.getPurchaseEndpoint(),
decodeURI(JSON.stringify(args))
)
} catch (e) { } catch (e) {
this.logger.error(e) this.logger.error(e)
throw new Error('HTTP request failed') throw new Error('HTTP request failed')
@ -80,10 +72,7 @@ export class Brizo extends Instantiable {
): Promise<string> { ): Promise<string> {
const signature = const signature =
(await account.getToken()) || (await account.getToken()) ||
(await this.ocean.utils.signature.signText( (await this.ocean.utils.signature.signText(noZeroX(agreementId), account.getId()))
noZeroX(agreementId),
account.getId()
))
const filesPromises = files const filesPromises = files
.filter((_, i) => index === -1 || i === index) .filter((_, i) => index === -1 || i === index)
.map(async ({ index: i }) => { .map(async ({ index: i }) => {
@ -94,11 +83,7 @@ export class Brizo extends Instantiable {
consumeUrl += `&signature=${signature}` consumeUrl += `&signature=${signature}`
try { try {
await this.ocean.utils.fetch.downloadFile( await this.ocean.utils.fetch.downloadFile(consumeUrl, destination, i)
consumeUrl,
destination,
i
)
} catch (e) { } catch (e) {
this.logger.error('Error consuming assets') this.logger.error('Error consuming assets')
this.logger.error(e) this.logger.error(e)
@ -109,12 +94,7 @@ export class Brizo extends Instantiable {
return destination return destination
} }
public async encrypt( public async encrypt(did: string, signature: string, document: any, publisher: string): Promise<string> {
did: string,
signature: string,
document: any,
publisher: string
): Promise<string> {
const args = { const args = {
documentId: did, documentId: did,
signature, signature,

View File

@ -52,9 +52,7 @@ export class DDO {
public constructor(ddo: Partial<DDO> = {}) { public constructor(ddo: Partial<DDO> = {}) {
Object.assign(this, ddo, { Object.assign(this, ddo, {
created: created: (ddo && ddo.created) || new Date().toISOString().replace(/\.[0-9]{3}/, '')
(ddo && ddo.created) ||
new Date().toISOString().replace(/\.[0-9]{3}/, '')
}) })
} }
@ -82,9 +80,7 @@ export class DDO {
* @param {string} serviceType Service type. * @param {string} serviceType Service type.
* @return {Service} Service. * @return {Service} Service.
*/ */
public findServiceByType<T extends ServiceType>( public findServiceByType<T extends ServiceType>(serviceType: T): Service<T> {
serviceType: T
): Service<T> {
if (!serviceType) { if (!serviceType) {
throw new Error('serviceType not set') throw new Error('serviceType not set')
} }
@ -120,18 +116,10 @@ export class DDO {
* @param {string} password Password if it's required. * @param {string} password Password if it's required.
* @return {Promise<Proof>} Proof object. * @return {Promise<Proof>} Proof object.
*/ */
public async generateProof( public async generateProof(ocean: Ocean, publicKey: string, password?: string): Promise<Proof> {
ocean: Ocean,
publicKey: string,
password?: string
): Promise<Proof> {
const checksum = this.getChecksum() const checksum = this.getChecksum()
const signature = await ocean.utils.signature.signText( const signature = await ocean.utils.signature.signText(checksum, publicKey, password)
checksum,
publicKey,
password
)
return { return {
created: new Date().toISOString().replace(/\.[0-9]{3}/, ''), created: new Date().toISOString().replace(/\.[0-9]{3}/, ''),
@ -160,11 +148,7 @@ export class DDO {
* @param {string} password Password if it's requirted. * @param {string} password Password if it's requirted.
* @return {Promise<Proof>} Proof object. * @return {Promise<Proof>} Proof object.
*/ */
public async addProof( public async addProof(web3: Web3, publicKey: string, password?: string): Promise<void> {
web3: Web3,
publicKey: string,
password?: string
): Promise<void> {
if (this.proof) { if (this.proof) {
throw new Error('Proof already exists') throw new Error('Proof already exists')
} }

View File

@ -13,11 +13,7 @@ export interface PublicKey {
* Type of key. * Type of key.
* @type {string} * @type {string}
*/ */
type: type: 'Ed25519VerificationKey2018' | 'RsaVerificationKey2018' | 'EdDsaSAPublicKeySecp256k1' | 'EthereumECDSAKey'
| 'Ed25519VerificationKey2018'
| 'RsaVerificationKey2018'
| 'EdDsaSAPublicKeySecp256k1'
| 'EthereumECDSAKey'
/** /**
* Key owner. * Key owner.

View File

@ -2,13 +2,7 @@ import { MetaData } from './MetaData'
import { ServiceAgreementTemplate } from './ServiceAgreementTemplate' import { ServiceAgreementTemplate } from './ServiceAgreementTemplate'
import { Provider } from './ComputingProvider' import { Provider } from './ComputingProvider'
export type ServiceType = export type ServiceType = 'authorization' | 'metadata' | 'access' | 'compute' | 'computing' | 'fitchainCompute'
| 'authorization'
| 'metadata'
| 'access'
| 'compute'
| 'computing'
| 'fitchainCompute'
export interface ServiceCommon { export interface ServiceCommon {
type: ServiceType type: ServiceType
@ -47,9 +41,7 @@ export interface ServiceCompute extends ServiceCommon {
templateId?: string templateId?: string
} }
export type Service< export type Service<T extends ServiceType | 'default' = 'default'> = T extends 'authorization'
T extends ServiceType | 'default' = 'default'
> = T extends 'authorization'
? ServiceAuthorization ? ServiceAuthorization
: T extends 'metadata' : T extends 'metadata'
? ServiceMetadata ? ServiceMetadata

View File

@ -17,9 +17,7 @@ export class ContractEvent {
private filter: { [key: string]: any } private filter: { [key: string]: any }
) {} ) {}
public subscribe( public subscribe(callback: (events: any[]) => void): ContractEventSubscription {
callback: (events: any[]) => void
): ContractEventSubscription {
const onEvent = async (blockNumber: number) => { const onEvent = async (blockNumber: number) => {
const events = await this.contract.getEventData(this.eventName, { const events = await this.contract.getEventData(this.eventName, {
filter: this.filter, filter: this.filter,

View File

@ -6,25 +6,15 @@ export default class ContractHandler extends Instantiable {
return ContractHandler.contracts.get(this.getHash(what, networkId)) return ContractHandler.contracts.get(this.getHash(what, networkId))
} }
protected static setContract( protected static setContract(what: string, networkId: number, contractInstance: Contract) {
what: string, ContractHandler.contracts.set(this.getHash(what, networkId), contractInstance)
networkId: number,
contractInstance: Contract
) {
ContractHandler.contracts.set(
this.getHash(what, networkId),
contractInstance
)
} }
protected static hasContract(what: string, networkId: number): boolean { protected static hasContract(what: string, networkId: number): boolean {
return ContractHandler.contracts.has(this.getHash(what, networkId)) return ContractHandler.contracts.has(this.getHash(what, networkId))
} }
private static contracts: Map<string, Contract> = new Map< private static contracts: Map<string, Contract> = new Map<string, Contract>()
string,
Contract
>()
private static getHash(what: string, networkId: number): string { private static getHash(what: string, networkId: number): string {
return `${what}/#${networkId}` return `${what}/#${networkId}`
@ -35,17 +25,11 @@ export default class ContractHandler extends Instantiable {
this.setInstanceConfig(config) this.setInstanceConfig(config)
} }
public async get( public async get(what: string, optional: boolean = false): Promise<Contract> {
what: string,
optional: boolean = false
): Promise<Contract> {
const where = (await this.ocean.keeper.getNetworkName()).toLowerCase() const where = (await this.ocean.keeper.getNetworkName()).toLowerCase()
const networkId = await this.ocean.keeper.getNetworkId() const networkId = await this.ocean.keeper.getNetworkId()
try { try {
return ( return ContractHandler.getContract(what, networkId) || (await this.load(what, where, networkId))
ContractHandler.getContract(what, networkId) ||
(await this.load(what, where, networkId))
)
} catch (err) { } catch (err) {
if (!optional) { if (!optional) {
this.logger.error('Failed to load', what, 'from', where, err) this.logger.error('Failed to load', what, 'from', where, err)
@ -54,34 +38,18 @@ export default class ContractHandler extends Instantiable {
} }
} }
private async load( private async load(what: string, where: string, networkId: number): Promise<Contract> {
what: string,
where: string,
networkId: number
): Promise<Contract> {
this.logger.debug('Loading', what, 'from', where) this.logger.debug('Loading', what, 'from', where)
const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${what}.${where}.json`) const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${what}.${where}.json`)
// Logger.log('Loaded artifact', artifact) // Logger.log('Loaded artifact', artifact)
const code = await this.web3.eth.getCode(artifact.address) const code = await this.web3.eth.getCode(artifact.address)
if (code === '0x0') { if (code === '0x0') {
// no code in the blockchain dude // no code in the blockchain dude
throw new Error( throw new Error(`No code deployed at address ${artifact.address}, sorry.`)
`No code deployed at address ${artifact.address}, sorry.`
)
} }
const contract = new this.web3.eth.Contract( const contract = new this.web3.eth.Contract(artifact.abi, artifact.address)
artifact.abi,
artifact.address
)
this.logger.debug( this.logger.debug('Getting instance of', what, 'from', where, 'at address', artifact.address)
'Getting instance of',
what,
'from',
where,
'at address',
artifact.address
)
ContractHandler.setContract(what, networkId, contract) ContractHandler.setContract(what, networkId, contract)
return ContractHandler.getContract(what, networkId) return ContractHandler.getContract(what, networkId)
} }

View File

@ -41,11 +41,7 @@ export class EventHandler extends Instantiable {
} }
} }
public getEvent( public getEvent(contract: ContractBase, eventName: string, filter: { [key: string]: any }) {
contract: ContractBase,
eventName: string,
filter: { [key: string]: any }
) {
return new ContractEvent(this, contract, eventName, filter) return new ContractEvent(this, contract, eventName, filter)
} }
@ -65,9 +61,6 @@ export class EventHandler extends Instantiable {
this.events.forEach(fn => fn(this.lastBlock + 1)) this.events.forEach(fn => fn(this.lastBlock + 1))
this.lastBlock = blockNumber this.lastBlock = blockNumber
} }
this.lastTimeout = global.setTimeout( this.lastTimeout = global.setTimeout(() => this.checkBlock(true, n++), this.interval)
() => this.checkBlock(true, n++),
this.interval
)
} }
} }

View File

@ -15,11 +15,7 @@ import {
EscrowAccessSecretStoreTemplate, EscrowAccessSecretStoreTemplate,
EscrowComputeExecutionTemplate EscrowComputeExecutionTemplate
} from './contracts/templates' } from './contracts/templates'
import { import { TemplateStoreManager, AgreementStoreManager, ConditionStoreManager } from './contracts/managers'
TemplateStoreManager,
AgreementStoreManager,
ConditionStoreManager
} from './contracts/managers'
import { objectPromiseAll } from '../utils' import { objectPromiseAll } from '../utils'
import { EventHandler } from './EventHandler' import { EventHandler } from './EventHandler'
@ -38,9 +34,7 @@ export class Keeper extends Instantiable {
* Returns Keeper instance. * Returns Keeper instance.
* @return {Promise<Keeper>} * @return {Promise<Keeper>}
*/ */
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<Keeper> {
config: InstantiableConfig
): Promise<Keeper> {
const keeper = new Keeper() const keeper = new Keeper()
keeper.setInstanceConfig(config) keeper.setInstanceConfig(config)
@ -56,28 +50,16 @@ export class Keeper extends Instantiable {
didRegistry: DIDRegistry.getInstance(config), didRegistry: DIDRegistry.getInstance(config),
// Managers // Managers
templateStoreManager: TemplateStoreManager.getInstance(config), templateStoreManager: TemplateStoreManager.getInstance(config),
agreementStoreManager: AgreementStoreManager.getInstance( agreementStoreManager: AgreementStoreManager.getInstance(config),
config conditionStoreManager: ConditionStoreManager.getInstance(config),
),
conditionStoreManager: ConditionStoreManager.getInstance(
config
),
// Conditions // Conditions
lockRewardCondition: LockRewardCondition.getInstance(config), lockRewardCondition: LockRewardCondition.getInstance(config),
escrowReward: EscrowReward.getInstance(config), escrowReward: EscrowReward.getInstance(config),
accessSecretStoreCondition: AccessSecretStoreCondition.getInstance( accessSecretStoreCondition: AccessSecretStoreCondition.getInstance(config),
config computeExecutionCondition: ComputeExecutionCondition.getInstance(config),
),
computeExecutionCondition: ComputeExecutionCondition.getInstance(
config
),
// Templates // Templates
escrowAccessSecretStoreTemplate: EscrowAccessSecretStoreTemplate.getInstance( escrowAccessSecretStoreTemplate: EscrowAccessSecretStoreTemplate.getInstance(config),
config escrowComputeExecutionTemplate: EscrowComputeExecutionTemplate.getInstance(config)
),
escrowComputeExecutionTemplate: EscrowComputeExecutionTemplate.getInstance(
config
)
}) })
keeper.connected = true keeper.connected = true
@ -105,17 +87,13 @@ export class Keeper extends Instantiable {
keeper.conditions = { keeper.conditions = {
lockRewardCondition: keeper.instances.lockRewardCondition, lockRewardCondition: keeper.instances.lockRewardCondition,
escrowReward: keeper.instances.escrowReward, escrowReward: keeper.instances.escrowReward,
accessSecretStoreCondition: accessSecretStoreCondition: keeper.instances.accessSecretStoreCondition,
keeper.instances.accessSecretStoreCondition, computeExecutionCondition: keeper.instances.computeExecutionCondition
computeExecutionCondition:
keeper.instances.computeExecutionCondition
} }
// Conditions // Conditions
keeper.templates = { keeper.templates = {
escrowAccessSecretStoreTemplate: escrowAccessSecretStoreTemplate: keeper.instances.escrowAccessSecretStoreTemplate,
keeper.instances.escrowAccessSecretStoreTemplate, escrowComputeExecutionTemplate: keeper.instances.escrowComputeExecutionTemplate
escrowComputeExecutionTemplate:
keeper.instances.escrowComputeExecutionTemplate
} }
// Utils // Utils
keeper.utils = { keeper.utils = {
@ -200,9 +178,7 @@ export class Keeper extends Instantiable {
* @return {Condition} Condition instance. * @return {Condition} Condition instance.
*/ */
public getConditionByAddress(address: string): Condition { public getConditionByAddress(address: string): Condition {
return Object.values(this.conditions).find( return Object.values(this.conditions).find(condition => condition.getAddress() === address)
condition => condition.getAddress() === address
)
} }
/** /**
@ -211,9 +187,7 @@ export class Keeper extends Instantiable {
* @return {AgreementTemplate} Agreement template instance. * @return {AgreementTemplate} Agreement template instance.
*/ */
public getTemplateByName(name: string): AgreementTemplate { public getTemplateByName(name: string): AgreementTemplate {
return Object.values(this.templates).find( return Object.values(this.templates).find(template => template.contractName === name)
template => template.contractName === name
)
} }
/** /**
@ -222,9 +196,7 @@ export class Keeper extends Instantiable {
* @return {AgreementTemplate} Agreement template instance. * @return {AgreementTemplate} Agreement template instance.
*/ */
public getTemplateByAddress(address: string): AgreementTemplate { public getTemplateByAddress(address: string): AgreementTemplate {
return Object.values(this.templates).find( return Object.values(this.templates).find(template => template.getAddress() === address)
template => template.getAddress() === address
)
} }
/** /**

View File

@ -7,10 +7,6 @@ export default class Web3Provider {
* @return {Web3} * @return {Web3}
*/ */
public static getWeb3(config: Partial<Config> = {}): Web3 { public static getWeb3(config: Partial<Config> = {}): Web3 {
return new Web3( return new Web3(config.web3Provider || Web3.givenProvider || new Web3.providers.HttpProvider(config.nodeUri))
config.web3Provider ||
Web3.givenProvider ||
new Web3.providers.HttpProvider(config.nodeUri)
)
} }
} }

View File

@ -22,9 +22,7 @@ export abstract class ContractBase extends Instantiable {
public async getEventData(eventName: string, options: any) { public async getEventData(eventName: string, options: any) {
if (!this.contract.events[eventName]) { if (!this.contract.events[eventName]) {
throw new Error( throw new Error(`Event "${eventName}" not found on contract "${this.contractName}"`)
`Event "${eventName}" not found on contract "${this.contractName}"`
)
} }
return this.contract.getPastEvents(eventName, options) return this.contract.getPastEvents(eventName, options)
} }
@ -54,10 +52,7 @@ export abstract class ContractBase extends Instantiable {
protected async init(config: InstantiableConfig) { protected async init(config: InstantiableConfig) {
this.setInstanceConfig(config) this.setInstanceConfig(config)
const contractHandler = new ContractHandler(config) const contractHandler = new ContractHandler(config)
this.contract = await contractHandler.get( this.contract = await contractHandler.get(this.contractName, this.optional)
this.contractName,
this.optional
)
} }
protected async getFromAddress(from?: string): Promise<string> { protected async getFromAddress(from?: string): Promise<string> {
@ -67,24 +62,14 @@ export abstract class ContractBase extends Instantiable {
return from return from
} }
protected async sendFrom( protected async sendFrom(name: string, args: any[], from?: string): Promise<TransactionReceipt> {
name: string,
args: any[],
from?: string
): Promise<TransactionReceipt> {
from = await this.getFromAddress(from) from = await this.getFromAddress(from)
return this.send(name, from, args) return this.send(name, from, args)
} }
protected async send( protected async send(name: string, from: string, args: any[]): Promise<TransactionReceipt> {
name: string,
from: string,
args: any[]
): Promise<TransactionReceipt> {
if (!this.contract.methods[name]) { if (!this.contract.methods[name]) {
throw new Error( throw new Error(`Method "${name}" is not part of contract "${this.contractName}"`)
`Method "${name}" is not part of contract "${this.contractName}"`
)
} }
// Logger.log(name, args) // Logger.log(name, args)
const method = this.contract.methods[name] const method = this.contract.methods[name]
@ -99,62 +84,41 @@ export abstract class ContractBase extends Instantiable {
}) })
return tx return tx
} catch (err) { } catch (err) {
const mappedArgs = this.searchMethod(name, args).inputs.map( const mappedArgs = this.searchMethod(name, args).inputs.map((input, i) => {
(input, i) => {
return { return {
name: input.name, name: input.name,
value: args[i] value: args[i]
} }
} })
)
this.logger.error('-'.repeat(40)) this.logger.error('-'.repeat(40))
this.logger.error( this.logger.error(`Sending transaction "${name}" on contract "${this.contractName}" failed.`)
`Sending transaction "${name}" on contract "${this.contractName}" failed.`
)
this.logger.error(`Error: ${err.message}`) this.logger.error(`Error: ${err.message}`)
this.logger.error(`From: ${from}`) this.logger.error(`From: ${from}`)
this.logger.error( this.logger.error(`Parameters: ${JSON.stringify(mappedArgs, null, 2)}`)
`Parameters: ${JSON.stringify(mappedArgs, null, 2)}`
)
this.logger.error('-'.repeat(40)) this.logger.error('-'.repeat(40))
throw err throw err
} }
} }
protected async call<T extends any>( protected async call<T extends any>(name: string, args: any[], from?: string): Promise<T> {
name: string,
args: any[],
from?: string
): Promise<T> {
if (!this.contract.methods[name]) { if (!this.contract.methods[name]) {
throw new Error( throw new Error(`Method ${name} is not part of contract ${this.contractName}`)
`Method ${name} is not part of contract ${this.contractName}`
)
} }
// Logger.log(name) // Logger.log(name)
try { try {
const method = this.contract.methods[name](...args) const method = this.contract.methods[name](...args)
return method.call(from ? { from } : null) return method.call(from ? { from } : null)
} catch (err) { } catch (err) {
this.logger.error( this.logger.error(`Calling method "${name}" on contract "${this.contractName}" failed. Args: ${args}`, err)
`Calling method "${name}" on contract "${this.contractName}" failed. Args: ${args}`,
err
)
throw err throw err
} }
} }
protected getEvent(eventName: string, filter: { [key: string]: any }) { protected getEvent(eventName: string, filter: { [key: string]: any }) {
if (!this.contract.events[eventName]) { if (!this.contract.events[eventName]) {
throw new Error( throw new Error(`Event ${eventName} is not part of contract ${this.contractName}`)
`Event ${eventName} is not part of contract ${this.contractName}`
)
} }
return this.ocean.keeper.utils.eventHandler.getEvent( return this.ocean.keeper.utils.eventHandler.getEvent(this, eventName, filter)
this,
eventName,
filter
)
} }
private searchMethod(methodName: string, args: any[] = []) { private searchMethod(methodName: string, args: any[] = []) {
@ -164,13 +128,9 @@ export abstract class ContractBase extends Instantiable {
signature: (method as any).signature signature: (method as any).signature
})) }))
.filter((method: any) => method.name === methodName) .filter((method: any) => method.name === methodName)
const foundMethod = const foundMethod = methods.find(({ inputs }) => inputs.length === args.length) || methods[0]
methods.find(({ inputs }) => inputs.length === args.length) ||
methods[0]
if (!foundMethod) { if (!foundMethod) {
throw new Error( throw new Error(`Method "${methodName}" is not part of contract "${this.contractName}"`)
`Method "${methodName}" is not part of contract "${this.contractName}"`
)
} }
return foundMethod return foundMethod
} }

View File

@ -3,9 +3,7 @@ import { zeroX, didPrefixed, didZeroX } from '../../utils'
import { InstantiableConfig } from '../../Instantiable.abstract' import { InstantiableConfig } from '../../Instantiable.abstract'
export default class DIDRegistry extends ContractBase { export default class DIDRegistry extends ContractBase {
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<DIDRegistry> {
config: InstantiableConfig
): Promise<DIDRegistry> {
const didRegistry: DIDRegistry = new DIDRegistry('DIDRegistry') const didRegistry: DIDRegistry = new DIDRegistry('DIDRegistry')
await didRegistry.init(config) await didRegistry.init(config)
return didRegistry return didRegistry
@ -18,12 +16,7 @@ export default class DIDRegistry extends ContractBase {
value: string, value: string,
ownerAddress: string ownerAddress: string
) { ) {
return this.send('registerAttribute', ownerAddress, [ return this.send('registerAttribute', ownerAddress, [zeroX(did), zeroX(checksum), providers.map(zeroX), value])
zeroX(did),
zeroX(checksum),
providers.map(zeroX),
value
])
} }
public async getDIDOwner(did: string): Promise<string> { public async getDIDOwner(did: string): Promise<string> {
@ -46,46 +39,22 @@ export default class DIDRegistry extends ContractBase {
.map(didPrefixed) .map(didPrefixed)
} }
public async getAttributesByDid( public async getAttributesByDid(did: string): Promise<{ did: string; serviceEndpoint: string; checksum: string }> {
did: string
): Promise<{ did: string; serviceEndpoint: string; checksum: string }> {
return (await this.getPastEvents('DIDAttributeRegistered', { return (await this.getPastEvents('DIDAttributeRegistered', {
_did: didZeroX(did) _did: didZeroX(did)
})).map( })).map(({ returnValues: { _did, _checksum: checksum, _value: serviceEndpoint } }) => ({
({
returnValues: {
_did,
_checksum: checksum,
_value: serviceEndpoint
}
}) => ({
did: didPrefixed(_did), did: didPrefixed(_did),
serviceEndpoint, serviceEndpoint,
checksum checksum
}) }))[0]
)[0]
} }
public async grantPermission( public async grantPermission(did: string, grantee: string, ownerAddress: string) {
did: string, return this.send('grantPermission', ownerAddress, [zeroX(did), zeroX(grantee)])
grantee: string,
ownerAddress: string
) {
return this.send('grantPermission', ownerAddress, [
zeroX(did),
zeroX(grantee)
])
} }
public async revokePermission( public async revokePermission(did: string, grantee: string, ownerAddress: string) {
did: string, return this.send('revokePermission', ownerAddress, [zeroX(did), zeroX(grantee)])
grantee: string,
ownerAddress: string
) {
return this.send('revokePermission', ownerAddress, [
zeroX(did),
zeroX(grantee)
])
} }
public async getPermission(did: string, grantee: string): Promise<boolean> { public async getPermission(did: string, grantee: string): Promise<boolean> {

View File

@ -2,18 +2,13 @@ import ContractBase from './ContractBase'
import { InstantiableConfig } from '../../Instantiable.abstract' import { InstantiableConfig } from '../../Instantiable.abstract'
export default class Dispenser extends ContractBase { export default class Dispenser extends ContractBase {
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<Dispenser> {
config: InstantiableConfig
): Promise<Dispenser> {
const dispenser: Dispenser = new Dispenser('Dispenser', true) const dispenser: Dispenser = new Dispenser('Dispenser', true)
await dispenser.init(config) await dispenser.init(config)
return dispenser return dispenser
} }
public async requestTokens( public async requestTokens(amount: number | string, receiverAddress: string) {
amount: number | string,
receiverAddress: string
) {
return this.send('requestTokens', receiverAddress, [String(amount)]) return this.send('requestTokens', receiverAddress, [String(amount)])
} }
} }

View File

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

View File

@ -3,9 +3,7 @@ import ContractBase from './ContractBase'
import { InstantiableConfig } from '../../Instantiable.abstract' import { InstantiableConfig } from '../../Instantiable.abstract'
export default class OceanToken extends ContractBase { export default class OceanToken extends ContractBase {
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<OceanToken> {
config: InstantiableConfig
): Promise<OceanToken> {
const token: OceanToken = new OceanToken('OceanToken') const token: OceanToken = new OceanToken('OceanToken')
await token.init(config) await token.init(config)
return token return token
@ -20,9 +18,7 @@ export default class OceanToken extends ContractBase {
} }
public async balanceOf(address: string): Promise<number> { public async balanceOf(address: string): Promise<number> {
return this.call('balanceOf', [address]).then((balance: string) => return this.call('balanceOf', [address]).then((balance: string) => new BigNumber(balance).toNumber())
new BigNumber(balance).toNumber()
)
} }
public async transfer(to: string, amount: number, from: string) { public async transfer(to: string, amount: number, from: string) {

View File

@ -3,44 +3,23 @@ import { zeroX, didZeroX, didPrefixed } from '../../../utils'
import { InstantiableConfig } from '../../../Instantiable.abstract' import { InstantiableConfig } from '../../../Instantiable.abstract'
export class AccessSecretStoreCondition extends Condition { export class AccessSecretStoreCondition extends Condition {
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<AccessSecretStoreCondition> {
config: InstantiableConfig return Condition.getInstance(config, 'AccessSecretStoreCondition', AccessSecretStoreCondition)
): Promise<AccessSecretStoreCondition> {
return Condition.getInstance(
config,
'AccessSecretStoreCondition',
AccessSecretStoreCondition
)
} }
public hashValues(did: string, grantee: string) { public hashValues(did: string, grantee: string) {
return super.hashValues(didZeroX(did), zeroX(grantee)) return super.hashValues(didZeroX(did), zeroX(grantee))
} }
public fulfill( public fulfill(agreementId: string, did: string, grantee: string, from?: string) {
agreementId: string, return super.fulfill(agreementId, [didZeroX(did), grantee].map(zeroX), from)
did: string,
grantee: string,
from?: string
) {
return super.fulfill(
agreementId,
[didZeroX(did), grantee].map(zeroX),
from
)
} }
public checkPermissions(grantee: string, did: string, from?: string) { public checkPermissions(grantee: string, did: string, from?: string) {
return this.call<boolean>( return this.call<boolean>('checkPermissions', [grantee, didZeroX(did)].map(zeroX), from)
'checkPermissions',
[grantee, didZeroX(did)].map(zeroX),
from
)
} }
public async getGrantedDidByConsumer( public async getGrantedDidByConsumer(consumer: string): Promise<{ did: string; agreementId: string }[]> {
consumer: string
): Promise<{ did: string; agreementId: string }[]> {
return (await this.getPastEvents('Fulfilled', { return (await this.getPastEvents('Fulfilled', {
_grantee: zeroX(consumer) _grantee: zeroX(consumer)
})).map(({ returnValues }) => ({ })).map(({ returnValues }) => ({

View File

@ -3,42 +3,19 @@ import { zeroX, didZeroX, didPrefixed } from '../../../utils'
import { InstantiableConfig } from '../../../Instantiable.abstract' import { InstantiableConfig } from '../../../Instantiable.abstract'
export class ComputeExecutionCondition extends Condition { export class ComputeExecutionCondition extends Condition {
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<ComputeExecutionCondition> {
config: InstantiableConfig return Condition.getInstance(config, 'ComputeExecutionCondition', ComputeExecutionCondition)
): Promise<ComputeExecutionCondition> {
return Condition.getInstance(
config,
'ComputeExecutionCondition',
ComputeExecutionCondition
)
} }
public hashValues(did: string, computeConsumer: string) { public hashValues(did: string, computeConsumer: string) {
return super.hashValues(didZeroX(did), zeroX(computeConsumer)) return super.hashValues(didZeroX(did), zeroX(computeConsumer))
} }
public fulfill( public fulfill(agreementId: string, did: string, computeConsumer: string, from?: string) {
agreementId: string, return super.fulfill(agreementId, [didZeroX(did), computeConsumer].map(zeroX), from)
did: string,
computeConsumer: string,
from?: string
) {
return super.fulfill(
agreementId,
[didZeroX(did), computeConsumer].map(zeroX),
from
)
} }
public wasComputeTriggered( public wasComputeTriggered(did: string, computeConsumer: string, from?: string) {
did: string, return this.call<boolean>('wasComputeTriggered', [didZeroX(did), computeConsumer].map(zeroX), from)
computeConsumer: string,
from?: string
) {
return this.call<boolean>(
'wasComputeTriggered',
[didZeroX(did), computeConsumer].map(zeroX),
from
)
} }
} }

View File

@ -9,12 +9,7 @@ export enum ConditionState {
Aborted = 3 Aborted = 3
} }
export const conditionStateNames = [ export const conditionStateNames = ['Uninitialized', 'Unfulfilled', 'Fulfilled', 'Aborted']
'Uninitialized',
'Unfulfilled',
'Fulfilled',
'Aborted'
]
export abstract class Condition extends ContractBase { export abstract class Condition extends ContractBase {
public static async getInstance( public static async getInstance(

View File

@ -3,9 +3,7 @@ import { zeroX } from '../../../utils'
import { InstantiableConfig } from '../../../Instantiable.abstract' import { InstantiableConfig } from '../../../Instantiable.abstract'
export class EscrowReward extends Condition { export class EscrowReward extends Condition {
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<EscrowReward> {
config: InstantiableConfig
): Promise<EscrowReward> {
return Condition.getInstance(config, 'EscrowReward', EscrowReward) return Condition.getInstance(config, 'EscrowReward', EscrowReward)
} }
@ -16,10 +14,7 @@ export class EscrowReward extends Condition {
lockCondition: string, lockCondition: string,
releaseCondition: string releaseCondition: string
) { ) {
return super.hashValues( return super.hashValues(amount, ...[receiver, sender, lockCondition, releaseCondition].map(zeroX))
amount,
...[receiver, sender, lockCondition, releaseCondition].map(zeroX)
)
} }
public fulfill( public fulfill(
@ -33,12 +28,7 @@ export class EscrowReward extends Condition {
) { ) {
return super.fulfill( return super.fulfill(
agreementId, agreementId,
[ [amount, ...[receiver, sender, lockCondition, releaseCondition].map(zeroX)],
amount,
...[receiver, sender, lockCondition, releaseCondition].map(
zeroX
)
],
from from
) )
} }

View File

@ -3,30 +3,15 @@ import { zeroX } from '../../../utils'
import { InstantiableConfig } from '../../../Instantiable.abstract' import { InstantiableConfig } from '../../../Instantiable.abstract'
export class LockRewardCondition extends Condition { export class LockRewardCondition extends Condition {
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<LockRewardCondition> {
config: InstantiableConfig return Condition.getInstance(config, 'LockRewardCondition', LockRewardCondition)
): Promise<LockRewardCondition> {
return Condition.getInstance(
config,
'LockRewardCondition',
LockRewardCondition
)
} }
public hashValues(rewardAddress: string, amount: number | string) { public hashValues(rewardAddress: string, amount: number | string) {
return super.hashValues(zeroX(rewardAddress), String(amount)) return super.hashValues(zeroX(rewardAddress), String(amount))
} }
public fulfill( public fulfill(agreementId: string, rewardAddress: string, amount: number | string, from?: string) {
agreementId: string, return super.fulfill(agreementId, [zeroX(rewardAddress), String(amount)], from)
rewardAddress: string,
amount: number | string,
from?: string
) {
return super.fulfill(
agreementId,
[zeroX(rewardAddress), String(amount)],
from
)
} }
} }

View File

@ -12,12 +12,8 @@ export interface AgreementData {
} }
export class AgreementStoreManager extends ContractBase { export class AgreementStoreManager extends ContractBase {
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<AgreementStoreManager> {
config: InstantiableConfig const templateStoreManeger: AgreementStoreManager = new AgreementStoreManager('AgreementStoreManager')
): Promise<AgreementStoreManager> {
const templateStoreManeger: AgreementStoreManager = new AgreementStoreManager(
'AgreementStoreManager'
)
await templateStoreManeger.init(config) await templateStoreManeger.init(config)
return templateStoreManeger return templateStoreManeger
} }
@ -27,14 +23,10 @@ export class AgreementStoreManager extends ContractBase {
} }
public async getAgreement(agreementId: string) { public async getAgreement(agreementId: string) {
const { const { did, didOwner, templateId, conditionIds, lastUpdatedBy, blockNumberUpdated } = await this.call(
did, 'getAgreement',
didOwner, [zeroX(agreementId)]
templateId, )
conditionIds,
lastUpdatedBy,
blockNumberUpdated
} = await this.call('getAgreement', [zeroX(agreementId)])
return { return {
did, did,
didOwner, didOwner,

View File

@ -14,12 +14,8 @@ export interface ConditionData {
} }
export class ConditionStoreManager extends ContractBase { export class ConditionStoreManager extends ContractBase {
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<ConditionStoreManager> {
config: InstantiableConfig const templateStoreManeger: ConditionStoreManager = new ConditionStoreManager('ConditionStoreManager')
): Promise<ConditionStoreManager> {
const templateStoreManeger: ConditionStoreManager = new ConditionStoreManager(
'ConditionStoreManager'
)
await templateStoreManeger.init(config) await templateStoreManeger.init(config)
return templateStoreManeger return templateStoreManeger
} }
@ -29,15 +25,10 @@ export class ConditionStoreManager extends ContractBase {
} }
public async getCondition(conditionId: string) { public async getCondition(conditionId: string) {
const { const { typeRef, state, timeLock, timeOut, blockNumber, lastUpdatedBy, blockNumberUpdated } = await this.call(
typeRef, 'getCondition',
state, [zeroX(conditionId)]
timeLock, )
timeOut,
blockNumber,
lastUpdatedBy,
blockNumberUpdated
} = await this.call('getCondition', [zeroX(conditionId)])
return { return {
typeRef, typeRef,
state: +state, state: +state,

View File

@ -17,12 +17,8 @@ export interface TemplateMetadata {
} }
export class TemplateStoreManager extends ContractBase { export class TemplateStoreManager extends ContractBase {
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<TemplateStoreManager> {
config: InstantiableConfig const templateStoreManeger: TemplateStoreManager = new TemplateStoreManager('TemplateStoreManager')
): Promise<TemplateStoreManager> {
const templateStoreManeger: TemplateStoreManager = new TemplateStoreManager(
'TemplateStoreManager'
)
await templateStoreManeger.init(config) await templateStoreManeger.init(config)
return templateStoreManeger return templateStoreManeger
} }
@ -31,11 +27,7 @@ export class TemplateStoreManager extends ContractBase {
return this.call('owner', []) return this.call('owner', [])
} }
public async proposeTemplate( public async proposeTemplate(address: string, from?: string, ignoreExists?: boolean) {
address: string,
from?: string,
ignoreExists?: boolean
) {
const template = await this.getTemplate(address) const template = await this.getTemplate(address)
if (template.blockNumberUpdated !== 0) { if (template.blockNumberUpdated !== 0) {
this.logger.warn(`Template "${address}" already exist.`) this.logger.warn(`Template "${address}" already exist.`)
@ -47,16 +39,10 @@ export class TemplateStoreManager extends ContractBase {
} }
} }
public async approveTemplate( public async approveTemplate(address: string, from?: string, ignoreApproved?: boolean) {
address: string,
from?: string,
ignoreApproved?: boolean
) {
const template = await this.getTemplate(address) const template = await this.getTemplate(address)
if (template.state !== TemplateState.Proposed) { if (template.state !== TemplateState.Proposed) {
this.logger.warn( this.logger.warn(`Template "${address}" is not in "proposed" state.`)
`Template "${address}" is not in "proposed" state.`
)
if (!ignoreApproved) { if (!ignoreApproved) {
throw new Error(`Template not in "proposed" state.`) throw new Error(`Template not in "proposed" state.`)
} }
@ -70,12 +56,7 @@ export class TemplateStoreManager extends ContractBase {
} }
public async getTemplate(address: string) { public async getTemplate(address: string) {
const { const { state, owner, lastUpdatedBy, blockNumberUpdated } = await this.call('getTemplate', [zeroX(address)])
state,
owner,
lastUpdatedBy,
blockNumberUpdated
} = await this.call('getTemplate', [zeroX(address)])
return { return {
state: +state, state: +state,
owner, owner,

View File

@ -1,9 +1,5 @@
import ContractBase from '../ContractBase' import ContractBase from '../ContractBase'
import { import { Condition, ConditionState, conditionStateNames } from '../conditions/Condition.abstract'
Condition,
ConditionState,
conditionStateNames
} from '../conditions/Condition.abstract'
import { DDO } from '../../../ddo/DDO' import { DDO } from '../../../ddo/DDO'
import { ServiceAgreementTemplate } from '../../../ddo/ServiceAgreementTemplate' import { ServiceAgreementTemplate } from '../../../ddo/ServiceAgreementTemplate'
import { zeroX } from '../../../utils' import { zeroX } from '../../../utils'
@ -25,9 +21,7 @@ export abstract class AgreementTemplate extends ContractBase {
conditionName: string, conditionName: string,
templateClass: any templateClass: any
): Promise<AgreementTemplate & any> { ): Promise<AgreementTemplate & any> {
const condition: AgreementTemplate = new (templateClass as any)( const condition: AgreementTemplate = new (templateClass as any)(conditionName)
conditionName
)
await condition.init(config) await condition.init(config)
return condition return condition
} }
@ -56,14 +50,7 @@ export abstract class AgreementTemplate extends ContractBase {
) { ) {
return this.sendFrom( return this.sendFrom(
'createAgreement', 'createAgreement',
[ [zeroX(agreementId), zeroX(did), conditionIds.map(zeroX), timeLocks, timeOuts, ...extraArgs],
zeroX(agreementId),
zeroX(did),
conditionIds.map(zeroX),
timeLocks,
timeOuts,
...extraArgs
],
from from
) )
} }
@ -81,9 +68,7 @@ export abstract class AgreementTemplate extends ContractBase {
* @return {Promise<Condition[]>} Conditions contracts. * @return {Promise<Condition[]>} Conditions contracts.
*/ */
public async getConditions(): Promise<Condition[]> { public async getConditions(): Promise<Condition[]> {
return (await this.getConditionTypes()).map(address => return (await this.getConditionTypes()).map(address => this.ocean.keeper.getConditionByAddress(address))
this.ocean.keeper.getConditionByAddress(address)
)
} }
/** /**
@ -114,9 +99,7 @@ export abstract class AgreementTemplate extends ContractBase {
from?: string from?: string
): Promise<boolean> ): Promise<boolean>
public abstract async getServiceAgreementTemplate(): Promise< public abstract async getServiceAgreementTemplate(): Promise<ServiceAgreementTemplate>
ServiceAgreementTemplate
>
public async getServiceAgreementTemplateConditions() { public async getServiceAgreementTemplateConditions() {
const serviceAgreementTemplate = await this.getServiceAgreementTemplate() const serviceAgreementTemplate = await this.getServiceAgreementTemplate()
@ -127,9 +110,7 @@ export abstract class AgreementTemplate extends ContractBase {
const name = (await this.getServiceAgreementTemplateConditions()).find( const name = (await this.getServiceAgreementTemplateConditions()).find(
({ name: conditionRef }) => conditionRef === ref ({ name: conditionRef }) => conditionRef === ref
).contractName ).contractName
return (await this.getConditions()).find( return (await this.getConditions()).find(condition => condition.contractName === name)
condition => condition.contractName === name
)
} }
public async getServiceAgreementTemplateDependencies() { public async getServiceAgreementTemplateDependencies() {
@ -142,9 +123,7 @@ export abstract class AgreementTemplate extends ContractBase {
* @param {string} agreementId Agreement ID. * @param {string} agreementId Agreement ID.
* @return {Promise} Conditions status. * @return {Promise} Conditions status.
*/ */
public async getAgreementStatus( public async getAgreementStatus(agreementId: string): Promise<AgreementConditionsStatus | false> {
agreementId: string
): Promise<AgreementConditionsStatus | false> {
const agreementStore = this.ocean.keeper.agreementStoreManager const agreementStore = this.ocean.keeper.agreementStoreManager
const conditionStore = this.ocean.keeper.conditionStoreManager const conditionStore = this.ocean.keeper.conditionStoreManager
@ -165,15 +144,11 @@ export abstract class AgreementTemplate extends ContractBase {
) )
const statesPromises = Object.keys(dependencies).map(async (ref, i) => { const statesPromises = Object.keys(dependencies).map(async (ref, i) => {
const { const { contractName } = await this.getServiceAgreementTemplateConditionByRef(ref)
contractName
} = await this.getServiceAgreementTemplateConditionByRef(ref)
return { return {
ref, ref,
contractName, contractName,
state: (await conditionStore.getCondition( state: (await conditionStore.getCondition(conditionIdByConddition[contractName])).state
conditionIdByConddition[contractName]
)).state
} }
}) })
const states = await Promise.all(statesPromises) const states = await Promise.all(statesPromises)
@ -181,9 +156,7 @@ export abstract class AgreementTemplate extends ContractBase {
return states.reduce((acc, { contractName, ref, state }) => { return states.reduce((acc, { contractName, ref, state }) => {
const blockers = dependencies[ref] const blockers = dependencies[ref]
.map(dependency => states.find(_ => _.ref === dependency)) .map(dependency => states.find(_ => _.ref === dependency))
.filter( .filter(condition => condition.state !== ConditionState.Fulfilled)
condition => condition.state !== ConditionState.Fulfilled
)
return { return {
...acc, ...acc,
[ref]: { [ref]: {
@ -211,22 +184,16 @@ export abstract class AgreementTemplate extends ContractBase {
if (!status) { if (!status) {
this.logger.bypass('Agreement not created yet!') this.logger.bypass('Agreement not created yet!')
} }
Object.values(status || []).forEach( Object.values(status || []).forEach(({ condition, contractName, state, blocked, blockedBy }, i) => {
({ condition, contractName, state, blocked, blockedBy }, i) => {
if (i) { if (i) {
this.logger.bypass('-'.repeat(20)) this.logger.bypass('-'.repeat(20))
} }
this.logger.bypass(`${condition} (${contractName})`) this.logger.bypass(`${condition} (${contractName})`)
this.logger.bypass( this.logger.bypass(' Status:', state, `(${conditionStateNames[state]})`)
' Status:',
state,
`(${conditionStateNames[state]})`
)
if (blocked) { if (blocked) {
this.logger.bypass(' Blocked by:', blockedBy) this.logger.bypass(' Blocked by:', blockedBy)
} }
} })
)
this.logger.bypass('-'.repeat(80)) this.logger.bypass('-'.repeat(80))
} }

View File

@ -26,15 +26,7 @@ export abstract class BaseEscrowTemplate extends AgreementTemplate {
accessConsumer: string, accessConsumer: string,
from?: string from?: string
) { ) {
return super.createAgreement( return super.createAgreement(agreementId, did, conditionIds, timeLocks, timeOuts, [accessConsumer], from)
agreementId,
did,
conditionIds,
timeLocks,
timeOuts,
[accessConsumer],
from
)
} }
public async getAgreementData(agreementId: string) { public async getAgreementData(agreementId: string) {

View File

@ -13,11 +13,7 @@ export const escrowAccessSecretStoreTemplateServiceAgreementTemplate: ServiceAgr
} }
} }
], ],
fulfillmentOrder: [ fulfillmentOrder: ['lockReward.fulfill', 'accessSecretStore.fulfill', 'escrowReward.fulfill'],
'lockReward.fulfill',
'accessSecretStore.fulfill',
'escrowReward.fulfill'
],
conditionDependency: { conditionDependency: {
lockReward: [], lockReward: [],
accessSecretStore: [], accessSecretStore: [],

View File

@ -7,26 +7,15 @@ import { InstantiableConfig } from '../../../Instantiable.abstract'
import { escrowAccessSecretStoreTemplateServiceAgreementTemplate } from './EscrowAccessSecretStoreTemplate.serviceAgreementTemplate' import { escrowAccessSecretStoreTemplateServiceAgreementTemplate } from './EscrowAccessSecretStoreTemplate.serviceAgreementTemplate'
export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate { export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate {
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<EscrowAccessSecretStoreTemplate> {
config: InstantiableConfig return AgreementTemplate.getInstance(config, 'EscrowAccessSecretStoreTemplate', EscrowAccessSecretStoreTemplate)
): Promise<EscrowAccessSecretStoreTemplate> {
return AgreementTemplate.getInstance(
config,
'EscrowAccessSecretStoreTemplate',
EscrowAccessSecretStoreTemplate
)
} }
public async getServiceAgreementTemplate() { public async getServiceAgreementTemplate() {
return escrowAccessSecretStoreTemplateServiceAgreementTemplate return escrowAccessSecretStoreTemplateServiceAgreementTemplate
} }
public async createAgreementFromDDO( public async createAgreementFromDDO(agreementId: string, ddo: DDO, consumer: string, from?: string) {
agreementId: string,
ddo: DDO,
consumer: string,
from?: string
) {
return !!(await this.createFullAgreement( return !!(await this.createFullAgreement(
ddo.shortId(), ddo.shortId(),
ddo.findServiceByType('metadata').attributes.main.price, ddo.findServiceByType('metadata').attributes.main.price,
@ -36,12 +25,7 @@ export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate {
)) ))
} }
public async getAgreementIdsFromDDO( public async getAgreementIdsFromDDO(agreementId: string, ddo: DDO, consumer: string, from?: string) {
agreementId: string,
ddo: DDO,
consumer: string,
from?: string
) {
const { const {
accessSecretStoreConditionId, accessSecretStoreConditionId,
lockRewardConditionId, lockRewardConditionId,
@ -52,11 +36,7 @@ export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate {
ddo.findServiceByType('metadata').attributes.main.price, ddo.findServiceByType('metadata').attributes.main.price,
consumer consumer
) )
return [ return [accessSecretStoreConditionId, lockRewardConditionId, escrowRewardId]
accessSecretStoreConditionId,
lockRewardConditionId,
escrowRewardId
]
} }
/** /**
@ -77,21 +57,12 @@ export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate {
accessSecretStoreConditionId, accessSecretStoreConditionId,
lockRewardConditionId, lockRewardConditionId,
escrowRewardId escrowRewardId
} = await this.createFullAgreementData( } = await this.createFullAgreementData(agreementId, did, amount, consumer)
agreementId,
did,
amount,
consumer
)
await this.createAgreement( await this.createAgreement(
agreementId, agreementId,
did, did,
[ [accessSecretStoreConditionId, lockRewardConditionId, escrowRewardId],
accessSecretStoreConditionId,
lockRewardConditionId,
escrowRewardId
],
[0, 0, 0], [0, 0, 0],
[0, 0, 0], [0, 0, 0],
consumer, consumer,
@ -101,19 +72,10 @@ export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate {
return zeroX(agreementId) return zeroX(agreementId)
} }
private async createFullAgreementData( private async createFullAgreementData(agreementId: string, did: string, amount: number | string, consumer: string) {
agreementId: string,
did: string,
amount: number | string,
consumer: string
) {
const { didRegistry, conditions } = this.ocean.keeper const { didRegistry, conditions } = this.ocean.keeper
const { const { accessSecretStoreCondition, lockRewardCondition, escrowReward } = conditions
accessSecretStoreCondition,
lockRewardCondition,
escrowReward
} = conditions
const publisher = await didRegistry.getDIDOwner(did) const publisher = await didRegistry.getDIDOwner(did)
@ -122,11 +84,7 @@ export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate {
await escrowReward.getAddress(), await escrowReward.getAddress(),
amount amount
) )
const accessSecretStoreConditionId = await accessSecretStoreCondition.generateIdHash( const accessSecretStoreConditionId = await accessSecretStoreCondition.generateIdHash(agreementId, did, consumer)
agreementId,
did,
consumer
)
const escrowRewardId = await escrowReward.generateIdHash( const escrowRewardId = await escrowReward.generateIdHash(
agreementId, agreementId,
String(amount), String(amount),

View File

@ -13,11 +13,7 @@ export const escrowComputeExecutionTemplateServiceAgreementTemplate: ServiceAgre
} }
} }
], ],
fulfillmentOrder: [ fulfillmentOrder: ['lockReward.fulfill', 'serviceExecution.fulfill', 'escrowReward.fulfill'],
'lockReward.fulfill',
'serviceExecution.fulfill',
'escrowReward.fulfill'
],
conditionDependency: { conditionDependency: {
lockReward: [], lockReward: [],
serviceExecution: [], serviceExecution: [],

View File

@ -7,26 +7,15 @@ import { InstantiableConfig } from '../../../Instantiable.abstract'
import { escrowComputeExecutionTemplateServiceAgreementTemplate } from './EscrowComputeExecutionTemplate.serviceAgreementTemplate' import { escrowComputeExecutionTemplateServiceAgreementTemplate } from './EscrowComputeExecutionTemplate.serviceAgreementTemplate'
export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate { export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate {
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<EscrowComputeExecutionTemplate> {
config: InstantiableConfig return AgreementTemplate.getInstance(config, 'EscrowComputeExecutionTemplate', EscrowComputeExecutionTemplate)
): Promise<EscrowComputeExecutionTemplate> {
return AgreementTemplate.getInstance(
config,
'EscrowComputeExecutionTemplate',
EscrowComputeExecutionTemplate
)
} }
public async getServiceAgreementTemplate() { public async getServiceAgreementTemplate() {
return escrowComputeExecutionTemplateServiceAgreementTemplate return escrowComputeExecutionTemplateServiceAgreementTemplate
} }
public async createAgreementFromDDO( public async createAgreementFromDDO(agreementId: string, ddo: DDO, consumer: string, from?: string) {
agreementId: string,
ddo: DDO,
consumer: string,
from?: string
) {
return !!(await this.createFullAgreement( return !!(await this.createFullAgreement(
ddo.shortId(), ddo.shortId(),
ddo.findServiceByType('Metadata').metadata.base.price, ddo.findServiceByType('Metadata').metadata.base.price,
@ -36,12 +25,7 @@ export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate {
)) ))
} }
public async getAgreementIdsFromDDO( public async getAgreementIdsFromDDO(agreementId: string, ddo: DDO, consumer: string, from?: string) {
agreementId: string,
ddo: DDO,
consumer: string,
from?: string
) {
const { const {
computeExecutionConditionId, computeExecutionConditionId,
lockRewardConditionId, lockRewardConditionId,
@ -52,11 +36,7 @@ export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate {
ddo.findServiceByType('Metadata').metadata.base.price, ddo.findServiceByType('Metadata').metadata.base.price,
consumer consumer
) )
return [ return [computeExecutionConditionId, lockRewardConditionId, escrowRewardId]
computeExecutionConditionId,
lockRewardConditionId,
escrowRewardId
]
} }
/** /**
@ -77,21 +57,12 @@ export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate {
computeExecutionConditionId, computeExecutionConditionId,
lockRewardConditionId, lockRewardConditionId,
escrowRewardId escrowRewardId
} = await this.createFullAgreementData( } = await this.createFullAgreementData(agreementId, did, amount, consumer)
agreementId,
did,
amount,
consumer
)
await this.createAgreement( await this.createAgreement(
agreementId, agreementId,
did, did,
[ [computeExecutionConditionId, lockRewardConditionId, escrowRewardId],
computeExecutionConditionId,
lockRewardConditionId,
escrowRewardId
],
[0, 0, 0], [0, 0, 0],
[0, 0, 0], [0, 0, 0],
consumer, consumer,
@ -101,19 +72,10 @@ export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate {
return zeroX(agreementId) return zeroX(agreementId)
} }
private async createFullAgreementData( private async createFullAgreementData(agreementId: string, did: string, amount: number | string, consumer: string) {
agreementId: string,
did: string,
amount: number | string,
consumer: string
) {
const { didRegistry, conditions } = this.ocean.keeper const { didRegistry, conditions } = this.ocean.keeper
const { const { computeExecutionCondition, lockRewardCondition, escrowReward } = conditions
computeExecutionCondition,
lockRewardCondition,
escrowReward
} = conditions
const publisher = await didRegistry.getDIDOwner(did) const publisher = await didRegistry.getDIDOwner(did)
@ -122,11 +84,7 @@ export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate {
await escrowReward.getAddress(), await escrowReward.getAddress(),
amount amount
) )
const computeExecutionConditionId = await computeExecutionCondition.generateIdHash( const computeExecutionConditionId = await computeExecutionCondition.generateIdHash(agreementId, did, consumer)
agreementId,
did,
consumer
)
const escrowRewardId = await escrowReward.generateIdHash( const escrowRewardId = await escrowReward.generateIdHash(
agreementId, agreementId,
String(amount), String(amount),

View File

@ -1,8 +1,4 @@
export * from './AgreementTemplate.abstract' export * from './AgreementTemplate.abstract'
export { BaseEscrowTemplate } from './BaseEscrowTemplate.abstract' export { BaseEscrowTemplate } from './BaseEscrowTemplate.abstract'
export { export { EscrowAccessSecretStoreTemplate } from './EscrowAccessSecretStoreTemplate'
EscrowAccessSecretStoreTemplate export { EscrowComputeExecutionTemplate } from './EscrowComputeExecutionTemplate'
} from './EscrowAccessSecretStoreTemplate'
export {
EscrowComputeExecutionTemplate
} from './EscrowComputeExecutionTemplate'

View File

@ -87,9 +87,7 @@ export default class Account extends Instantiable {
* @return {Promise<number>} * @return {Promise<number>}
*/ */
public async getEtherBalance(): Promise<number> { public async getEtherBalance(): Promise<number> {
return this.web3.eth return this.web3.eth.getBalance(this.id, 'latest').then((balance: string): number => {
.getBalance(this.id, 'latest')
.then((balance: string): number => {
return new BigNumber(balance).toNumber() return new BigNumber(balance).toNumber()
}) })
} }

View File

@ -14,10 +14,7 @@ import Keeper from '../keeper/Keeper'
import { Config } from '../models/Config' import { Config } from '../models/Config'
import { import { Instantiable, generateIntantiableConfigFromConfig } from '../Instantiable.abstract'
Instantiable,
generateIntantiableConfigFromConfig
} from '../Instantiable.abstract'
/** /**
* Main interface for Ocean Protocol. * Main interface for Ocean Protocol.
@ -46,9 +43,7 @@ export class Ocean extends Instantiable {
instance.auth = await OceanAuth.getInstance(instanceConfig) instance.auth = await OceanAuth.getInstance(instanceConfig)
instance.assets = await OceanAssets.getInstance(instanceConfig) instance.assets = await OceanAssets.getInstance(instanceConfig)
instance.agreements = await OceanAgreements.getInstance(instanceConfig) instance.agreements = await OceanAgreements.getInstance(instanceConfig)
instance.secretStore = await OceanSecretStore.getInstance( instance.secretStore = await OceanSecretStore.getInstance(instanceConfig)
instanceConfig
)
instance.tokens = await OceanTokens.getInstance(instanceConfig) instance.tokens = await OceanTokens.getInstance(instanceConfig)
instance.versions = await OceanVersions.getInstance(instanceConfig) instance.versions = await OceanVersions.getInstance(instanceConfig)

View File

@ -10,9 +10,7 @@ export class OceanAccounts extends Instantiable {
* Returns the instance of OceanAccounts. * Returns the instance of OceanAccounts.
* @return {Promise<OceanAccounts>} * @return {Promise<OceanAccounts>}
*/ */
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<OceanAccounts> {
config: InstantiableConfig
): Promise<OceanAccounts> {
const instance = new OceanAccounts() const instance = new OceanAccounts()
instance.setInstanceConfig(config) instance.setInstanceConfig(config)
@ -27,9 +25,7 @@ export class OceanAccounts extends Instantiable {
// retrieve eth accounts // retrieve eth accounts
const ethAccounts: string[] = await this.web3.eth.getAccounts() const ethAccounts: string[] = await this.web3.eth.getAccounts()
const accountPromises = ethAccounts.map( const accountPromises = ethAccounts.map(address => new Account(address, this.instanceConfig))
address => new Account(address, this.instanceConfig)
)
return Promise.all(accountPromises) return Promise.all(accountPromises)
} }
@ -48,10 +44,7 @@ export class OceanAccounts extends Instantiable {
* @param {number} amount Token amount. * @param {number} amount Token amount.
* @return {Promise<boolean>} Success. * @return {Promise<boolean>} Success.
*/ */
public async requestTokens( public async requestTokens(account: Account, amount: number): Promise<boolean> {
account: Account,
amount: number
): Promise<boolean> {
try { try {
await account.requestTokens(amount) await account.requestTokens(amount)
return true return true

View File

@ -21,14 +21,10 @@ export class OceanAgreements extends Instantiable {
* Returns the instance of OceanAgreements. * Returns the instance of OceanAgreements.
* @return {Promise<OceanAgreements>} * @return {Promise<OceanAgreements>}
*/ */
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<OceanAgreements> {
config: InstantiableConfig
): Promise<OceanAgreements> {
const instance = new OceanAgreements() const instance = new OceanAgreements()
instance.setInstanceConfig(config) instance.setInstanceConfig(config)
instance.conditions = await OceanAgreementsConditions.getInstance( instance.conditions = await OceanAgreementsConditions.getInstance(config)
config
)
return instance return instance
} }
@ -46,25 +42,15 @@ export class OceanAgreements extends Instantiable {
* @param {Account} consumer Consumer account. * @param {Account} consumer Consumer account.
* @return {Promise<AgreementPrepareResult>} Agreement ID and signaturee. * @return {Promise<AgreementPrepareResult>} Agreement ID and signaturee.
*/ */
public async prepare( public async prepare(did: string, index: number, consumer: Account): Promise<AgreementPrepareResult> {
did: string,
index: number,
consumer: Account
): Promise<AgreementPrepareResult> {
const d: DID = DID.parse(did as string) const d: DID = DID.parse(did as string)
const ddo = await this.ocean.aquarius.retrieveDDO(d) const ddo = await this.ocean.aquarius.retrieveDDO(d)
const agreementId: string = zeroX(generateId()) const agreementId: string = zeroX(generateId())
const templateName = ddo.findServiceByType('access') const templateName = ddo.findServiceByType('access').serviceAgreementTemplate.contractName
.serviceAgreementTemplate.contractName
const agreementConditionsIds = await this.ocean.keeper const agreementConditionsIds = await this.ocean.keeper
.getTemplateByName(templateName) .getTemplateByName(templateName)
.getAgreementIdsFromDDO( .getAgreementIdsFromDDO(agreementId, ddo, consumer.getId(), consumer.getId())
agreementId,
ddo,
consumer.getId(),
consumer.getId()
)
const signature = await this.ocean.utils.agreements.signServiceAgreement( const signature = await this.ocean.utils.agreements.signServiceAgreement(
ddo, ddo,
@ -100,9 +86,7 @@ export class OceanAgreements extends Instantiable {
) )
if (!result.ok) { if (!result.ok) {
throw new Error( throw new Error('Error on initialize agreement: ' + (await result.text()))
'Error on initialize agreement: ' + (await result.text())
)
} }
} }
@ -129,16 +113,10 @@ export class OceanAgreements extends Instantiable {
const d: DID = DID.parse(did) const d: DID = DID.parse(did)
const ddo = await this.ocean.aquarius.retrieveDDO(d) const ddo = await this.ocean.aquarius.retrieveDDO(d)
const templateName = ddo.findServiceById<'access'>(index) const templateName = ddo.findServiceById<'access'>(index).serviceAgreementTemplate.contractName
.serviceAgreementTemplate.contractName
await this.ocean.keeper await this.ocean.keeper
.getTemplateByName(templateName) .getTemplateByName(templateName)
.createAgreementFromDDO( .createAgreementFromDDO(agreementId, ddo, consumer.getId(), publisher.getId())
agreementId,
ddo,
consumer.getId(),
publisher.getId()
)
return true return true
} }
@ -149,25 +127,13 @@ export class OceanAgreements extends Instantiable {
* @param {boolean} extended Returns a complete status with dependencies. * @param {boolean} extended Returns a complete status with dependencies.
* @return {Promise<any>} * @return {Promise<any>}
*/ */
public async status( public async status(agreementId: string, extended?: false): Promise<{ [condition: string]: ConditionState }>
agreementId: string,
extended?: false
): Promise<{ [condition: string]: ConditionState }>
public async status( public async status(agreementId: string, extended: true): Promise<AgreementConditionsStatus>
agreementId: string,
extended: true
): Promise<AgreementConditionsStatus>
public async status(agreementId: string, extended: boolean = false) { public async status(agreementId: string, extended: boolean = false) {
const { const { templateId } = await this.ocean.keeper.agreementStoreManager.getAgreement(agreementId)
templateId const fullStatus = await this.ocean.keeper.getTemplateByAddress(templateId).getAgreementStatus(agreementId)
} = await this.ocean.keeper.agreementStoreManager.getAgreement(
agreementId
)
const fullStatus = await this.ocean.keeper
.getTemplateByAddress(templateId)
.getAgreementStatus(agreementId)
if (!fullStatus) { if (!fullStatus) {
return return

View File

@ -9,9 +9,7 @@ export class OceanAgreementsConditions extends Instantiable {
* Returns the instance of OceanAgreementsConditions. * Returns the instance of OceanAgreementsConditions.
* @return {Promise<OceanAgreementsConditions>} * @return {Promise<OceanAgreementsConditions>}
*/ */
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<OceanAgreementsConditions> {
config: InstantiableConfig
): Promise<OceanAgreementsConditions> {
const instance = new OceanAgreementsConditions() const instance = new OceanAgreementsConditions()
instance.setInstanceConfig(config) instance.setInstanceConfig(config)
@ -25,22 +23,11 @@ export class OceanAgreementsConditions extends Instantiable {
* @param {number} amount Asset amount. * @param {number} amount Asset amount.
* @param {Account} from Account of sender. * @param {Account} from Account of sender.
*/ */
public async lockReward( public async lockReward(agreementId: string, amount: number | string, from?: Account) {
agreementId: string, const { lockRewardCondition, escrowReward } = this.ocean.keeper.conditions
amount: number | string,
from?: Account
) {
const {
lockRewardCondition,
escrowReward
} = this.ocean.keeper.conditions
try { try {
await this.ocean.keeper.token.approve( await this.ocean.keeper.token.approve(lockRewardCondition.getAddress(), amount, from.getId())
lockRewardCondition.getAddress(),
amount,
from.getId()
)
const receipt = await lockRewardCondition.fulfill( const receipt = await lockRewardCondition.fulfill(
agreementId, agreementId,
@ -62,21 +49,11 @@ export class OceanAgreementsConditions extends Instantiable {
* @param {string} grantee Consumer address. * @param {string} grantee Consumer address.
* @param {Account} from Account of sender. * @param {Account} from Account of sender.
*/ */
public async grantAccess( public async grantAccess(agreementId: string, did: string, grantee: string, from?: Account) {
agreementId: string,
did: string,
grantee: string,
from?: Account
) {
try { try {
const { accessSecretStoreCondition } = this.ocean.keeper.conditions const { accessSecretStoreCondition } = this.ocean.keeper.conditions
const receipt = await accessSecretStoreCondition.fulfill( const receipt = await accessSecretStoreCondition.fulfill(agreementId, did, grantee, from && from.getId())
agreementId,
did,
grantee,
from && from.getId()
)
return !!receipt.events.Fulfilled return !!receipt.events.Fulfilled
} catch { } catch {
return false return false
@ -90,21 +67,11 @@ export class OceanAgreementsConditions extends Instantiable {
* @param {string} grantee Consumer address. * @param {string} grantee Consumer address.
* @param {Account} from Account of sender. * @param {Account} from Account of sender.
*/ */
public async grantServiceExecution( public async grantServiceExecution(agreementId: string, did: string, grantee: string, from?: Account) {
agreementId: string,
did: string,
grantee: string,
from?: Account
) {
try { try {
const { computeExecutionCondition } = this.ocean.keeper.conditions const { computeExecutionCondition } = this.ocean.keeper.conditions
const receipt = await computeExecutionCondition.fulfill( const receipt = await computeExecutionCondition.fulfill(agreementId, did, grantee, from && from.getId())
agreementId,
did,
grantee,
from && from.getId()
)
return !!receipt.events.Fulfilled return !!receipt.events.Fulfilled
} catch { } catch {
return false return false
@ -133,17 +100,9 @@ export class OceanAgreementsConditions extends Instantiable {
from?: Account from?: Account
) { ) {
try { try {
const { const { escrowReward, accessSecretStoreCondition, lockRewardCondition } = this.ocean.keeper.conditions
escrowReward,
accessSecretStoreCondition,
lockRewardCondition
} = this.ocean.keeper.conditions
const conditionIdAccess = await accessSecretStoreCondition.generateIdHash( const conditionIdAccess = await accessSecretStoreCondition.generateIdHash(agreementId, did, consumer)
agreementId,
did,
consumer
)
const conditionIdLock = await lockRewardCondition.generateIdHash( const conditionIdLock = await lockRewardCondition.generateIdHash(
agreementId, agreementId,
escrowReward.getAddress(), escrowReward.getAddress(),

View File

@ -4,12 +4,7 @@ import { MetaData } from '../ddo/MetaData'
import { Service } from '../ddo/Service' import { Service } from '../ddo/Service'
import Account from './Account' import Account from './Account'
import DID from './DID' import DID from './DID'
import { import { fillConditionsWithDDO, SubscribablePromise, generateId, zeroX } from '../utils'
fillConditionsWithDDO,
SubscribablePromise,
generateId,
zeroX
} from '../utils'
import { Instantiable, InstantiableConfig } from '../Instantiable.abstract' import { Instantiable, InstantiableConfig } from '../Instantiable.abstract'
export enum CreateProgressStep { export enum CreateProgressStep {
@ -38,9 +33,7 @@ export class OceanAssets extends Instantiable {
* Returns the instance of OceanAssets. * Returns the instance of OceanAssets.
* @return {Promise<OceanAssets>} * @return {Promise<OceanAssets>}
*/ */
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<OceanAssets> {
config: InstantiableConfig
): Promise<OceanAssets> {
const instance = new OceanAssets() const instance = new OceanAssets()
instance.setInstanceConfig(config) instance.setInstanceConfig(config)
@ -53,9 +46,7 @@ export class OceanAssets extends Instantiable {
* @return {Promise<DDO>} * @return {Promise<DDO>}
*/ */
public async resolve(did: string): Promise<DDO> { public async resolve(did: string): Promise<DDO> {
const { const { serviceEndpoint } = await this.ocean.keeper.didRegistry.getAttributesByDid(did)
serviceEndpoint
} = await this.ocean.keeper.didRegistry.getAttributesByDid(did)
return this.ocean.aquarius.retrieveDDOByUrl(serviceEndpoint) return this.ocean.aquarius.retrieveDDOByUrl(serviceEndpoint)
} }
@ -79,11 +70,7 @@ export class OceanAssets extends Instantiable {
this.logger.log('Encrypting files') this.logger.log('Encrypting files')
observer.next(CreateProgressStep.EncryptingFiles) observer.next(CreateProgressStep.EncryptingFiles)
const encryptedFiles = await this.ocean.secretStore.encrypt( const encryptedFiles = await this.ocean.secretStore.encrypt(did.getId(), metadata.main.files, publisher)
did.getId(),
metadata.main.files,
publisher
)
this.logger.log('Files encrypted') this.logger.log('Files encrypted')
observer.next(CreateProgressStep.FilesEncrypted) observer.next(CreateProgressStep.FilesEncrypted)
@ -139,13 +126,11 @@ export class OceanAssets extends Instantiable {
...metadata.main, ...metadata.main,
contentUrls: undefined, contentUrls: undefined,
encryptedFiles, encryptedFiles,
files: metadata.main.files.map( files: metadata.main.files.map((file, index) => ({
(file, index) => ({
...file, ...file,
index, index,
url: undefined url: undefined
}) }))
)
} as any } as any
} }
}, },
@ -153,10 +138,7 @@ export class OceanAssets extends Instantiable {
] ]
// Remove duplications // Remove duplications
.reverse() .reverse()
.filter( .filter(({ type }, i, list) => list.findIndex(({ type: t }) => t === type) === i)
({ type }, i, list) =>
list.findIndex(({ type: t }) => t === type) === i
)
.reverse() .reverse()
// Adding index // Adding index
.map(_ => ({ .map(_ => ({
@ -173,11 +155,7 @@ export class OceanAssets extends Instantiable {
ddo.addChecksum() ddo.addChecksum()
this.logger.log('Generating proof') this.logger.log('Generating proof')
observer.next(CreateProgressStep.GeneratingProof) observer.next(CreateProgressStep.GeneratingProof)
await ddo.addProof( await ddo.addProof(this.ocean, publisher.getId(), publisher.getPassword())
this.ocean,
publisher.getId(),
publisher.getPassword()
)
this.logger.log('Proof generated') this.logger.log('Proof generated')
observer.next(CreateProgressStep.ProofGenerated) observer.next(CreateProgressStep.ProofGenerated)
@ -242,16 +220,12 @@ export class OceanAssets extends Instantiable {
const { serviceEndpoint } = accessService const { serviceEndpoint } = accessService
if (!serviceEndpoint) { if (!serviceEndpoint) {
throw new Error( throw new Error('Consume asset failed, service definition is missing the `serviceEndpoint`.')
'Consume asset failed, service definition is missing the `serviceEndpoint`.'
)
} }
this.logger.log('Consuming files') this.logger.log('Consuming files')
resultPath = resultPath resultPath = resultPath ? `${resultPath}/datafile.${ddo.shortId()}.${serviceIndex}/` : undefined
? `${resultPath}/datafile.${ddo.shortId()}.${serviceIndex}/`
: undefined
if (!useSecretStore) { if (!useSecretStore) {
await this.ocean.brizo.consumeService( await this.ocean.brizo.consumeService(
@ -265,16 +239,13 @@ export class OceanAssets extends Instantiable {
} else { } else {
const files = await this.ocean.secretStore.decrypt( const files = await this.ocean.secretStore.decrypt(
did, did,
ddo.findServiceByType('metadata').attributes.main ddo.findServiceByType('metadata').attributes.main.encryptedFiles,
.encryptedFiles,
consumerAccount, consumerAccount,
ddo.findServiceByType('authorization').serviceEndpoint ddo.findServiceByType('authorization').serviceEndpoint
) )
const downloads = files const downloads = files
.filter(({ index: i }) => index === -1 || index === i) .filter(({ index: i }) => index === -1 || index === i)
.map(({ url, index: i }) => .map(({ url, index: i }) => this.ocean.utils.fetch.downloadFile(url, resultPath, i))
this.ocean.utils.fetch.downloadFile(url, resultPath, i)
)
await Promise.all(downloads) await Promise.all(downloads)
} }
this.logger.log('Files consumed') this.logger.log('Files consumed')
@ -293,11 +264,7 @@ export class OceanAssets extends Instantiable {
* @param {Account} consumer Consumer account. * @param {Account} consumer Consumer account.
* @return {Promise<string>} Returns Agreement ID * @return {Promise<string>} Returns Agreement ID
*/ */
public order( public order(did: string, index: number, consumer: Account): SubscribablePromise<OrderProgressStep, string> {
did: string,
index: number,
consumer: Account
): SubscribablePromise<OrderProgressStep, string> {
return new SubscribablePromise(async observer => { return new SubscribablePromise(async observer => {
const oceanAgreements = this.ocean.agreements const oceanAgreements = this.ocean.agreements
@ -305,8 +272,7 @@ export class OceanAssets extends Instantiable {
const ddo = await this.resolve(did) const ddo = await this.resolve(did)
const { keeper } = this.ocean const { keeper } = this.ocean
const templateName = ddo.findServiceByType('access') const templateName = ddo.findServiceByType('access').serviceAgreementTemplate.contractName
.serviceAgreementTemplate.contractName
const template = keeper.getTemplateByName(templateName) const template = keeper.getTemplateByName(templateName)
const accessCondition = keeper.conditions.accessSecretStoreCondition const accessCondition = keeper.conditions.accessSecretStoreCondition
@ -321,16 +287,10 @@ export class OceanAssets extends Instantiable {
this.logger.log('Locking payment') this.logger.log('Locking payment')
const accessGranted = accessCondition const accessGranted = accessCondition.getConditionFulfilledEvent(agreementId).once()
.getConditionFulfilledEvent(agreementId)
.once()
observer.next(OrderProgressStep.LockingPayment) observer.next(OrderProgressStep.LockingPayment)
const paid = await oceanAgreements.conditions.lockReward( const paid = await oceanAgreements.conditions.lockReward(agreementId, attributes.main.price, consumer)
agreementId,
attributes.main.price,
consumer
)
observer.next(OrderProgressStep.LockedPayment) observer.next(OrderProgressStep.LockedPayment)
if (paid) { if (paid) {
@ -350,14 +310,7 @@ export class OceanAssets extends Instantiable {
observer.next(OrderProgressStep.CreatingAgreement) observer.next(OrderProgressStep.CreatingAgreement)
this.logger.log('Creating agreement') this.logger.log('Creating agreement')
await oceanAgreements.create( await oceanAgreements.create(did, agreementId, index, undefined, consumer, consumer)
did,
agreementId,
index,
undefined,
consumer,
consumer
)
this.logger.log('Agreement created') this.logger.log('Agreement created')
try { try {
@ -379,15 +332,10 @@ export class OceanAssets extends Instantiable {
const ddo = await this.resolve(did) const ddo = await this.resolve(did)
const checksum = ddo.getChecksum() const checksum = ddo.getChecksum()
const { creator, signatureValue } = ddo.proof const { creator, signatureValue } = ddo.proof
const signer = await this.ocean.utils.signature.verifyText( const signer = await this.ocean.utils.signature.verifyText(checksum, signatureValue)
checksum,
signatureValue
)
if (signer.toLowerCase() !== creator.toLowerCase()) { if (signer.toLowerCase() !== creator.toLowerCase()) {
this.logger.warn( this.logger.warn(`Owner of ${ddo.id} doesn't match. Expected ${creator} instead of ${signer}.`)
`Owner of ${ddo.id} doesn't match. Expected ${creator} instead of ${signer}.`
)
} }
return creator return creator
@ -408,9 +356,9 @@ export class OceanAssets extends Instantiable {
* @return {Promise<string[]>} List of DIDs. * @return {Promise<string[]>} List of DIDs.
*/ */
public async consumerAssets(consumer: string) { public async consumerAssets(consumer: string) {
return (await this.ocean.keeper.conditions.accessSecretStoreCondition.getGrantedDidByConsumer( return (await this.ocean.keeper.conditions.accessSecretStoreCondition.getGrantedDidByConsumer(consumer)).map(
consumer ({ did }) => did
)).map(({ did }) => did) )
} }
/** /**

View File

@ -13,9 +13,7 @@ export class OceanAuth extends Instantiable {
* Returns the instance of OceanAuth. * Returns the instance of OceanAuth.
* @return {Promise<OceanAuth>} * @return {Promise<OceanAuth>}
*/ */
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<OceanAuth> {
config: InstantiableConfig
): Promise<OceanAuth> {
const instance = new OceanAuth() const instance = new OceanAuth()
instance.setInstanceConfig(config) instance.setInstanceConfig(config)
@ -32,11 +30,7 @@ export class OceanAuth extends Instantiable {
const message = `${this.getMessage()}\n${time}` const message = `${this.getMessage()}\n${time}`
try { try {
const signature = await this.ocean.utils.signature.signText( const signature = await this.ocean.utils.signature.signText(message, account.getId(), account.getPassword())
message,
account.getId(),
account.getPassword()
)
return `${signature}-${time}` return `${signature}-${time}`
} catch { } catch {
@ -59,9 +53,7 @@ export class OceanAuth extends Instantiable {
return `0x${'0'.repeat(40)}` return `0x${'0'.repeat(40)}`
} }
return this.web3.utils.toChecksumAddress( return this.web3.utils.toChecksumAddress(await this.ocean.utils.signature.verifyText(message, signature))
await this.ocean.utils.signature.verifyText(message, signature)
)
} }
/** /**
@ -129,9 +121,7 @@ export class OceanAuth extends Instantiable {
try { try {
localStorage.getItem('') localStorage.getItem('')
} catch { } catch {
throw new Error( throw new Error('LocalStorage is not supported. This feature is only available on browsers.')
'LocalStorage is not supported. This feature is only available on browsers.'
)
} }
return localStorage return localStorage
} }

View File

@ -13,9 +13,7 @@ export class OceanSecretStore extends Instantiable {
* Returns the instance of OceanSecretStore. * Returns the instance of OceanSecretStore.
* @return {Promise<OceanSecretStore>} * @return {Promise<OceanSecretStore>}
*/ */
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<OceanSecretStore> {
config: InstantiableConfig
): Promise<OceanSecretStore> {
const instance = new OceanSecretStore() const instance = new OceanSecretStore()
instance.setInstanceConfig(config) instance.setInstanceConfig(config)
@ -30,25 +28,12 @@ export class OceanSecretStore extends Instantiable {
* @param {string} publisher Publisher account. * @param {string} publisher Publisher account.
* @return {Promise<string>} Encrypted text. * @return {Promise<string>} Encrypted text.
*/ */
public async encrypt( public async encrypt(did: string, document: any, publisher: Account): Promise<string> {
did: string,
document: any,
publisher: Account
): Promise<string> {
const signature = const signature =
(await publisher.getToken()) || (await publisher.getToken()) ||
(await this.ocean.utils.signature.signText( (await this.ocean.utils.signature.signText(noDidPrefixed(did), publisher.getId(), publisher.getPassword()))
noDidPrefixed(did),
publisher.getId(),
publisher.getPassword()
))
return this.ocean.brizo.encrypt( return this.ocean.brizo.encrypt(noDidPrefixed(did), signature, document, publisher.getId())
noDidPrefixed(did),
signature,
document,
publisher.getId()
)
} }
/** /**
@ -59,16 +44,8 @@ export class OceanSecretStore extends Instantiable {
* @param {string} consumer cONSUMER account. * @param {string} consumer cONSUMER account.
* @return {Promise<string>} Encrypted text. * @return {Promise<string>} Encrypted text.
*/ */
public async decrypt( public async decrypt(did: string, content: string, consumer?: Account, secretStoreUrl?: string): Promise<any> {
did: string, return this.getSecretStoreByAccount(consumer, secretStoreUrl).decryptDocument(noDidPrefixed(did), content)
content: string,
consumer?: Account,
secretStoreUrl?: string
): Promise<any> {
return this.getSecretStoreByAccount(
consumer,
secretStoreUrl
).decryptDocument(noDidPrefixed(did), content)
} }
private getSecretStoreByAccount(account: Account, secretStoreUrl?: string) { private getSecretStoreByAccount(account: Account, secretStoreUrl?: string) {
@ -86,13 +63,7 @@ export class OceanSecretStore extends Instantiable {
} }
private getSecretStore(config: SecretStoreConfig): SecretStore { private getSecretStore(config: SecretStoreConfig): SecretStore {
const { const { secretStoreUri, parityUri, password, address, threshold } = config
secretStoreUri,
parityUri,
password,
address,
threshold
} = config
config = { secretStoreUri, parityUri, password, address, threshold } config = { secretStoreUri, parityUri, password, address, threshold }
return new SecretStore(config) return new SecretStore(config)

View File

@ -9,9 +9,7 @@ export class OceanTokens extends Instantiable {
* Returns the instance of OceanTokens. * Returns the instance of OceanTokens.
* @return {Promise<OceanTokens>} * @return {Promise<OceanTokens>}
*/ */
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<OceanTokens> {
config: InstantiableConfig
): Promise<OceanTokens> {
const instance = new OceanTokens() const instance = new OceanTokens()
instance.setInstanceConfig(config) instance.setInstanceConfig(config)
@ -25,11 +23,7 @@ export class OceanTokens extends Instantiable {
* @param {Account} from Sender account address. * @param {Account} from Sender account address.
* @return {Promise<boolean>} Success, * @return {Promise<boolean>} Success,
*/ */
public async transfer( public async transfer(to: string, amount: number, from: Account): Promise<boolean> {
to: string,
amount: number,
from: Account
): Promise<boolean> {
this.ocean.keeper.token.transfer(to, amount, from.getId()) this.ocean.keeper.token.transfer(to, amount, from.getId())
return true return true
} }

View File

@ -42,9 +42,7 @@ export class OceanVersions extends Instantiable {
* Returns the instance of OceanVersions. * Returns the instance of OceanVersions.
* @return {Promise<OceanVersions>} * @return {Promise<OceanVersions>}
*/ */
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<OceanVersions> {
config: InstantiableConfig
): Promise<OceanVersions> {
const instance = new OceanVersions() const instance = new OceanVersions()
instance.setInstanceConfig(config) instance.setInstanceConfig(config)
@ -99,10 +97,7 @@ export class OceanVersions extends Instantiable {
// Aquarius // Aquarius
try { try {
const { const { software: name, version } = await this.ocean.aquarius.getVersionInfo()
software: name,
version
} = await this.ocean.aquarius.getVersionInfo()
versions.aquarius = { versions.aquarius = {
name, name,
status: OceanPlatformTechStatus.Working, status: OceanPlatformTechStatus.Working,
@ -124,9 +119,7 @@ export class OceanVersions extends Instantiable {
.reduce((acc, network) => ({ ...acc, [network]: true }), {}) .reduce((acc, network) => ({ ...acc, [network]: true }), {})
let contractStatus = true let contractStatus = true
const contractList = techs const contractList = techs.map(({ contracts }) => contracts).filter(_ => !!_)
.map(({ contracts }) => contracts)
.filter(_ => !!_)
Array.from(contractList.map(Object.keys)) Array.from(contractList.map(Object.keys))
.reduce((acc, _) => [...acc, ..._], []) .reduce((acc, _) => [...acc, ..._], [])
.filter((_, i, list) => list.indexOf(_) === i) .filter((_, i, list) => list.indexOf(_) === i)
@ -146,9 +139,7 @@ export class OceanVersions extends Instantiable {
}) })
versions.status = { versions.status = {
ok: !techs.find( ok: !techs.find(({ status }) => status !== OceanPlatformTechStatus.Working),
({ status }) => status !== OceanPlatformTechStatus.Working
),
network: Object.keys(networks).length === 1, network: Object.keys(networks).length === 1,
contracts: contractStatus contracts: contractStatus
} }

View File

@ -12,9 +12,7 @@ export class OceanUtils extends Instantiable {
* Returns the instance of OceanUtils. * Returns the instance of OceanUtils.
* @return {Promise<OceanUtils>} * @return {Promise<OceanUtils>}
*/ */
public static async getInstance( public static async getInstance(config: InstantiableConfig): Promise<OceanUtils> {
config: InstantiableConfig
): Promise<OceanUtils> {
const instance = new OceanUtils() const instance = new OceanUtils()
instance.setInstanceConfig(config) instance.setInstanceConfig(config)

View File

@ -19,14 +19,8 @@ export class ServiceAgreement extends Instantiable {
consumer: Account consumer: Account
): Promise<string> { ): Promise<string> {
const service = ddo.findServiceById<'access'>(index) const service = ddo.findServiceById<'access'>(index)
const timelockValues: number[] = this.getTimeValuesFromService( const timelockValues: number[] = this.getTimeValuesFromService(service, 'timelock')
service, const timeoutValues: number[] = this.getTimeValuesFromService(service, 'timeout')
'timelock'
)
const timeoutValues: number[] = this.getTimeValuesFromService(
service,
'timeout'
)
if (!service.templateId) { if (!service.templateId) {
throw new Error('TemplateId not found in DDO.') throw new Error('TemplateId not found in DDO.')
@ -89,10 +83,7 @@ export class ServiceAgreement extends Instantiable {
return this.web3.utils.soliditySha3(...args).toString('hex') return this.web3.utils.soliditySha3(...args).toString('hex')
} }
private getTimeValuesFromService( private getTimeValuesFromService(service: ServiceAccess, type: 'timeout' | 'timelock'): number[] {
service: ServiceAccess,
type: 'timeout' | 'timelock'
): number[] {
const timeoutValues: number[] = service.serviceAgreementTemplate.conditions.map( const timeoutValues: number[] = service.serviceAgreementTemplate.conditions.map(
(condition: ServiceAgreementTemplateCondition) => condition[type] (condition: ServiceAgreementTemplateCondition) => condition[type]
) )

View File

@ -6,15 +6,8 @@ export class SignatureUtils extends Instantiable {
this.setInstanceConfig(config) this.setInstanceConfig(config)
} }
public async signText( public async signText(text: string, publicKey: string, password?: string): Promise<string> {
text: string, const isMetaMask = this.web3 && this.web3.currentProvider && this.web3.currentProvider.isMetaMask
publicKey: string,
password?: string
): Promise<string> {
const isMetaMask =
this.web3 &&
this.web3.currentProvider &&
this.web3.currentProvider.isMetaMask
try { try {
return await this.web3.eth.personal.sign(text, publicKey, password) return await this.web3.eth.personal.sign(text, publicKey, password)
} catch (e) { } catch (e) {

View File

@ -43,20 +43,14 @@ export class WebServiceConnector extends Instantiable {
}) })
} }
public async downloadFile( public async downloadFile(url: string, destination?: string, index?: number): Promise<string> {
url: string,
destination?: string,
index?: number
): Promise<string> {
const response = await this.get(url) const response = await this.get(url)
if (!response.ok) { if (!response.ok) {
throw new Error('Response error.') throw new Error('Response error.')
} }
let filename let filename
try { try {
filename = response.headers filename = response.headers.get('content-disposition').match(/attachment;filename=(.+)/)[1]
.get('content-disposition')
.match(/attachment;filename=(.+)/)[1]
} catch { } catch {
try { try {
filename = url.split('/').pop() filename = url.split('/').pop()
@ -69,9 +63,7 @@ export class WebServiceConnector extends Instantiable {
// eslint-disable-next-line no-async-promise-executor // eslint-disable-next-line no-async-promise-executor
await new Promise(async (resolve, reject) => { await new Promise(async (resolve, reject) => {
fs.mkdirSync(destination, { recursive: true }) fs.mkdirSync(destination, { recursive: true })
const fileStream = fs.createWriteStream( const fileStream = fs.createWriteStream(`${destination}${filename}`)
`${destination}${filename}`
)
response.body.pipe(fileStream) response.body.pipe(fileStream)
response.body.on('error', reject) response.body.on('error', reject)
fileStream.on('finish', resolve) fileStream.on('finish', resolve)

View File

@ -24,14 +24,4 @@ export {
export { AgreementTemplate } from './keeper/contracts/templates' export { AgreementTemplate } from './keeper/contracts/templates'
export { Condition, ConditionState } from './keeper/contracts/conditions' export { Condition, ConditionState } from './keeper/contracts/conditions'
export { export { Ocean, Account, Config, DID, Logger, Keeper, conditions, templates, utils }
Ocean,
Account,
Config,
DID,
Logger,
Keeper,
conditions,
templates,
utils
}

View File

@ -4,11 +4,7 @@ import { LoggerInstance } from './Logger'
export const zeroX = (input: string) => zeroXTransformer(input, true) export const zeroX = (input: string) => zeroXTransformer(input, true)
export const noZeroX = (input: string) => zeroXTransformer(input, false) export const noZeroX = (input: string) => zeroXTransformer(input, false)
export function zeroXTransformer(input: string = '', zeroOutput: boolean) { export function zeroXTransformer(input: string = '', zeroOutput: boolean) {
const { valid, output } = inputMatch( const { valid, output } = inputMatch(input, /^(?:0x)*([a-f0-9]+)$/i, 'zeroXTransformer')
input,
/^(?:0x)*([a-f0-9]+)$/i,
'zeroXTransformer'
)
return (zeroOutput && valid ? '0x' : '') + output return (zeroOutput && valid ? '0x' : '') + output
} }
@ -16,11 +12,7 @@ export function zeroXTransformer(input: string = '', zeroOutput: boolean) {
export const didPrefixed = (input: string) => didTransformer(input, true) export const didPrefixed = (input: string) => didTransformer(input, true)
export const noDidPrefixed = (input: string) => didTransformer(input, false) export const noDidPrefixed = (input: string) => didTransformer(input, false)
export function didTransformer(input: string = '', prefixOutput: boolean) { export function didTransformer(input: string = '', prefixOutput: boolean) {
const { valid, output } = inputMatch( const { valid, output } = inputMatch(input, /^(?:0x|did:op:)*([a-f0-9]{64})$/i, 'didTransformer')
input,
/^(?:0x|did:op:)*([a-f0-9]{64})$/i,
'didTransformer'
)
return (prefixOutput && valid ? 'did:op:' : '') + output return (prefixOutput && valid ? 'did:op:' : '') + output
} }
@ -28,17 +20,11 @@ export function didTransformer(input: string = '', prefixOutput: boolean) {
export const didZeroX = (input: string) => zeroX(didTransformer(input, false)) export const didZeroX = (input: string) => zeroX(didTransformer(input, false))
// Shared functions // Shared functions
function inputMatch( function inputMatch(input: string, regexp: RegExp, conversorName: string): { valid: boolean; output: string } {
input: string,
regexp: RegExp,
conversorName: string
): { valid: boolean; output: string } {
if (typeof input !== 'string') { if (typeof input !== 'string') {
LoggerInstance.debug('Not input string:') LoggerInstance.debug('Not input string:')
LoggerInstance.debug(input) LoggerInstance.debug(input)
throw new Error( throw new Error(`[${conversorName}] Expected string, input type: ${typeof input}`)
`[${conversorName}] Expected string, input type: ${typeof input}`
)
} }
const match = input.match(regexp) const match = input.match(regexp)
if (!match) { if (!match) {

View File

@ -1,8 +1,5 @@
import { DDO } from '../ddo/DDO' import { DDO } from '../ddo/DDO'
import { import { ServiceAgreementTemplateCondition, ServiceAgreementTemplateParameter } from '../ddo/ServiceAgreementTemplate'
ServiceAgreementTemplateCondition,
ServiceAgreementTemplateParameter
} from '../ddo/ServiceAgreementTemplate'
function fillParameterWithDDO( function fillParameterWithDDO(
parameter: ServiceAgreementTemplateParameter, parameter: ServiceAgreementTemplateParameter,
@ -12,9 +9,7 @@ function fillParameterWithDDO(
switch (name) { switch (name) {
case 'amount': case 'amount':
case 'price': case 'price':
return String( return String(ddo.findServiceByType('metadata').attributes.main.price)
ddo.findServiceByType('metadata').attributes.main.price
)
case 'assetId': case 'assetId':
case 'documentId': case 'documentId':
case 'documentKeyId': case 'documentKeyId':

View File

@ -8,9 +8,7 @@ const zipObject = (keys = [], values = []) => {
) )
} }
export const objectPromiseAll = async (obj: { export const objectPromiseAll = async (obj: { [key: string]: Promise<any> }) => {
[key: string]: Promise<any>
}) => {
const keys = Object.keys(obj) const keys = Object.keys(obj)
const result = await Promise.all(Object.values(obj)) const result = await Promise.all(Object.values(obj))
return zipObject(keys, result) return zipObject(keys, result)

View File

@ -7,11 +7,7 @@ export class SubscribableObserver<T, P> {
onError?: (error: any) => void onError?: (error: any) => void
}>() }>()
public subscribe( public subscribe(onNext?: (next: T) => void, onComplete?: (complete: P) => void, onError?: (error: any) => void) {
onNext?: (next: T) => void,
onComplete?: (complete: P) => void,
onError?: (error: any) => void
) {
if (this.completed) { if (this.completed) {
throw new Error('Observer completed.') throw new Error('Observer completed.')
} }
@ -40,9 +36,7 @@ export class SubscribableObserver<T, P> {
private emit(type: 'onNext' | 'onComplete' | 'onError', value: any) { private emit(type: 'onNext' | 'onComplete' | 'onError', value: any) {
Array.from(this.subscriptions) Array.from(this.subscriptions)
.map(subscription => subscription[type]) .map(subscription => subscription[type])
.filter( .filter((callback: any) => callback && typeof callback === 'function')
(callback: any) => callback && typeof callback === 'function'
)
.forEach((callback: any) => callback(value)) .forEach((callback: any) => callback(value))
} }

View File

@ -12,9 +12,7 @@ export class SubscribablePromise<T extends any, P extends any> {
this this
) )
constructor( constructor(executor: (observer: SubscribableObserver<T, P>) => void | Promise<P>) {
executor: (observer: SubscribableObserver<T, P>) => void | Promise<P>
) {
// Defear // Defear
setTimeout(() => this.init(executor), 1) setTimeout(() => this.init(executor), 1)
} }
@ -28,10 +26,7 @@ export class SubscribablePromise<T extends any, P extends any> {
return this return this
} }
public then( public then(onfulfilled?: (value: P) => any, onrejected?: (error: any) => any) {
onfulfilled?: (value: P) => any,
onrejected?: (error: any) => any
) {
return Object.assign(this.promise.then(onfulfilled, onrejected), this) return Object.assign(this.promise.then(onfulfilled, onrejected), this)
} }
@ -43,9 +38,7 @@ export class SubscribablePromise<T extends any, P extends any> {
return Object.assign(this.promise.finally(onfinally), this) return Object.assign(this.promise.finally(onfinally), this)
} }
private init( private init(executor: (observer: SubscribableObserver<T, P>) => void | Promise<P>) {
executor: (observer: SubscribableObserver<T, P>) => void | Promise<P>
) {
const execution = executor(this.observer) const execution = executor(this.observer)
Promise.resolve(execution as any) Promise.resolve(execution as any)

View File

@ -17,12 +17,12 @@ describe('Aquarius', () => {
let ocean: Ocean let ocean: Ocean
let aquarius: Aquarius let aquarius: Aquarius
/* eslint-disable @typescript-eslint/camelcase */ /* eslint-disable @typescript-eslint/camelcase */
const getResults = ( const getResults = (results: DDO[], page = 0, total_pages = 1, total_results = 1) => ({
results: DDO[], results,
page = 0, page,
total_pages = 1, total_pages,
total_results = 1 total_results
) => ({ results, page, total_pages, total_results }) })
/* eslint-enable @typescript-eslint/camelcase */ /* eslint-enable @typescript-eslint/camelcase */
beforeEach(async () => { beforeEach(async () => {
@ -48,9 +48,7 @@ describe('Aquarius', () => {
} as SearchQuery } as SearchQuery
it('should query metadata', async () => { it('should query metadata', async () => {
spy.on(ocean.utils.fetch, 'post', () => spy.on(ocean.utils.fetch, 'post', () => reponsify(getResults([new DDO()])))
reponsify(getResults([new DDO()]))
)
const result = await aquarius.queryMetadata(query) const result = await aquarius.queryMetadata(query)
assert.typeOf(result.results, 'array') assert.typeOf(result.results, 'array')
@ -61,9 +59,7 @@ describe('Aquarius', () => {
}) })
it('should query metadata and return real ddo', async () => { it('should query metadata and return real ddo', async () => {
spy.on(ocean.utils.fetch, 'post', () => spy.on(ocean.utils.fetch, 'post', () => reponsify(getResults([new DDO()])))
reponsify(getResults([new DDO()]))
)
const result = await aquarius.queryMetadata(query) const result = await aquarius.queryMetadata(query)
assert.typeOf(result.results, 'array') assert.typeOf(result.results, 'array')
@ -86,9 +82,7 @@ describe('Aquarius', () => {
} as SearchQuery } as SearchQuery
it('should query metadata by text', async () => { it('should query metadata by text', async () => {
spy.on(ocean.utils.fetch, 'get', () => spy.on(ocean.utils.fetch, 'get', () => reponsify(getResults([new DDO()])))
reponsify(getResults([new DDO()]))
)
const result = await aquarius.queryMetadataByText(query) const result = await aquarius.queryMetadataByText(query)
assert.typeOf(result.results, 'array') assert.typeOf(result.results, 'array')
@ -99,9 +93,7 @@ describe('Aquarius', () => {
}) })
it('should query metadata and return real ddo', async () => { it('should query metadata and return real ddo', async () => {
spy.on(ocean.utils.fetch, 'get', () => spy.on(ocean.utils.fetch, 'get', () => reponsify(getResults([new DDO()])))
reponsify(getResults([new DDO()]))
)
const result = await aquarius.queryMetadataByText(query) const result = await aquarius.queryMetadataByText(query)
assert.typeOf(result.results, 'array') assert.typeOf(result.results, 'array')

View File

@ -46,8 +46,7 @@ describe('DDO', () => {
}, },
{ {
type: 'CredentialRepositoryService', type: 'CredentialRepositoryService',
serviceEndpoint: serviceEndpoint: 'https://repository.example.com/service/8377464'
'https://repository.example.com/service/8377464'
}, },
{ {
type: 'XdiService', type: 'XdiService',
@ -55,8 +54,7 @@ describe('DDO', () => {
}, },
{ {
type: 'HubService', type: 'HubService',
serviceEndpoint: serviceEndpoint: 'https://hub.example.com/.identity/did:op:0123456789abcdef/'
'https://hub.example.com/.identity/did:op:0123456789abcdef/'
}, },
{ {
type: 'MessagingService', type: 'MessagingService',
@ -89,8 +87,7 @@ describe('DDO', () => {
{ {
type: 'metadata', type: 'metadata',
index: 0, index: 0,
serviceEndpoint: serviceEndpoint: 'http://myaquarius.org/api/v1/provider/assets/metadata/{did}',
'http://myaquarius.org/api/v1/provider/assets/metadata/{did}',
attributes: { attributes: {
main: { main: {
name: 'UK Weather information 2011', name: 'UK Weather information 2011',
@ -106,8 +103,7 @@ describe('DDO', () => {
checksum: 'efb2c764274b745f5fc37f97c6b0e761', checksum: 'efb2c764274b745f5fc37f97c6b0e761',
contentLength: 4535431, contentLength: 4535431,
contentType: 'application/json', contentType: 'application/json',
resourceId: resourceId: 'access-log2018-02-13-15-17-29-18386C502CAEA932'
'access-log2018-02-13-15-17-29-18386C502CAEA932'
}, },
{ {
index: 1, index: 1,
@ -128,11 +124,9 @@ describe('DDO', () => {
schema: 'Binary Voting' schema: 'Binary Voting'
}, },
additionalInformation: { additionalInformation: {
description: description: 'Weather information of UK including temperature and humidity',
'Weather information of UK including temperature and humidity',
copyrightHolder: 'Met Office', copyrightHolder: 'Met Office',
workExample: workExample: '423432fsd,51.509865,-0.118092,2011-01-01T10:55:11+00:00,7.2,68',
'423432fsd,51.509865,-0.118092,2011-01-01T10:55:11+00:00,7.2,68',
links: [ links: [
{ {
sample1: sample1:
@ -143,29 +137,20 @@ describe('DDO', () => {
'http://data.ceda.ac.uk/badc/ukcp09/data/gridded-land-obs/gridded-land-obs-averages-25km/' 'http://data.ceda.ac.uk/badc/ukcp09/data/gridded-land-obs/gridded-land-obs-averages-25km/'
}, },
{ {
fieldsDescription: fieldsDescription: 'http://data.ceda.ac.uk/badc/ukcp09/'
'http://data.ceda.ac.uk/badc/ukcp09/'
} }
], ],
inLanguage: 'en', inLanguage: 'en',
categories: ['Economy', 'Data Science'], categories: ['Economy', 'Data Science'],
tags: [ tags: ['weather', 'uk', '2011', 'temperature', 'humidity'],
'weather',
'uk',
'2011',
'temperature',
'humidity'
],
updateFrequency: 'yearly', updateFrequency: 'yearly',
structuredMarkup: [ structuredMarkup: [
{ {
uri: uri: 'http://skos.um.es/unescothes/C01194/jsonld',
'http://skos.um.es/unescothes/C01194/jsonld',
mediaType: 'application/ld+json' mediaType: 'application/ld+json'
}, },
{ {
uri: uri: 'http://skos.um.es/unescothes/C01194/turtle',
'http://skos.um.es/unescothes/C01194/turtle',
mediaType: 'text/turtle' mediaType: 'text/turtle'
} }
] ]
@ -234,10 +219,7 @@ describe('DDO', () => {
assert.instanceOf(ddo, DDO) assert.instanceOf(ddo, DDO)
assert.equal(ddo.id, testDDO.id) assert.equal(ddo.id, testDDO.id)
assert.equal( assert.equal(ddo.publicKey[0].publicKeyPem, testDDO.publicKey[0].publicKeyPem)
ddo.publicKey[0].publicKeyPem,
testDDO.publicKey[0].publicKeyPem
)
}) })
it('should properly deserialize from json file', async () => { it('should properly deserialize from json file', async () => {
@ -245,10 +227,7 @@ describe('DDO', () => {
assert(ddo) assert(ddo)
assert.equal(ddo.id, jsonDDO.id) assert.equal(ddo.id, jsonDDO.id)
assert.equal( assert.equal(ddo.publicKey[0].publicKeyPem, jsonDDO.publicKey[0].publicKeyPem)
ddo.publicKey[0].publicKeyPem,
jsonDDO.publicKey[0].publicKeyPem
)
}) })
}) })
@ -257,10 +236,7 @@ describe('DDO', () => {
const ddo = new DDO(testDDO) const ddo = new DDO(testDDO)
const checksum = ddo.getChecksum() const checksum = ddo.getChecksum()
assert.equal( assert.equal(checksum, '0x15f27a7a3c7b15d2b06dec7347c6b8da168adddd7df51a8ebbbe87b59b80049b')
checksum,
'0x15f27a7a3c7b15d2b06dec7347c6b8da168adddd7df51a8ebbbe87b59b80049b'
)
}) })
}) })
@ -269,11 +245,7 @@ describe('DDO', () => {
const signature = `0x${'a'.repeat(130)}` const signature = `0x${'a'.repeat(130)}`
it('should properly generate the proof', async () => { it('should properly generate the proof', async () => {
const signTextSpy = spy.on( const signTextSpy = spy.on(ocean.utils.signature, 'signText', () => signature)
ocean.utils.signature,
'signText',
() => signature
)
const ddo = new DDO(testDDO) const ddo = new DDO(testDDO)
const checksum = ddo.getChecksum() const checksum = ddo.getChecksum()
const proof = await ddo.generateProof(ocean, publicKey) const proof = await ddo.generateProof(ocean, publicKey)
@ -298,11 +270,7 @@ describe('DDO', () => {
signaturValue: 'test' signaturValue: 'test'
} as any } as any
const ddo = new DDO(testDDO) const ddo = new DDO(testDDO)
const generateProofSpy = spy.on( const generateProofSpy = spy.on(ddo, 'generateProof', () => fakeProof)
ddo,
'generateProof',
() => fakeProof
)
await ddo.addProof(web3, publicKey) await ddo.addProof(web3, publicKey)
assert.equal(ddo.proof, fakeProof) assert.equal(ddo.proof, fakeProof)

View File

@ -30,9 +30,7 @@ describe('ContractWrapperBase', () => {
}) })
it('should fail to call on an unknown contract function', done => { it('should fail to call on an unknown contract function', done => {
wrappedContract wrappedContract.sendMock('balanceOfxxx', '0x00', ['0x00']).catch(() => {
.sendMock('balanceOfxxx', '0x00', ['0x00'])
.catch(() => {
done() done()
}) })
}) })
@ -46,9 +44,7 @@ describe('ContractWrapperBase', () => {
describe('#send()', () => { describe('#send()', () => {
it('should fail to call on an unknown contract function', done => { it('should fail to call on an unknown contract function', done => {
wrappedContract wrappedContract.sendMock('transferxxx', accounts[0].getId(), []).catch(() => {
.sendMock('transferxxx', accounts[0].getId(), [])
.catch(() => {
done() done()
}) })
}) })

View File

@ -17,17 +17,12 @@ describe('ContractEvent', () => {
eventHandler = new EventHandler((ocean as any).instanceConfig) eventHandler = new EventHandler((ocean as any).instanceConfig)
account = (await ocean.accounts.list())[0].getId() account = (await ocean.accounts.list())[0].getId()
executeTransaction = () => executeTransaction = () => ocean.keeper.dispenser.requestTokens(10, account)
ocean.keeper.dispenser.requestTokens(10, account)
}) })
describe('#subscribe()', () => { describe('#subscribe()', () => {
it('should be able to listen to events', async () => { it('should be able to listen to events', async () => {
const event = eventHandler.getEvent( const event = eventHandler.getEvent(ocean.keeper.token, 'Transfer', { to: account })
ocean.keeper.token,
'Transfer',
{ to: account }
)
let validResolve = false let validResolve = false
let subscription: ContractEventSubscription let subscription: ContractEventSubscription
@ -57,11 +52,7 @@ describe('ContractEvent', () => {
describe('#once()', () => { describe('#once()', () => {
it('should listen to event only once', async () => { it('should listen to event only once', async () => {
const to = account const to = account
const event = eventHandler.getEvent( const event = eventHandler.getEvent(ocean.keeper.token, 'Transfer', { to })
ocean.keeper.token,
'Transfer',
{ to }
)
let canBeRejected = false let canBeRejected = false
const waitUntilEvent = new Promise((resolve, reject) => { const waitUntilEvent = new Promise((resolve, reject) => {
@ -85,11 +76,7 @@ describe('ContractEvent', () => {
it('should get the event like a promise', async () => { it('should get the event like a promise', async () => {
const to = account const to = account
const event = eventHandler.getEvent( const event = eventHandler.getEvent(ocean.keeper.token, 'Transfer', { to })
ocean.keeper.token,
'Transfer',
{ to }
)
const waitUntilEvent = event.once() const waitUntilEvent = event.once()

View File

@ -21,13 +21,7 @@ describe('DIDRegistry', () => {
const ownerAccount: Account = (await ocean.accounts.list())[0] const ownerAccount: Account = (await ocean.accounts.list())[0]
const did = generateId() const did = generateId()
const data = 'my nice provider, is nice' const data = 'my nice provider, is nice'
const receipt = await didRegistry.registerAttribute( const receipt = await didRegistry.registerAttribute(did, `0123456789abcdef`, [], data, ownerAccount.getId())
did,
`0123456789abcdef`,
[],
data,
ownerAccount.getId()
)
assert(receipt.status) assert(receipt.status)
assert(receipt.events.DIDAttributeRegistered) assert(receipt.events.DIDAttributeRegistered)
}) })
@ -38,13 +32,7 @@ describe('DIDRegistry', () => {
{ {
// register the first attribute // register the first attribute
const data = 'my nice provider, is nice' const data = 'my nice provider, is nice'
await didRegistry.registerAttribute( await didRegistry.registerAttribute(did, '0123456789abcdef', [], data, ownerAccount.getId())
did,
'0123456789abcdef',
[],
data,
ownerAccount.getId()
)
} }
{ {
// register the second attribute with the same did // register the second attribute with the same did
@ -67,21 +55,11 @@ describe('DIDRegistry', () => {
const ownerAccount: Account = (await ocean.accounts.list())[0] const ownerAccount: Account = (await ocean.accounts.list())[0]
const did = generateId() const did = generateId()
const data = 'my nice provider, is nice' const data = 'my nice provider, is nice'
await didRegistry.registerAttribute( await didRegistry.registerAttribute(did, '0123456789abcdef', [], data, ownerAccount.getId())
did,
'0123456789abcdef',
[],
data,
ownerAccount.getId()
)
const owner = await didRegistry.getDIDOwner(did) const owner = await didRegistry.getDIDOwner(did)
assert.equal( assert.equal(owner, ownerAccount.getId(), `Got ${owner} but expected ${ownerAccount.getId()}`)
owner,
ownerAccount.getId(),
`Got ${owner} but expected ${ownerAccount.getId()}`
)
}) })
it('should get 0x0 for a not registered did', async () => { it('should get 0x0 for a not registered did', async () => {

View File

@ -27,11 +27,7 @@ describe('EventHandler', () => {
assert.isDefined(subscription) assert.isDefined(subscription)
const countAfter = eventHandler.count const countAfter = eventHandler.count
assert.equal( assert.equal(countBefore + 1, countAfter, 'The event seems not added.')
countBefore + 1,
countAfter,
'The event seems not added.'
)
subscription.unsubscribe() subscription.unsubscribe()
}) })
@ -58,11 +54,7 @@ describe('EventHandler', () => {
eventHandler.unsubscribe(callback) eventHandler.unsubscribe(callback)
const countAfter = eventHandler.count const countAfter = eventHandler.count
assert.equal( assert.equal(countBefore, countAfter, 'The event seems not removed.')
countBefore,
countAfter,
'The event seems not removed.'
)
}) })
}) })

View File

@ -20,33 +20,23 @@ export default class TestContractHandler extends ContractHandler {
Logger.log('Trying to deploy contracts') Logger.log('Trying to deploy contracts')
// Libraries // Libraries
const epochLibrary = await TestContractHandler.deployContract( const epochLibrary = await TestContractHandler.deployContract('EpochLibrary', deployerAddress)
'EpochLibrary', const didRegistryLibrary = await TestContractHandler.deployContract('DIDRegistryLibrary', deployerAddress)
deployerAddress
)
const didRegistryLibrary = await TestContractHandler.deployContract(
'DIDRegistryLibrary',
deployerAddress
)
// Contracts // Contracts
const token = await TestContractHandler.deployContract( const token = await TestContractHandler.deployContract('OceanToken', deployerAddress, [
'OceanToken',
deployerAddress, deployerAddress,
[deployerAddress, deployerAddress] deployerAddress
) ])
const dispenser = await TestContractHandler.deployContract( const dispenser = await TestContractHandler.deployContract('Dispenser', deployerAddress, [
'Dispenser', token.options.address,
deployerAddress, deployerAddress
[token.options.address, deployerAddress] ])
)
// Add dispenser as Token minter // Add dispenser as Token minter
if (!token.$initialized) { if (!token.$initialized) {
await token.methods await token.methods.addMinter(dispenser.options.address).send({ from: deployerAddress })
.addMinter(dispenser.options.address)
.send({ from: deployerAddress })
} }
const didRegistry = await TestContractHandler.deployContract( const didRegistry = await TestContractHandler.deployContract(
@ -59,11 +49,9 @@ export default class TestContractHandler extends ContractHandler {
) )
// Managers // Managers
const templateStoreManager = await TestContractHandler.deployContract( const templateStoreManager = await TestContractHandler.deployContract('TemplateStoreManager', deployerAddress, [
'TemplateStoreManager', deployerAddress
deployerAddress, ])
[deployerAddress]
)
const conditionStoreManager = await TestContractHandler.deployContract( const conditionStoreManager = await TestContractHandler.deployContract(
'ConditionStoreManager', 'ConditionStoreManager',
deployerAddress, deployerAddress,
@ -84,49 +72,33 @@ export default class TestContractHandler extends ContractHandler {
) )
// Conditions // Conditions
const lockRewardCondition = await TestContractHandler.deployContract( const lockRewardCondition = await TestContractHandler.deployContract('LockRewardCondition', deployerAddress, [
'LockRewardCondition',
deployerAddress,
[
deployerAddress, deployerAddress,
conditionStoreManager.options.address, conditionStoreManager.options.address,
token.options.address token.options.address
] ])
)
const accessSecretStoreCondition = await TestContractHandler.deployContract( const accessSecretStoreCondition = await TestContractHandler.deployContract(
'AccessSecretStoreCondition', 'AccessSecretStoreCondition',
deployerAddress, deployerAddress,
[ [deployerAddress, conditionStoreManager.options.address, agreementStoreManager.options.address]
deployerAddress,
conditionStoreManager.options.address,
agreementStoreManager.options.address
]
) )
// Conditions rewards // Conditions rewards
const escrowReward = await TestContractHandler.deployContract( const escrowReward = await TestContractHandler.deployContract('EscrowReward', deployerAddress, [
'EscrowReward',
deployerAddress,
[
deployerAddress, deployerAddress,
conditionStoreManager.options.address, conditionStoreManager.options.address,
token.options.address token.options.address
] ])
)
// Templates // Templates
await TestContractHandler.deployContract( await TestContractHandler.deployContract('EscrowAccessSecretStoreTemplate', deployerAddress, [
'EscrowAccessSecretStoreTemplate',
deployerAddress,
[
deployerAddress, deployerAddress,
agreementStoreManager.options.address, agreementStoreManager.options.address,
didRegistry.options.address, didRegistry.options.address,
accessSecretStoreCondition.options.address, accessSecretStoreCondition.options.address,
lockRewardCondition.options.address, lockRewardCondition.options.address,
escrowReward.options.address escrowReward.options.address
] ])
)
} }
private static async deployContract( private static async deployContract(
@ -156,10 +128,7 @@ export default class TestContractHandler extends ContractHandler {
gasPrice: 10000000000 gasPrice: 10000000000
} }
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( const tempContract = new web3.eth.Contract(artifact.abi, artifact.address)
artifact.abi,
artifact.address
)
const isZos = !!tempContract.methods.initialize const isZos = !!tempContract.methods.initialize
Logger.debug({ Logger.debug({
@ -176,42 +145,27 @@ export default class TestContractHandler extends ContractHandler {
contractInstance = await tempContract contractInstance = await tempContract
.deploy({ .deploy({
data: TestContractHandler.replaceTokens( data: TestContractHandler.replaceTokens(artifact.bytecode.toString(), tokens),
artifact.bytecode.toString(),
tokens
),
arguments: isZos ? undefined : args arguments: isZos ? undefined : args
}) })
.send(sendConfig) .send(sendConfig)
if (isZos) { if (isZos) {
await contractInstance.methods await contractInstance.methods.initialize(...args).send(sendConfig)
.initialize(...args)
.send(sendConfig)
} }
contractInstance.testContract = true contractInstance.testContract = true
ContractHandler.setContract(name, where, contractInstance) ContractHandler.setContract(name, where, contractInstance)
// Logger.log("Deployed", name, "at", contractInstance.options.address); // Logger.log("Deployed", name, "at", contractInstance.options.address);
} catch (err) { } catch (err) {
Logger.error( Logger.error('Deployment failed for', name, 'with args', JSON.stringify(args, null, 2), err.message)
'Deployment failed for',
name,
'with args',
JSON.stringify(args, null, 2),
err.message
)
throw err throw err
} }
return contractInstance return contractInstance
} }
private static replaceTokens( private static replaceTokens(bytecode: string, tokens: { [name: string]: string }): string {
bytecode: string,
tokens: { [name: string]: string }
): string {
return Object.entries(tokens).reduce( return Object.entries(tokens).reduce(
(acc, [token, address]) => (acc, [token, address]) => acc.replace(new RegExp(`_+${token}_+`, 'g'), address.substr(2)),
acc.replace(new RegExp(`_+${token}_+`, 'g'), address.substr(2)),
bytecode bytecode
) )
} }

View File

@ -13,8 +13,7 @@ describe('AccessSecretStoreCondition', () => {
before(async () => { before(async () => {
await TestContractHandler.prepareContracts() await TestContractHandler.prepareContracts()
condition = (await Ocean.getInstance(config)).keeper.conditions condition = (await Ocean.getInstance(config)).keeper.conditions.accessSecretStoreCondition
.accessSecretStoreCondition
}) })
describe('#hashValues()', () => { describe('#hashValues()', () => {

View File

@ -21,27 +21,13 @@ describe('EscrowReward', () => {
await TestContractHandler.prepareContracts() await TestContractHandler.prepareContracts()
condition = keeper.conditions.escrowReward condition = keeper.conditions.escrowReward
lockCondition = await keeper.conditions.lockRewardCondition.generateIdHash( lockCondition = await keeper.conditions.lockRewardCondition.generateIdHash(agreementId, publisher, amount)
agreementId, releaseCondition = await keeper.conditions.accessSecretStoreCondition.generateIdHash(agreementId, did, consumer)
publisher,
amount
)
releaseCondition = await keeper.conditions.accessSecretStoreCondition.generateIdHash(
agreementId,
did,
consumer
)
}) })
describe('#hashValues()', () => { describe('#hashValues()', () => {
it('should hash the values', async () => { it('should hash the values', async () => {
const hash = await condition.hashValues( const hash = await condition.hashValues(amount, consumer, publisher, lockCondition, releaseCondition)
amount,
consumer,
publisher,
lockCondition,
releaseCondition
)
assert.match(hash, /^0x[a-f0-9]{64}$/i) assert.match(hash, /^0x[a-f0-9]{64}$/i)
}) })
@ -49,13 +35,7 @@ describe('EscrowReward', () => {
describe('#generateId()', () => { describe('#generateId()', () => {
it('should generate an ID', async () => { it('should generate an ID', async () => {
const hash = await condition.hashValues( const hash = await condition.hashValues(amount, consumer, publisher, lockCondition, releaseCondition)
amount,
consumer,
publisher,
lockCondition,
releaseCondition
)
const id = await condition.generateId(agreementId, hash) const id = await condition.generateId(agreementId, hash)
assert.match(id, /^0x[a-f0-9]{64}$/i) assert.match(id, /^0x[a-f0-9]{64}$/i)

View File

@ -13,8 +13,7 @@ describe('LockRewardCondition', () => {
before(async () => { before(async () => {
await TestContractHandler.prepareContracts() await TestContractHandler.prepareContracts()
condition = (await Ocean.getInstance(config)).keeper.conditions condition = (await Ocean.getInstance(config)).keeper.conditions.lockRewardCondition
.lockRewardCondition
}) })
describe('#hashValues()', () => { describe('#hashValues()', () => {

View File

@ -15,9 +15,7 @@ export default class WebServiceConnectorMock extends WebServiceConnector {
return this.returnData ? this.returnData : {} return this.returnData ? this.returnData : {}
}, },
text: () => { text: () => {
return this.returnData return this.returnData ? JSON.stringify(this.returnData.toString()) : ''
? JSON.stringify(this.returnData.toString())
: ''
} }
}) })
}) })

View File

@ -39,10 +39,7 @@ describe('Account', () => {
const balance = await account.getEtherBalance() const balance = await account.getEtherBalance()
const web3 = Web3Provider.getWeb3() const web3 = Web3Provider.getWeb3()
assert( assert(Number(web3.utils.toWei('100', 'ether')) === balance, `ether did not match ${balance}`)
Number(web3.utils.toWei('100', 'ether')) === balance,
`ether did not match ${balance}`
)
}) })
}) })
@ -52,10 +49,7 @@ describe('Account', () => {
const balance = await account.getBalance() const balance = await account.getBalance()
const web3 = Web3Provider.getWeb3() const web3 = Web3Provider.getWeb3()
assert( assert(Number(web3.utils.toWei('100', 'ether')) === balance.eth, `ether did not match ${balance.eth}`)
Number(web3.utils.toWei('100', 'ether')) === balance.eth,
`ether did not match ${balance.eth}`
)
assert(balance.ocn === 0, `tokens did not match ${balance.ocn}`) assert(balance.ocn === 0, `tokens did not match ${balance.ocn}`)
}) })
}) })

View File

@ -54,11 +54,7 @@ describe('OceanAuth', () => {
describe('#store()', () => { describe('#store()', () => {
it('should sign and store the token', async () => { it('should sign and store the token', async () => {
const writeTokenSpy = spy.on( const writeTokenSpy = spy.on(oceanAuth as any, 'writeToken', () => {})
oceanAuth as any,
'writeToken',
() => {}
)
await oceanAuth.store(account) await oceanAuth.store(account)

View File

@ -27,17 +27,9 @@ describe('OceanSecretStore', () => {
describe('#encrypt()', () => { describe('#encrypt()', () => {
it('should encrypt a content', async () => { it('should encrypt a content', async () => {
const secretStoreEncryptSpy = spy.on( const secretStoreEncryptSpy = spy.on(ocean.brizo, 'encrypt', () => 'encryptedResult')
ocean.brizo,
'encrypt',
() => 'encryptedResult'
)
const result = await oceanSecretStore.encrypt( const result = await oceanSecretStore.encrypt(did, 'test', accounts[0])
did,
'test',
accounts[0]
)
expect(secretStoreEncryptSpy).to.have.been.called.with(did, 'test') expect(secretStoreEncryptSpy).to.have.been.called.with(did, 'test')

View File

@ -38,33 +38,18 @@ describe('SignatureUtils', () => {
}) })
it('should sign a text as expected using password', async () => { it('should sign a text as expected using password', async () => {
const signed = await ocean.utils.signature.signText( const signed = await ocean.utils.signature.signText(text, publicKey, 'test')
text,
publicKey,
'test'
)
assert.equal(signed, signature) assert.equal(signed, signature)
expect(personalSignSpy).to.have.been.called.with( expect(personalSignSpy).to.have.been.called.with(text, publicKey, 'test')
text,
publicKey,
'test'
)
}) })
}) })
describe('#verifyText', () => { describe('#verifyText', () => {
it('should recover the privateKey of a signed message', async () => { it('should recover the privateKey of a signed message', async () => {
const personalRecoverSpy = spy.on( const personalRecoverSpy = spy.on(web3.eth.personal, 'ecRecover', () => publicKey)
web3.eth.personal,
'ecRecover',
() => publicKey
)
const verifiedPublicKey = await ocean.utils.signature.verifyText( const verifiedPublicKey = await ocean.utils.signature.verifyText(text, signature)
text,
signature
)
assert.equal(publicKey, verifiedPublicKey) assert.equal(publicKey, verifiedPublicKey)
expect(personalRecoverSpy).to.have.been.called.with(text, signature) expect(personalRecoverSpy).to.have.been.called.with(text, signature)

View File

@ -1,10 +1,5 @@
import { assert } from 'chai' import { assert } from 'chai'
import { import { zeroX, noZeroX, didPrefixed, noDidPrefixed } from '../../src/utils/ConversionTypeHelpers'
zeroX,
noZeroX,
didPrefixed,
noDidPrefixed
} from '../../src/utils/ConversionTypeHelpers'
describe('ConversionTypeHelpers', () => { describe('ConversionTypeHelpers', () => {
describe('#zeroXTransformer()', () => { describe('#zeroXTransformer()', () => {