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:
parent
13e43d7b40
commit
3d7d1f3972
@ -1,5 +1,6 @@
|
||||
{
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"printWidth": 120,
|
||||
"trailingComma": "none"
|
||||
}
|
||||
|
@ -44,12 +44,7 @@ if (process.env.SEED_WORDS) {
|
||||
const seedphrase = process.env.SEED_WORDS
|
||||
|
||||
// @ts-ignore
|
||||
configJson.web3Provider = new HDWalletProvider(
|
||||
seedphrase,
|
||||
configJson.nodeUri,
|
||||
0,
|
||||
5
|
||||
)
|
||||
configJson.web3Provider = new HDWalletProvider(seedphrase, configJson.nodeUri, 0, 5)
|
||||
}
|
||||
|
||||
export const config: Config & { forceVerbose: Config } = configJson as any
|
||||
|
@ -32,49 +32,35 @@ describe('Asset Owners', () => {
|
||||
it('should set the provider of an asset', async () => {
|
||||
const ddo = await ocean.assets.create(metadata as any, account1)
|
||||
|
||||
const isProvider = await ocean.keeper.didRegistry.isDIDProvider(
|
||||
ddo.id,
|
||||
config.brizoAddress
|
||||
)
|
||||
const isProvider = await ocean.keeper.didRegistry.isDIDProvider(ddo.id, config.brizoAddress)
|
||||
|
||||
assert.isTrue(isProvider)
|
||||
})
|
||||
|
||||
it('should get the assets owned by a user', async () => {
|
||||
const { length: initialLength } = await ocean.assets.ownerAssets(
|
||||
account2.getId()
|
||||
)
|
||||
const { length: initialLength } = await ocean.assets.ownerAssets(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, account2)
|
||||
|
||||
const { length: finalLength } = await ocean.assets.ownerAssets(
|
||||
account2.getId()
|
||||
)
|
||||
const { length: finalLength } = await ocean.assets.ownerAssets(account2.getId())
|
||||
|
||||
assert.equal(finalLength - initialLength, 1)
|
||||
})
|
||||
|
||||
it('should get the assets that can be consumed by a user', async () => {
|
||||
const { length: initialLength } = await ocean.assets.consumerAssets(
|
||||
account2.getId()
|
||||
)
|
||||
const { length: initialLength } = await ocean.assets.consumerAssets(account2.getId())
|
||||
|
||||
const ddo = await ocean.assets.create(metadata as any, account1)
|
||||
|
||||
const { length: finalLength1 } = await ocean.assets.consumerAssets(
|
||||
account2.getId()
|
||||
)
|
||||
const { length: finalLength1 } = await ocean.assets.consumerAssets(account2.getId())
|
||||
assert.equal(finalLength1 - initialLength, 0)
|
||||
|
||||
// Granting access
|
||||
try {
|
||||
await account2.requestTokens(
|
||||
+metadata.main.price *
|
||||
10 ** -(await ocean.keeper.token.decimals())
|
||||
)
|
||||
await account2.requestTokens(+metadata.main.price * 10 ** -(await ocean.keeper.token.decimals()))
|
||||
} catch {}
|
||||
|
||||
const { index } = ddo.findServiceByType('access')
|
||||
@ -82,9 +68,7 @@ describe('Asset Owners', () => {
|
||||
await ocean.assets.order(ddo.id, index, account2)
|
||||
// Access granted
|
||||
|
||||
const { length: finalLength2 } = await ocean.assets.consumerAssets(
|
||||
account2.getId()
|
||||
)
|
||||
const { length: finalLength2 } = await ocean.assets.consumerAssets(account2.getId())
|
||||
assert.equal(finalLength2 - initialLength, 1)
|
||||
})
|
||||
})
|
||||
|
@ -36,53 +36,29 @@ describe('Consume Asset', () => {
|
||||
|
||||
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.isAtLeast(
|
||||
ddo.authentication.length,
|
||||
1,
|
||||
'Default authentication not added'
|
||||
)
|
||||
assert.isDefined(
|
||||
ddo.findServiceByType('access'),
|
||||
"DDO access service doesn't exist"
|
||||
)
|
||||
assert.isAtLeast(ddo.authentication.length, 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 () => {
|
||||
const initialBalance = (await consumer.getBalance()).ocn
|
||||
const claimedTokens =
|
||||
+metadata.main.price * 10 ** -(await ocean.keeper.token.decimals())
|
||||
const claimedTokens = +metadata.main.price * 10 ** -(await ocean.keeper.token.decimals())
|
||||
|
||||
try {
|
||||
await consumer.requestTokens(claimedTokens)
|
||||
} catch {}
|
||||
|
||||
assert.equal(
|
||||
(await consumer.getBalance()).ocn,
|
||||
initialBalance + claimedTokens,
|
||||
'OCN Tokens not delivered'
|
||||
)
|
||||
assert.equal((await consumer.getBalance()).ocn, initialBalance + claimedTokens, 'OCN Tokens not delivered')
|
||||
})
|
||||
|
||||
it('should sign the service agreement', async () => {
|
||||
const accessService = ddo.findServiceByType('access')
|
||||
|
||||
serviceAgreementSignatureResult = await ocean.agreements.prepare(
|
||||
ddo.id,
|
||||
accessService.index,
|
||||
consumer
|
||||
)
|
||||
serviceAgreementSignatureResult = await ocean.agreements.prepare(ddo.id, accessService.index, consumer)
|
||||
|
||||
const { agreementId, signature } = serviceAgreementSignatureResult
|
||||
assert.match(
|
||||
agreementId,
|
||||
/^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'
|
||||
)
|
||||
assert.match(agreementId, /^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 () => {
|
||||
@ -101,9 +77,7 @@ describe('Consume Asset', () => {
|
||||
})
|
||||
|
||||
it('should get the agreement conditions status not fulfilled', async () => {
|
||||
const status = await ocean.agreements.status(
|
||||
serviceAgreementSignatureResult.agreementId
|
||||
)
|
||||
const status = await ocean.agreements.status(serviceAgreementSignatureResult.agreementId)
|
||||
|
||||
assert.deepEqual(status, {
|
||||
lockReward: ConditionState.Unfulfilled,
|
||||
@ -144,9 +118,7 @@ describe('Consume Asset', () => {
|
||||
})
|
||||
|
||||
it('should get the agreement conditions status fulfilled', async () => {
|
||||
const status = await ocean.agreements.status(
|
||||
serviceAgreementSignatureResult.agreementId
|
||||
)
|
||||
const status = await ocean.agreements.status(serviceAgreementSignatureResult.agreementId)
|
||||
|
||||
assert.deepEqual(status, {
|
||||
lockReward: ConditionState.Fulfilled,
|
||||
@ -175,11 +147,7 @@ describe('Consume Asset', () => {
|
||||
})
|
||||
})
|
||||
|
||||
assert.deepEqual(
|
||||
files,
|
||||
['README.md', 'package.json'],
|
||||
'Stored files are not correct.'
|
||||
)
|
||||
assert.deepEqual(files, ['README.md', 'package.json'], 'Stored files are not correct.')
|
||||
})
|
||||
|
||||
it('should consume and store one asset', async () => {
|
||||
|
@ -41,9 +41,7 @@ describe('Consume Asset (Brizo)', () => {
|
||||
|
||||
it('should regiester an asset', async () => {
|
||||
const steps = []
|
||||
ddo = await ocean.assets
|
||||
.create(metadata as any, publisher)
|
||||
.next(step => steps.push(step))
|
||||
ddo = await ocean.assets.create(metadata as any, publisher).next(step => steps.push(step))
|
||||
|
||||
assert.instanceOf(ddo, DDO)
|
||||
assert.deepEqual(steps, [0, 1, 2, 3, 4, 5, 6, 7])
|
||||
@ -53,16 +51,11 @@ describe('Consume Asset (Brizo)', () => {
|
||||
const accessService = ddo.findServiceByType('access')
|
||||
|
||||
try {
|
||||
await consumer.requestTokens(
|
||||
+metadata.main.price *
|
||||
10 ** -(await ocean.keeper.token.decimals())
|
||||
)
|
||||
await consumer.requestTokens(+metadata.main.price * 10 ** -(await ocean.keeper.token.decimals()))
|
||||
} catch {}
|
||||
|
||||
const steps = []
|
||||
agreementId = await ocean.assets
|
||||
.order(ddo.id, accessService.index, consumer)
|
||||
.next(step => steps.push(step))
|
||||
agreementId = await ocean.assets.order(ddo.id, accessService.index, consumer).next(step => steps.push(step))
|
||||
|
||||
assert.isDefined(agreementId)
|
||||
assert.deepEqual(steps, [0, 1, 2, 3])
|
||||
@ -72,13 +65,7 @@ describe('Consume Asset (Brizo)', () => {
|
||||
const accessService = ddo.findServiceByType('access')
|
||||
|
||||
const folder = '/tmp/ocean/squid-js'
|
||||
const path = await ocean.assets.consume(
|
||||
agreementId,
|
||||
ddo.id,
|
||||
accessService.index,
|
||||
consumer,
|
||||
folder
|
||||
)
|
||||
const path = await ocean.assets.consume(agreementId, ddo.id, accessService.index, consumer, folder)
|
||||
|
||||
assert.include(path, folder, 'The storage path is not correct.')
|
||||
|
||||
@ -88,10 +75,6 @@ describe('Consume Asset (Brizo)', () => {
|
||||
})
|
||||
})
|
||||
|
||||
assert.deepEqual(
|
||||
files,
|
||||
['README.md', 'package.json'],
|
||||
'Stored files are not correct.'
|
||||
)
|
||||
assert.deepEqual(files, ['README.md', 'package.json'], 'Stored files are not correct.')
|
||||
})
|
||||
})
|
||||
|
@ -51,17 +51,10 @@ xdescribe('Consume Asset (Large size)', () => {
|
||||
const accessService = ddo.findServiceByType('access')
|
||||
|
||||
try {
|
||||
await consumer.requestTokens(
|
||||
+metadata.main.price *
|
||||
10 ** -(await ocean.keeper.token.decimals())
|
||||
)
|
||||
await consumer.requestTokens(+metadata.main.price * 10 ** -(await ocean.keeper.token.decimals()))
|
||||
} catch {}
|
||||
|
||||
agreementId = await ocean.assets.order(
|
||||
ddo.id,
|
||||
accessService.index,
|
||||
consumer
|
||||
)
|
||||
agreementId = await ocean.assets.order(ddo.id, accessService.index, consumer)
|
||||
|
||||
assert.isDefined(agreementId)
|
||||
})
|
||||
@ -70,13 +63,7 @@ xdescribe('Consume Asset (Large size)', () => {
|
||||
const accessService = ddo.findServiceByType('access')
|
||||
|
||||
const folder = '/tmp/ocean/squid-js'
|
||||
const path = await ocean.assets.consume(
|
||||
agreementId,
|
||||
ddo.id,
|
||||
accessService.index,
|
||||
consumer,
|
||||
folder
|
||||
)
|
||||
const path = await ocean.assets.consume(agreementId, ddo.id, accessService.index, consumer, folder)
|
||||
|
||||
assert.include(path, folder, 'The storage path is not correct.')
|
||||
|
||||
|
@ -4,11 +4,7 @@ import { config } from '../config'
|
||||
|
||||
import { Ocean, templates, conditions, utils, Account, Keeper } from '../../src' // @oceanprotocol/squid
|
||||
|
||||
const {
|
||||
LockRewardCondition,
|
||||
EscrowReward,
|
||||
AccessSecretStoreCondition
|
||||
} = conditions
|
||||
const { LockRewardCondition, EscrowReward, AccessSecretStoreCondition } = conditions
|
||||
|
||||
describe('Register Escrow Access Secret Store Template', () => {
|
||||
let ocean: Ocean
|
||||
@ -40,8 +36,7 @@ describe('Register Escrow Access Secret Store Template', () => {
|
||||
consumer = (await ocean.accounts.list())[2]
|
||||
|
||||
// Conditions
|
||||
accessSecretStoreCondition =
|
||||
keeper.conditions.accessSecretStoreCondition
|
||||
accessSecretStoreCondition = keeper.conditions.accessSecretStoreCondition
|
||||
lockRewardCondition = keeper.conditions.lockRewardCondition
|
||||
escrowReward = keeper.conditions.escrowReward
|
||||
|
||||
@ -52,21 +47,13 @@ describe('Register Escrow Access Secret Store Template', () => {
|
||||
|
||||
describe('Propose and approve template', () => {
|
||||
it('should propose the template', async () => {
|
||||
await keeper.templateStoreManager.proposeTemplate(
|
||||
template.getAddress(),
|
||||
consumer.getId(),
|
||||
true
|
||||
)
|
||||
await keeper.templateStoreManager.proposeTemplate(template.getAddress(), consumer.getId(), true)
|
||||
// TODO: Use a event to detect template mined
|
||||
await new Promise(resolve => setTimeout(resolve, 2 * 1000))
|
||||
})
|
||||
|
||||
it('should approve the template', async () => {
|
||||
await keeper.templateStoreManager.approveTemplate(
|
||||
template.getAddress(),
|
||||
templateManagerOwner.getId(),
|
||||
true
|
||||
)
|
||||
await keeper.templateStoreManager.approveTemplate(template.getAddress(), templateManagerOwner.getId(), true)
|
||||
// TODO: Use a event to detect template mined
|
||||
await new Promise(resolve => setTimeout(resolve, 2 * 1000))
|
||||
})
|
||||
@ -81,21 +68,11 @@ describe('Register Escrow Access Secret Store Template', () => {
|
||||
let conditionIdEscrow: string
|
||||
|
||||
it('should register a DID', async () => {
|
||||
await keeper.didRegistry.registerAttribute(
|
||||
did,
|
||||
checksum,
|
||||
[],
|
||||
url,
|
||||
publisher.getId()
|
||||
)
|
||||
await keeper.didRegistry.registerAttribute(did, checksum, [], url, publisher.getId())
|
||||
})
|
||||
|
||||
it('should generate the condition IDs', async () => {
|
||||
conditionIdAccess = await accessSecretStoreCondition.generateIdHash(
|
||||
agreementId,
|
||||
did,
|
||||
consumer.getId()
|
||||
)
|
||||
conditionIdAccess = await accessSecretStoreCondition.generateIdHash(agreementId, did, consumer.getId())
|
||||
conditionIdLock = await lockRewardCondition.generateIdHash(
|
||||
agreementId,
|
||||
await escrowReward.getAddress(),
|
||||
@ -131,20 +108,10 @@ describe('Register Escrow Access Secret Store Template', () => {
|
||||
|
||||
assert.equal(conditionInstances.length, 3, 'Expected 3 conditions.')
|
||||
|
||||
const conditionClasses = [
|
||||
AccessSecretStoreCondition,
|
||||
EscrowReward,
|
||||
LockRewardCondition
|
||||
]
|
||||
const conditionClasses = [AccessSecretStoreCondition, EscrowReward, LockRewardCondition]
|
||||
conditionClasses.forEach(conditionClass => {
|
||||
if (
|
||||
!conditionInstances.find(
|
||||
condition => condition instanceof conditionClass
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
`${conditionClass.name} is not part of the conditions.`
|
||||
)
|
||||
if (!conditionInstances.find(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 () => {
|
||||
const accessGranted = await accessSecretStoreCondition.checkPermissions(
|
||||
consumer.getId(),
|
||||
did
|
||||
)
|
||||
const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
|
||||
|
||||
assert.isFalse(accessGranted, 'Consumer has been granted.')
|
||||
})
|
||||
@ -177,11 +141,7 @@ describe('Register Escrow Access Secret Store Template', () => {
|
||||
await consumer.requestTokens(escrowAmount)
|
||||
} catch {}
|
||||
|
||||
await keeper.token.approve(
|
||||
lockRewardCondition.getAddress(),
|
||||
escrowAmount,
|
||||
consumer.getId()
|
||||
)
|
||||
await keeper.token.approve(lockRewardCondition.getAddress(), escrowAmount, consumer.getId())
|
||||
|
||||
const fulfill = await lockRewardCondition.fulfill(
|
||||
agreementId,
|
||||
@ -219,10 +179,7 @@ describe('Register Escrow Access Secret Store Template', () => {
|
||||
})
|
||||
|
||||
it('should grant the access to the consumer', async () => {
|
||||
const accessGranted = await accessSecretStoreCondition.checkPermissions(
|
||||
consumer.getId(),
|
||||
did
|
||||
)
|
||||
const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
|
||||
|
||||
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 () => {
|
||||
// This part is executed inside Ocean.assets.create()
|
||||
await keeper.didRegistry.registerAttribute(
|
||||
did,
|
||||
checksum,
|
||||
[],
|
||||
url,
|
||||
publisher.getId()
|
||||
)
|
||||
await keeper.didRegistry.registerAttribute(did, checksum, [], url, publisher.getId())
|
||||
})
|
||||
|
||||
it('should create a new agreement (short way)', async () => {
|
||||
agreementId = await template.createFullAgreement(
|
||||
did,
|
||||
escrowAmount,
|
||||
consumer.getId(),
|
||||
publisher.getId()
|
||||
)
|
||||
agreementId = await template.createFullAgreement(did, escrowAmount, consumer.getId(), publisher.getId())
|
||||
|
||||
assert.match(agreementId, /^0x[a-f0-9]{64}$/i)
|
||||
})
|
||||
|
||||
it('should not grant the access to the consumer', async () => {
|
||||
const accessGranted = await accessSecretStoreCondition.checkPermissions(
|
||||
consumer.getId(),
|
||||
did
|
||||
)
|
||||
const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
|
||||
|
||||
assert.isFalse(accessGranted, 'Consumer has been granted.')
|
||||
})
|
||||
@ -269,20 +212,11 @@ describe('Register Escrow Access Secret Store Template', () => {
|
||||
await consumer.requestTokens(escrowAmount)
|
||||
} catch {}
|
||||
|
||||
await ocean.agreements.conditions.lockReward(
|
||||
agreementId,
|
||||
escrowAmount,
|
||||
consumer
|
||||
)
|
||||
await ocean.agreements.conditions.lockReward(agreementId, escrowAmount, consumer)
|
||||
})
|
||||
|
||||
it('should fulfill the conditions from publisher side', async () => {
|
||||
await ocean.agreements.conditions.grantAccess(
|
||||
agreementId,
|
||||
did,
|
||||
consumer.getId(),
|
||||
publisher
|
||||
)
|
||||
await ocean.agreements.conditions.grantAccess(agreementId, did, consumer.getId(), publisher)
|
||||
await ocean.agreements.conditions.releaseReward(
|
||||
agreementId,
|
||||
escrowAmount,
|
||||
@ -294,10 +228,7 @@ describe('Register Escrow Access Secret Store Template', () => {
|
||||
})
|
||||
|
||||
it('should grant the access to the consumer', async () => {
|
||||
const accessGranted = await accessSecretStoreCondition.checkPermissions(
|
||||
consumer.getId(),
|
||||
did
|
||||
)
|
||||
const accessGranted = await accessSecretStoreCondition.checkPermissions(consumer.getId(), did)
|
||||
|
||||
assert.isTrue(accessGranted, 'Consumer has not been granted.')
|
||||
})
|
||||
|
@ -4,11 +4,7 @@ import { config } from '../config'
|
||||
|
||||
import { Ocean, templates, conditions, utils, Account, Keeper } from '../../src' // @oceanprotocol/squid
|
||||
|
||||
const {
|
||||
LockRewardCondition,
|
||||
EscrowReward,
|
||||
ComputeExecutionCondition
|
||||
} = conditions
|
||||
const { LockRewardCondition, EscrowReward, ComputeExecutionCondition } = conditions
|
||||
|
||||
describe('Register Escrow Compute Execution Template', () => {
|
||||
let ocean: Ocean
|
||||
@ -51,21 +47,13 @@ describe('Register Escrow Compute Execution Template', () => {
|
||||
|
||||
describe('Propose and approve template', () => {
|
||||
it('should propose the template', async () => {
|
||||
await keeper.templateStoreManager.proposeTemplate(
|
||||
template.getAddress(),
|
||||
consumer.getId(),
|
||||
true
|
||||
)
|
||||
await keeper.templateStoreManager.proposeTemplate(template.getAddress(), consumer.getId(), true)
|
||||
// TODO: Use a event to detect template mined
|
||||
await new Promise(resolve => setTimeout(resolve, 2 * 1000))
|
||||
})
|
||||
|
||||
it('should approve the template', async () => {
|
||||
await keeper.templateStoreManager.approveTemplate(
|
||||
template.getAddress(),
|
||||
templateManagerOwner.getId(),
|
||||
true
|
||||
)
|
||||
await keeper.templateStoreManager.approveTemplate(template.getAddress(), templateManagerOwner.getId(), true)
|
||||
// TODO: Use a event to detect template mined
|
||||
await new Promise(resolve => setTimeout(resolve, 2 * 1000))
|
||||
})
|
||||
@ -80,21 +68,11 @@ describe('Register Escrow Compute Execution Template', () => {
|
||||
let conditionIdEscrow: string
|
||||
|
||||
it('should register a DID', async () => {
|
||||
await keeper.didRegistry.registerAttribute(
|
||||
did,
|
||||
checksum,
|
||||
[],
|
||||
url,
|
||||
publisher.getId()
|
||||
)
|
||||
await keeper.didRegistry.registerAttribute(did, checksum, [], url, publisher.getId())
|
||||
})
|
||||
|
||||
it('should generate the condition IDs', async () => {
|
||||
conditionIdCompute = await computeExecutionCondition.generateIdHash(
|
||||
agreementId,
|
||||
did,
|
||||
consumer.getId()
|
||||
)
|
||||
conditionIdCompute = await computeExecutionCondition.generateIdHash(agreementId, did, consumer.getId())
|
||||
conditionIdLock = await lockRewardCondition.generateIdHash(
|
||||
agreementId,
|
||||
await escrowReward.getAddress(),
|
||||
@ -130,20 +108,10 @@ describe('Register Escrow Compute Execution Template', () => {
|
||||
|
||||
assert.equal(conditionInstances.length, 3, 'Expected 3 conditions.')
|
||||
|
||||
const conditionClasses = [
|
||||
ComputeExecutionCondition,
|
||||
EscrowReward,
|
||||
LockRewardCondition
|
||||
]
|
||||
const conditionClasses = [ComputeExecutionCondition, EscrowReward, LockRewardCondition]
|
||||
conditionClasses.forEach(conditionClass => {
|
||||
if (
|
||||
!conditionInstances.find(
|
||||
condition => condition instanceof conditionClass
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
`${conditionClass.name} is not part of the conditions.`
|
||||
)
|
||||
if (!conditionInstances.find(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 () => {
|
||||
const computeTriggered = await computeExecutionCondition.wasComputeTriggered(
|
||||
did,
|
||||
consumer.getId()
|
||||
)
|
||||
const computeTriggered = await computeExecutionCondition.wasComputeTriggered(did, consumer.getId())
|
||||
|
||||
assert.isFalse(computeTriggered, 'Compute has been triggered.')
|
||||
})
|
||||
@ -176,11 +141,7 @@ describe('Register Escrow Compute Execution Template', () => {
|
||||
await consumer.requestTokens(escrowAmount)
|
||||
} catch {}
|
||||
|
||||
await keeper.token.approve(
|
||||
lockRewardCondition.getAddress(),
|
||||
escrowAmount,
|
||||
consumer.getId()
|
||||
)
|
||||
await keeper.token.approve(lockRewardCondition.getAddress(), escrowAmount, consumer.getId())
|
||||
|
||||
const fulfill = await lockRewardCondition.fulfill(
|
||||
agreementId,
|
||||
@ -218,10 +179,7 @@ describe('Register Escrow Compute Execution Template', () => {
|
||||
})
|
||||
|
||||
it('should grant the access to the consumer', async () => {
|
||||
const computeTriggered = await computeExecutionCondition.wasComputeTriggered(
|
||||
did,
|
||||
consumer.getId()
|
||||
)
|
||||
const computeTriggered = await computeExecutionCondition.wasComputeTriggered(did, consumer.getId())
|
||||
|
||||
assert.isTrue(computeTriggered, 'Compute has not been triggered.')
|
||||
})
|
||||
@ -234,31 +192,17 @@ describe('Register Escrow Compute Execution Template', () => {
|
||||
|
||||
it('should register a DID', async () => {
|
||||
// This part is executed inside Ocean.assets.create()
|
||||
await keeper.didRegistry.registerAttribute(
|
||||
did,
|
||||
checksum,
|
||||
[],
|
||||
url,
|
||||
publisher.getId()
|
||||
)
|
||||
await keeper.didRegistry.registerAttribute(did, checksum, [], url, publisher.getId())
|
||||
})
|
||||
|
||||
it('should create a new agreement (short way)', async () => {
|
||||
agreementId = await template.createFullAgreement(
|
||||
did,
|
||||
escrowAmount,
|
||||
consumer.getId(),
|
||||
publisher.getId()
|
||||
)
|
||||
agreementId = await template.createFullAgreement(did, escrowAmount, consumer.getId(), publisher.getId())
|
||||
|
||||
assert.match(agreementId, /^0x[a-f0-9]{64}$/i)
|
||||
})
|
||||
|
||||
it('should not grant the access to the consumer', async () => {
|
||||
const computeTriggered = await computeExecutionCondition.wasComputeTriggered(
|
||||
did,
|
||||
consumer.getId()
|
||||
)
|
||||
const computeTriggered = await computeExecutionCondition.wasComputeTriggered(did, consumer.getId())
|
||||
|
||||
assert.isFalse(computeTriggered, 'Compute has been triggered.')
|
||||
})
|
||||
@ -268,20 +212,11 @@ describe('Register Escrow Compute Execution Template', () => {
|
||||
await consumer.requestTokens(escrowAmount)
|
||||
} catch {}
|
||||
|
||||
await ocean.agreements.conditions.lockReward(
|
||||
agreementId,
|
||||
escrowAmount,
|
||||
consumer
|
||||
)
|
||||
await ocean.agreements.conditions.lockReward(agreementId, escrowAmount, consumer)
|
||||
})
|
||||
|
||||
it('should fulfill the conditions from computing side', async () => {
|
||||
await ocean.agreements.conditions.grantServiceExecution(
|
||||
agreementId,
|
||||
did,
|
||||
consumer.getId(),
|
||||
publisher
|
||||
)
|
||||
await ocean.agreements.conditions.grantServiceExecution(agreementId, did, consumer.getId(), publisher)
|
||||
await ocean.agreements.conditions.releaseReward(
|
||||
agreementId,
|
||||
escrowAmount,
|
||||
@ -293,10 +228,7 @@ describe('Register Escrow Compute Execution Template', () => {
|
||||
})
|
||||
|
||||
it('should grant the access to the consumer', async () => {
|
||||
const computeTriggered = await computeExecutionCondition.wasComputeTriggered(
|
||||
did,
|
||||
consumer.getId()
|
||||
)
|
||||
const computeTriggered = await computeExecutionCondition.wasComputeTriggered(did, consumer.getId())
|
||||
|
||||
assert.isTrue(computeTriggered, 'Compute has not been triggered.')
|
||||
})
|
||||
|
@ -15,8 +15,7 @@ describe('Search Asset', () => {
|
||||
.toString(36)
|
||||
.substr(2)
|
||||
let price
|
||||
const metadataGenerator = (name: string) =>
|
||||
generateMetadata(`${name}${testHash}`, price)
|
||||
const metadataGenerator = (name: string) => generateMetadata(`${name}${testHash}`, price)
|
||||
|
||||
let test1length
|
||||
let test2length
|
||||
@ -35,10 +34,8 @@ describe('Search Asset', () => {
|
||||
assert.isArray(ddos, 'A search should return an array')
|
||||
|
||||
test1length = ddos.length
|
||||
test2length = (await ocean.assets.search(`Test2${testHash}`)).results
|
||||
.length
|
||||
test3length = (await ocean.assets.search(`Test3${testHash}`)).results
|
||||
.length
|
||||
test2length = (await ocean.assets.search(`Test2${testHash}`)).results.length
|
||||
test3length = (await ocean.assets.search(`Test3${testHash}`)).results.length
|
||||
|
||||
if (!ocean.keeper.dispenser) {
|
||||
price = 0
|
||||
@ -46,46 +43,20 @@ describe('Search Asset', () => {
|
||||
})
|
||||
|
||||
it('should register an asset', async () => {
|
||||
assert.instanceOf(
|
||||
await ocean.assets.create(
|
||||
metadataGenerator('Test1') as any,
|
||||
publisher
|
||||
),
|
||||
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
|
||||
)
|
||||
assert.instanceOf(await ocean.assets.create(metadataGenerator('Test1') as any, publisher), 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 () => {
|
||||
assert.equal(
|
||||
(await ocean.assets.search(`Test2${testHash}`)).results.length -
|
||||
test2length,
|
||||
(await ocean.assets.search(`Test2${testHash}`)).results.length - test2length,
|
||||
2,
|
||||
'Something was wrong searching the assets'
|
||||
)
|
||||
assert.equal(
|
||||
(await ocean.assets.search(`Test3${testHash}`)).results.length -
|
||||
test3length,
|
||||
(await ocean.assets.search(`Test3${testHash}`)).results.length - test3length,
|
||||
1,
|
||||
'Something was wrong searching the assets'
|
||||
)
|
||||
@ -94,14 +65,8 @@ describe('Search Asset', () => {
|
||||
it('should return a list of DDOs', async () => {
|
||||
const { results: ddos } = await ocean.assets.search(`Test1${testHash}`)
|
||||
|
||||
assert.equal(
|
||||
ddos.length - test1length,
|
||||
1,
|
||||
'Something was wrong searching the assets'
|
||||
)
|
||||
ddos.map(ddo =>
|
||||
assert.instanceOf(ddo, DDO, 'The DDO is not an instance of a DDO')
|
||||
)
|
||||
assert.equal(ddos.length - test1length, 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 () => {
|
||||
@ -117,8 +82,6 @@ describe('Search Asset', () => {
|
||||
})
|
||||
|
||||
assert.equal(ddos.length, 1, 'Something was wrong searching the assets')
|
||||
ddos.map(ddo =>
|
||||
assert.instanceOf(ddo, DDO, 'The DDO is not an instance of a DDO')
|
||||
)
|
||||
ddos.map(ddo => assert.instanceOf(ddo, DDO, 'The DDO is not an instance of a DDO'))
|
||||
})
|
||||
})
|
||||
|
@ -21,11 +21,7 @@ describe('Secret Store', () => {
|
||||
})
|
||||
|
||||
it('should encrypt a text', async () => {
|
||||
encryptedContent = await ocean.secretStore.encrypt(
|
||||
did.getId(),
|
||||
content,
|
||||
account
|
||||
)
|
||||
encryptedContent = await ocean.secretStore.encrypt(did.getId(), content, account)
|
||||
|
||||
assert.isDefined(encryptedContent)
|
||||
assert.match(encryptedContent, /^0x[a-f0-9]{76}$/i)
|
||||
|
@ -76,11 +76,7 @@ describe('Signature', () => {
|
||||
ddo,
|
||||
0,
|
||||
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
|
||||
)
|
||||
|
||||
|
@ -13,23 +13,19 @@ const metadata: Partial<MetaData> = {
|
||||
{
|
||||
index: 0,
|
||||
contentType: 'application/json',
|
||||
url:
|
||||
'https://raw.githubusercontent.com/oceanprotocol/squid-js/master/package.json'
|
||||
url: 'https://raw.githubusercontent.com/oceanprotocol/squid-js/master/package.json'
|
||||
},
|
||||
{
|
||||
index: 1,
|
||||
contentType: 'text/plain',
|
||||
url:
|
||||
'https://raw.githubusercontent.com/oceanprotocol/squid-js/master/README.md'
|
||||
url: 'https://raw.githubusercontent.com/oceanprotocol/squid-js/master/README.md'
|
||||
}
|
||||
]
|
||||
},
|
||||
additionalInformation: {
|
||||
description:
|
||||
'Weather information of UK including temperature and humidity',
|
||||
description: 'Weather information of UK including temperature and humidity',
|
||||
copyrightHolder: 'Met Office',
|
||||
workExample:
|
||||
'423432fsd,51.509865,-0.118092,2011-01-01T10:55:11+00:00,7.2,68',
|
||||
workExample: '423432fsd,51.509865,-0.118092,2011-01-01T10:55:11+00:00,7.2,68',
|
||||
links: [
|
||||
{
|
||||
name: 'Sample of Asset Data',
|
||||
@ -48,10 +44,7 @@ const metadata: Partial<MetaData> = {
|
||||
}
|
||||
}
|
||||
|
||||
export const generateMetadata = (
|
||||
name: string,
|
||||
price?: number
|
||||
): Partial<MetaData> => ({
|
||||
export const generateMetadata = (name: string, price?: number): Partial<MetaData> => ({
|
||||
...metadata,
|
||||
main: {
|
||||
...metadata.main,
|
||||
@ -63,5 +56,4 @@ export const generateMetadata = (
|
||||
}
|
||||
})
|
||||
|
||||
export const getMetadata = (price?: number) =>
|
||||
generateMetadata('TestAsset', price)
|
||||
export const getMetadata = (price?: number) => generateMetadata('TestAsset', price)
|
||||
|
@ -6,26 +6,23 @@ module.exports = class AddVendorsPlugin {
|
||||
}
|
||||
|
||||
apply(compiler) {
|
||||
compiler.hooks.emit.tapAsync(
|
||||
`AddVendorsPlugin ${this.base}`,
|
||||
(compilation, callback) => {
|
||||
const main = compilation.assets[`main.${this.base}`]
|
||||
const mainMap = compilation.assets[`main.${this.base}.map`]
|
||||
const vendor = compilation.assets[`vendors.${this.base}`]
|
||||
compiler.hooks.emit.tapAsync(`AddVendorsPlugin ${this.base}`, (compilation, callback) => {
|
||||
const main = compilation.assets[`main.${this.base}`]
|
||||
const mainMap = compilation.assets[`main.${this.base}.map`]
|
||||
const vendor = compilation.assets[`vendors.${this.base}`]
|
||||
|
||||
if (main && vendor) {
|
||||
const compiledAsset = new ConcatSource(main.children[0])
|
||||
compiledAsset.add(vendor)
|
||||
compiledAsset.add(main.children[1])
|
||||
compilation.assets = {}
|
||||
compilation.assets[this.base] = compiledAsset
|
||||
} else if (main && mainMap) {
|
||||
compilation.assets = {}
|
||||
compilation.assets[this.base] = main
|
||||
compilation.assets[`${this.base}.map`] = mainMap
|
||||
}
|
||||
callback()
|
||||
if (main && vendor) {
|
||||
const compiledAsset = new ConcatSource(main.children[0])
|
||||
compiledAsset.add(vendor)
|
||||
compiledAsset.add(main.children[1])
|
||||
compilation.assets = {}
|
||||
compilation.assets[this.base] = compiledAsset
|
||||
} else if (main && mainMap) {
|
||||
compilation.assets = {}
|
||||
compilation.assets[this.base] = main
|
||||
compilation.assets[`${this.base}.map`] = mainMap
|
||||
}
|
||||
)
|
||||
callback()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -15,10 +15,7 @@ const outPath = './dist/squid-js.json'
|
||||
const files = ['./src/squid.ts']
|
||||
|
||||
// specifically point to tsconfig, otherwise TypeDoc fails
|
||||
const config = typescript.findConfigFile(
|
||||
'./tsconfig.js',
|
||||
typescript.sys.fileExists
|
||||
)
|
||||
const config = typescript.findConfigFile('./tsconfig.js', typescript.sys.fileExists)
|
||||
|
||||
const generateJson = () => {
|
||||
const spinnerTypedoc = ora('Generating TypeDoc json...').start()
|
||||
|
@ -11,9 +11,7 @@ export interface InstantiableConfig {
|
||||
logger?: Logger
|
||||
}
|
||||
|
||||
export function generateIntantiableConfigFromConfig(
|
||||
config: Config
|
||||
): Partial<InstantiableConfig> {
|
||||
export function generateIntantiableConfigFromConfig(config: Config): Partial<InstantiableConfig> {
|
||||
const logLevel =
|
||||
typeof config.verbose !== 'number'
|
||||
? config.verbose
|
||||
@ -68,9 +66,7 @@ export abstract class Instantiable {
|
||||
public static async getInstance(...args: any[]): Promise<any>
|
||||
|
||||
public static async getInstance(config: InstantiableConfig): Promise<any> {
|
||||
LoggerInstance.warn(
|
||||
'getInstance() methods has needs to be added to child class.'
|
||||
)
|
||||
LoggerInstance.warn('getInstance() methods has needs to be added to child class.')
|
||||
}
|
||||
|
||||
protected static setInstanceConfig<T extends Instantiable>(
|
||||
|
@ -40,33 +40,20 @@ export class Aquarius extends Instantiable {
|
||||
|
||||
public async getAccessUrl(accessToken: any, payload: any): Promise<string> {
|
||||
const accessUrl: string = await this.ocean.utils.fetch
|
||||
.post(
|
||||
`${accessToken.service_endpoint}/${accessToken.resource_id}`,
|
||||
payload
|
||||
)
|
||||
.post(`${accessToken.service_endpoint}/${accessToken.resource_id}`, payload)
|
||||
.then((response: any): string => {
|
||||
if (response.ok) {
|
||||
return response.text()
|
||||
}
|
||||
this.logger.error(
|
||||
'Failed: ',
|
||||
response.status,
|
||||
response.statusText
|
||||
)
|
||||
this.logger.error('Failed: ', response.status, response.statusText)
|
||||
return null
|
||||
})
|
||||
.then((consumptionUrl: string): string => {
|
||||
this.logger.error(
|
||||
'Success accessing consume endpoint: ',
|
||||
consumptionUrl
|
||||
)
|
||||
this.logger.error('Success accessing consume endpoint: ', consumptionUrl)
|
||||
return consumptionUrl
|
||||
})
|
||||
.catch(error => {
|
||||
this.logger.error(
|
||||
'Error fetching the data asset consumption url: ',
|
||||
error
|
||||
)
|
||||
this.logger.error('Error fetching the data asset consumption url: ', error)
|
||||
return null
|
||||
})
|
||||
|
||||
@ -85,11 +72,7 @@ export class Aquarius extends Instantiable {
|
||||
if (response.ok) {
|
||||
return response.json() as DDO[]
|
||||
}
|
||||
this.logger.error(
|
||||
'queryMetadata failed:',
|
||||
response.status,
|
||||
response.statusText
|
||||
)
|
||||
this.logger.error('queryMetadata failed:', response.status, response.statusText)
|
||||
return this.transformResult()
|
||||
})
|
||||
.then(results => {
|
||||
@ -111,10 +94,7 @@ export class Aquarius extends Instantiable {
|
||||
public async queryMetadataByText(query: SearchQuery): Promise<QueryResult> {
|
||||
const fullUrl = new URL(`${this.url}${apiPath}/query`)
|
||||
fullUrl.searchParams.append('text', query.text)
|
||||
fullUrl.searchParams.append(
|
||||
'sort',
|
||||
decodeURIComponent(JSON.stringify(query.sort))
|
||||
)
|
||||
fullUrl.searchParams.append('sort', decodeURIComponent(JSON.stringify(query.sort)))
|
||||
fullUrl.searchParams.append('offset', query.offset.toString())
|
||||
fullUrl.searchParams.append('page', query.page.toString())
|
||||
const result: QueryResult = await this.ocean.utils.fetch
|
||||
@ -123,21 +103,14 @@ export class Aquarius extends Instantiable {
|
||||
if (response.ok) {
|
||||
return response.json() as DDO[]
|
||||
}
|
||||
this.logger.log(
|
||||
'queryMetadataByText failed:',
|
||||
response.status,
|
||||
response.statusText
|
||||
)
|
||||
this.logger.log('queryMetadataByText failed:', response.status, response.statusText)
|
||||
return this.transformResult()
|
||||
})
|
||||
.then(results => {
|
||||
return this.transformResult(results)
|
||||
})
|
||||
.catch(error => {
|
||||
this.logger.error(
|
||||
'Error fetching querying metadata by text: ',
|
||||
error
|
||||
)
|
||||
this.logger.error('Error fetching querying metadata by text: ', error)
|
||||
return this.transformResult()
|
||||
})
|
||||
|
||||
@ -157,12 +130,7 @@ export class Aquarius extends Instantiable {
|
||||
if (response.ok) {
|
||||
return response.json()
|
||||
}
|
||||
this.logger.error(
|
||||
'storeDDO failed:',
|
||||
response.status,
|
||||
response.statusText,
|
||||
ddo
|
||||
)
|
||||
this.logger.error('storeDDO failed:', response.status, response.statusText, ddo)
|
||||
return null as DDO
|
||||
})
|
||||
.then((response: DDO) => {
|
||||
@ -181,25 +149,16 @@ export class Aquarius extends Instantiable {
|
||||
* @param {DID | string} did DID of the asset.
|
||||
* @return {Promise<DDO>} DDO of the asset.
|
||||
*/
|
||||
public async retrieveDDO(
|
||||
did: DID | string,
|
||||
metadataServiceEndpoint?: string
|
||||
): Promise<DDO> {
|
||||
public async retrieveDDO(did: DID | string, metadataServiceEndpoint?: string): Promise<DDO> {
|
||||
did = did && DID.parse(did)
|
||||
const fullUrl =
|
||||
metadataServiceEndpoint || `${this.url}${apiPath}/${did.getDid()}`
|
||||
const fullUrl = metadataServiceEndpoint || `${this.url}${apiPath}/${did.getDid()}`
|
||||
const result = await this.ocean.utils.fetch
|
||||
.get(fullUrl)
|
||||
.then((response: any) => {
|
||||
if (response.ok) {
|
||||
return response.json()
|
||||
}
|
||||
this.logger.log(
|
||||
'retrieveDDO failed:',
|
||||
response.status,
|
||||
response.statusText,
|
||||
did
|
||||
)
|
||||
this.logger.log('retrieveDDO failed:', response.status, response.statusText, did)
|
||||
return null as DDO
|
||||
})
|
||||
.then((response: DDO) => {
|
||||
@ -222,12 +181,7 @@ export class Aquarius extends Instantiable {
|
||||
}
|
||||
|
||||
private transformResult(
|
||||
{
|
||||
results,
|
||||
page,
|
||||
total_pages: totalPages,
|
||||
total_results: totalResults
|
||||
}: any = {
|
||||
{ results, page, total_pages: totalPages, total_results: totalResults }: any = {
|
||||
result: [],
|
||||
page: 0,
|
||||
total_pages: 0, // eslint-disable-line @typescript-eslint/camelcase
|
||||
|
@ -35,12 +35,7 @@ export class Brizo extends Instantiable {
|
||||
return `${this.url}${apiPath}/publish`
|
||||
}
|
||||
|
||||
public getComputeEndpoint(
|
||||
pubKey: string,
|
||||
serviceIndex: number,
|
||||
_notUsed: string,
|
||||
container: string
|
||||
) {
|
||||
public getComputeEndpoint(pubKey: string, serviceIndex: number, _notUsed: string, container: string) {
|
||||
return `${this.url}${apiPath}/compute`
|
||||
}
|
||||
|
||||
@ -60,10 +55,7 @@ export class Brizo extends Instantiable {
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.ocean.utils.fetch.post(
|
||||
this.getPurchaseEndpoint(),
|
||||
decodeURI(JSON.stringify(args))
|
||||
)
|
||||
return await this.ocean.utils.fetch.post(this.getPurchaseEndpoint(), decodeURI(JSON.stringify(args)))
|
||||
} catch (e) {
|
||||
this.logger.error(e)
|
||||
throw new Error('HTTP request failed')
|
||||
@ -80,10 +72,7 @@ export class Brizo extends Instantiable {
|
||||
): Promise<string> {
|
||||
const signature =
|
||||
(await account.getToken()) ||
|
||||
(await this.ocean.utils.signature.signText(
|
||||
noZeroX(agreementId),
|
||||
account.getId()
|
||||
))
|
||||
(await this.ocean.utils.signature.signText(noZeroX(agreementId), account.getId()))
|
||||
const filesPromises = files
|
||||
.filter((_, i) => index === -1 || i === index)
|
||||
.map(async ({ index: i }) => {
|
||||
@ -94,11 +83,7 @@ export class Brizo extends Instantiable {
|
||||
consumeUrl += `&signature=${signature}`
|
||||
|
||||
try {
|
||||
await this.ocean.utils.fetch.downloadFile(
|
||||
consumeUrl,
|
||||
destination,
|
||||
i
|
||||
)
|
||||
await this.ocean.utils.fetch.downloadFile(consumeUrl, destination, i)
|
||||
} catch (e) {
|
||||
this.logger.error('Error consuming assets')
|
||||
this.logger.error(e)
|
||||
@ -109,12 +94,7 @@ export class Brizo extends Instantiable {
|
||||
return destination
|
||||
}
|
||||
|
||||
public async encrypt(
|
||||
did: string,
|
||||
signature: string,
|
||||
document: any,
|
||||
publisher: string
|
||||
): Promise<string> {
|
||||
public async encrypt(did: string, signature: string, document: any, publisher: string): Promise<string> {
|
||||
const args = {
|
||||
documentId: did,
|
||||
signature,
|
||||
|
@ -52,9 +52,7 @@ export class DDO {
|
||||
|
||||
public constructor(ddo: Partial<DDO> = {}) {
|
||||
Object.assign(this, ddo, {
|
||||
created:
|
||||
(ddo && ddo.created) ||
|
||||
new Date().toISOString().replace(/\.[0-9]{3}/, '')
|
||||
created: (ddo && ddo.created) || new Date().toISOString().replace(/\.[0-9]{3}/, '')
|
||||
})
|
||||
}
|
||||
|
||||
@ -82,9 +80,7 @@ export class DDO {
|
||||
* @param {string} serviceType Service type.
|
||||
* @return {Service} Service.
|
||||
*/
|
||||
public findServiceByType<T extends ServiceType>(
|
||||
serviceType: T
|
||||
): Service<T> {
|
||||
public findServiceByType<T extends ServiceType>(serviceType: T): Service<T> {
|
||||
if (!serviceType) {
|
||||
throw new Error('serviceType not set')
|
||||
}
|
||||
@ -120,18 +116,10 @@ export class DDO {
|
||||
* @param {string} password Password if it's required.
|
||||
* @return {Promise<Proof>} Proof object.
|
||||
*/
|
||||
public async generateProof(
|
||||
ocean: Ocean,
|
||||
publicKey: string,
|
||||
password?: string
|
||||
): Promise<Proof> {
|
||||
public async generateProof(ocean: Ocean, publicKey: string, password?: string): Promise<Proof> {
|
||||
const checksum = this.getChecksum()
|
||||
|
||||
const signature = await ocean.utils.signature.signText(
|
||||
checksum,
|
||||
publicKey,
|
||||
password
|
||||
)
|
||||
const signature = await ocean.utils.signature.signText(checksum, publicKey, password)
|
||||
|
||||
return {
|
||||
created: new Date().toISOString().replace(/\.[0-9]{3}/, ''),
|
||||
@ -160,11 +148,7 @@ export class DDO {
|
||||
* @param {string} password Password if it's requirted.
|
||||
* @return {Promise<Proof>} Proof object.
|
||||
*/
|
||||
public async addProof(
|
||||
web3: Web3,
|
||||
publicKey: string,
|
||||
password?: string
|
||||
): Promise<void> {
|
||||
public async addProof(web3: Web3, publicKey: string, password?: string): Promise<void> {
|
||||
if (this.proof) {
|
||||
throw new Error('Proof already exists')
|
||||
}
|
||||
|
@ -13,11 +13,7 @@ export interface PublicKey {
|
||||
* Type of key.
|
||||
* @type {string}
|
||||
*/
|
||||
type:
|
||||
| 'Ed25519VerificationKey2018'
|
||||
| 'RsaVerificationKey2018'
|
||||
| 'EdDsaSAPublicKeySecp256k1'
|
||||
| 'EthereumECDSAKey'
|
||||
type: 'Ed25519VerificationKey2018' | 'RsaVerificationKey2018' | 'EdDsaSAPublicKeySecp256k1' | 'EthereumECDSAKey'
|
||||
|
||||
/**
|
||||
* Key owner.
|
||||
|
@ -2,13 +2,7 @@ import { MetaData } from './MetaData'
|
||||
import { ServiceAgreementTemplate } from './ServiceAgreementTemplate'
|
||||
import { Provider } from './ComputingProvider'
|
||||
|
||||
export type ServiceType =
|
||||
| 'authorization'
|
||||
| 'metadata'
|
||||
| 'access'
|
||||
| 'compute'
|
||||
| 'computing'
|
||||
| 'fitchainCompute'
|
||||
export type ServiceType = 'authorization' | 'metadata' | 'access' | 'compute' | 'computing' | 'fitchainCompute'
|
||||
|
||||
export interface ServiceCommon {
|
||||
type: ServiceType
|
||||
@ -47,9 +41,7 @@ export interface ServiceCompute extends ServiceCommon {
|
||||
templateId?: string
|
||||
}
|
||||
|
||||
export type Service<
|
||||
T extends ServiceType | 'default' = 'default'
|
||||
> = T extends 'authorization'
|
||||
export type Service<T extends ServiceType | 'default' = 'default'> = T extends 'authorization'
|
||||
? ServiceAuthorization
|
||||
: T extends 'metadata'
|
||||
? ServiceMetadata
|
||||
|
@ -17,9 +17,7 @@ export class ContractEvent {
|
||||
private filter: { [key: string]: any }
|
||||
) {}
|
||||
|
||||
public subscribe(
|
||||
callback: (events: any[]) => void
|
||||
): ContractEventSubscription {
|
||||
public subscribe(callback: (events: any[]) => void): ContractEventSubscription {
|
||||
const onEvent = async (blockNumber: number) => {
|
||||
const events = await this.contract.getEventData(this.eventName, {
|
||||
filter: this.filter,
|
||||
|
@ -6,25 +6,15 @@ export default class ContractHandler extends Instantiable {
|
||||
return ContractHandler.contracts.get(this.getHash(what, networkId))
|
||||
}
|
||||
|
||||
protected static setContract(
|
||||
what: string,
|
||||
networkId: number,
|
||||
contractInstance: Contract
|
||||
) {
|
||||
ContractHandler.contracts.set(
|
||||
this.getHash(what, networkId),
|
||||
contractInstance
|
||||
)
|
||||
protected static setContract(what: string, networkId: number, contractInstance: Contract) {
|
||||
ContractHandler.contracts.set(this.getHash(what, networkId), contractInstance)
|
||||
}
|
||||
|
||||
protected static hasContract(what: string, networkId: number): boolean {
|
||||
return ContractHandler.contracts.has(this.getHash(what, networkId))
|
||||
}
|
||||
|
||||
private static contracts: Map<string, Contract> = new Map<
|
||||
string,
|
||||
Contract
|
||||
>()
|
||||
private static contracts: Map<string, Contract> = new Map<string, Contract>()
|
||||
|
||||
private static getHash(what: string, networkId: number): string {
|
||||
return `${what}/#${networkId}`
|
||||
@ -35,17 +25,11 @@ export default class ContractHandler extends Instantiable {
|
||||
this.setInstanceConfig(config)
|
||||
}
|
||||
|
||||
public async get(
|
||||
what: string,
|
||||
optional: boolean = false
|
||||
): Promise<Contract> {
|
||||
public async get(what: string, optional: boolean = false): Promise<Contract> {
|
||||
const where = (await this.ocean.keeper.getNetworkName()).toLowerCase()
|
||||
const networkId = await this.ocean.keeper.getNetworkId()
|
||||
try {
|
||||
return (
|
||||
ContractHandler.getContract(what, networkId) ||
|
||||
(await this.load(what, where, networkId))
|
||||
)
|
||||
return ContractHandler.getContract(what, networkId) || (await this.load(what, where, networkId))
|
||||
} catch (err) {
|
||||
if (!optional) {
|
||||
this.logger.error('Failed to load', what, 'from', where, err)
|
||||
@ -54,34 +38,18 @@ export default class ContractHandler extends Instantiable {
|
||||
}
|
||||
}
|
||||
|
||||
private async load(
|
||||
what: string,
|
||||
where: string,
|
||||
networkId: number
|
||||
): Promise<Contract> {
|
||||
private async load(what: string, where: string, networkId: number): Promise<Contract> {
|
||||
this.logger.debug('Loading', what, 'from', where)
|
||||
const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${what}.${where}.json`)
|
||||
// Logger.log('Loaded artifact', artifact)
|
||||
const code = await this.web3.eth.getCode(artifact.address)
|
||||
if (code === '0x0') {
|
||||
// no code in the blockchain dude
|
||||
throw new Error(
|
||||
`No code deployed at address ${artifact.address}, sorry.`
|
||||
)
|
||||
throw new Error(`No code deployed at address ${artifact.address}, sorry.`)
|
||||
}
|
||||
const contract = new this.web3.eth.Contract(
|
||||
artifact.abi,
|
||||
artifact.address
|
||||
)
|
||||
const contract = new this.web3.eth.Contract(artifact.abi, artifact.address)
|
||||
|
||||
this.logger.debug(
|
||||
'Getting instance of',
|
||||
what,
|
||||
'from',
|
||||
where,
|
||||
'at address',
|
||||
artifact.address
|
||||
)
|
||||
this.logger.debug('Getting instance of', what, 'from', where, 'at address', artifact.address)
|
||||
ContractHandler.setContract(what, networkId, contract)
|
||||
return ContractHandler.getContract(what, networkId)
|
||||
}
|
||||
|
@ -41,11 +41,7 @@ export class EventHandler extends Instantiable {
|
||||
}
|
||||
}
|
||||
|
||||
public getEvent(
|
||||
contract: ContractBase,
|
||||
eventName: string,
|
||||
filter: { [key: string]: any }
|
||||
) {
|
||||
public getEvent(contract: ContractBase, eventName: string, filter: { [key: string]: any }) {
|
||||
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.lastBlock = blockNumber
|
||||
}
|
||||
this.lastTimeout = global.setTimeout(
|
||||
() => this.checkBlock(true, n++),
|
||||
this.interval
|
||||
)
|
||||
this.lastTimeout = global.setTimeout(() => this.checkBlock(true, n++), this.interval)
|
||||
}
|
||||
}
|
||||
|
@ -15,11 +15,7 @@ import {
|
||||
EscrowAccessSecretStoreTemplate,
|
||||
EscrowComputeExecutionTemplate
|
||||
} from './contracts/templates'
|
||||
import {
|
||||
TemplateStoreManager,
|
||||
AgreementStoreManager,
|
||||
ConditionStoreManager
|
||||
} from './contracts/managers'
|
||||
import { TemplateStoreManager, AgreementStoreManager, ConditionStoreManager } from './contracts/managers'
|
||||
|
||||
import { objectPromiseAll } from '../utils'
|
||||
import { EventHandler } from './EventHandler'
|
||||
@ -38,9 +34,7 @@ export class Keeper extends Instantiable {
|
||||
* Returns Keeper instance.
|
||||
* @return {Promise<Keeper>}
|
||||
*/
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<Keeper> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<Keeper> {
|
||||
const keeper = new Keeper()
|
||||
keeper.setInstanceConfig(config)
|
||||
|
||||
@ -56,28 +50,16 @@ export class Keeper extends Instantiable {
|
||||
didRegistry: DIDRegistry.getInstance(config),
|
||||
// Managers
|
||||
templateStoreManager: TemplateStoreManager.getInstance(config),
|
||||
agreementStoreManager: AgreementStoreManager.getInstance(
|
||||
config
|
||||
),
|
||||
conditionStoreManager: ConditionStoreManager.getInstance(
|
||||
config
|
||||
),
|
||||
agreementStoreManager: AgreementStoreManager.getInstance(config),
|
||||
conditionStoreManager: ConditionStoreManager.getInstance(config),
|
||||
// Conditions
|
||||
lockRewardCondition: LockRewardCondition.getInstance(config),
|
||||
escrowReward: EscrowReward.getInstance(config),
|
||||
accessSecretStoreCondition: AccessSecretStoreCondition.getInstance(
|
||||
config
|
||||
),
|
||||
computeExecutionCondition: ComputeExecutionCondition.getInstance(
|
||||
config
|
||||
),
|
||||
accessSecretStoreCondition: AccessSecretStoreCondition.getInstance(config),
|
||||
computeExecutionCondition: ComputeExecutionCondition.getInstance(config),
|
||||
// Templates
|
||||
escrowAccessSecretStoreTemplate: EscrowAccessSecretStoreTemplate.getInstance(
|
||||
config
|
||||
),
|
||||
escrowComputeExecutionTemplate: EscrowComputeExecutionTemplate.getInstance(
|
||||
config
|
||||
)
|
||||
escrowAccessSecretStoreTemplate: EscrowAccessSecretStoreTemplate.getInstance(config),
|
||||
escrowComputeExecutionTemplate: EscrowComputeExecutionTemplate.getInstance(config)
|
||||
})
|
||||
|
||||
keeper.connected = true
|
||||
@ -105,17 +87,13 @@ export class Keeper extends Instantiable {
|
||||
keeper.conditions = {
|
||||
lockRewardCondition: keeper.instances.lockRewardCondition,
|
||||
escrowReward: keeper.instances.escrowReward,
|
||||
accessSecretStoreCondition:
|
||||
keeper.instances.accessSecretStoreCondition,
|
||||
computeExecutionCondition:
|
||||
keeper.instances.computeExecutionCondition
|
||||
accessSecretStoreCondition: keeper.instances.accessSecretStoreCondition,
|
||||
computeExecutionCondition: keeper.instances.computeExecutionCondition
|
||||
}
|
||||
// Conditions
|
||||
keeper.templates = {
|
||||
escrowAccessSecretStoreTemplate:
|
||||
keeper.instances.escrowAccessSecretStoreTemplate,
|
||||
escrowComputeExecutionTemplate:
|
||||
keeper.instances.escrowComputeExecutionTemplate
|
||||
escrowAccessSecretStoreTemplate: keeper.instances.escrowAccessSecretStoreTemplate,
|
||||
escrowComputeExecutionTemplate: keeper.instances.escrowComputeExecutionTemplate
|
||||
}
|
||||
// Utils
|
||||
keeper.utils = {
|
||||
@ -200,9 +178,7 @@ export class Keeper extends Instantiable {
|
||||
* @return {Condition} Condition instance.
|
||||
*/
|
||||
public getConditionByAddress(address: string): Condition {
|
||||
return Object.values(this.conditions).find(
|
||||
condition => condition.getAddress() === address
|
||||
)
|
||||
return Object.values(this.conditions).find(condition => condition.getAddress() === address)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -211,9 +187,7 @@ export class Keeper extends Instantiable {
|
||||
* @return {AgreementTemplate} Agreement template instance.
|
||||
*/
|
||||
public getTemplateByName(name: string): AgreementTemplate {
|
||||
return Object.values(this.templates).find(
|
||||
template => template.contractName === name
|
||||
)
|
||||
return Object.values(this.templates).find(template => template.contractName === name)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -222,9 +196,7 @@ export class Keeper extends Instantiable {
|
||||
* @return {AgreementTemplate} Agreement template instance.
|
||||
*/
|
||||
public getTemplateByAddress(address: string): AgreementTemplate {
|
||||
return Object.values(this.templates).find(
|
||||
template => template.getAddress() === address
|
||||
)
|
||||
return Object.values(this.templates).find(template => template.getAddress() === address)
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -7,10 +7,6 @@ export default class Web3Provider {
|
||||
* @return {Web3}
|
||||
*/
|
||||
public static getWeb3(config: Partial<Config> = {}): Web3 {
|
||||
return new Web3(
|
||||
config.web3Provider ||
|
||||
Web3.givenProvider ||
|
||||
new Web3.providers.HttpProvider(config.nodeUri)
|
||||
)
|
||||
return new Web3(config.web3Provider || Web3.givenProvider || new Web3.providers.HttpProvider(config.nodeUri))
|
||||
}
|
||||
}
|
||||
|
@ -22,9 +22,7 @@ export abstract class ContractBase extends Instantiable {
|
||||
|
||||
public async getEventData(eventName: string, options: any) {
|
||||
if (!this.contract.events[eventName]) {
|
||||
throw new Error(
|
||||
`Event "${eventName}" not found on contract "${this.contractName}"`
|
||||
)
|
||||
throw new Error(`Event "${eventName}" not found on contract "${this.contractName}"`)
|
||||
}
|
||||
return this.contract.getPastEvents(eventName, options)
|
||||
}
|
||||
@ -54,10 +52,7 @@ export abstract class ContractBase extends Instantiable {
|
||||
protected async init(config: InstantiableConfig) {
|
||||
this.setInstanceConfig(config)
|
||||
const contractHandler = new ContractHandler(config)
|
||||
this.contract = await contractHandler.get(
|
||||
this.contractName,
|
||||
this.optional
|
||||
)
|
||||
this.contract = await contractHandler.get(this.contractName, this.optional)
|
||||
}
|
||||
|
||||
protected async getFromAddress(from?: string): Promise<string> {
|
||||
@ -67,24 +62,14 @@ export abstract class ContractBase extends Instantiable {
|
||||
return from
|
||||
}
|
||||
|
||||
protected async sendFrom(
|
||||
name: string,
|
||||
args: any[],
|
||||
from?: string
|
||||
): Promise<TransactionReceipt> {
|
||||
protected async sendFrom(name: string, args: any[], from?: string): Promise<TransactionReceipt> {
|
||||
from = await this.getFromAddress(from)
|
||||
return this.send(name, from, args)
|
||||
}
|
||||
|
||||
protected async send(
|
||||
name: string,
|
||||
from: string,
|
||||
args: any[]
|
||||
): Promise<TransactionReceipt> {
|
||||
protected async send(name: string, from: string, args: any[]): Promise<TransactionReceipt> {
|
||||
if (!this.contract.methods[name]) {
|
||||
throw new Error(
|
||||
`Method "${name}" is not part of contract "${this.contractName}"`
|
||||
)
|
||||
throw new Error(`Method "${name}" is not part of contract "${this.contractName}"`)
|
||||
}
|
||||
// Logger.log(name, args)
|
||||
const method = this.contract.methods[name]
|
||||
@ -99,62 +84,41 @@ export abstract class ContractBase extends Instantiable {
|
||||
})
|
||||
return tx
|
||||
} catch (err) {
|
||||
const mappedArgs = this.searchMethod(name, args).inputs.map(
|
||||
(input, i) => {
|
||||
return {
|
||||
name: input.name,
|
||||
value: args[i]
|
||||
}
|
||||
const mappedArgs = this.searchMethod(name, args).inputs.map((input, i) => {
|
||||
return {
|
||||
name: input.name,
|
||||
value: args[i]
|
||||
}
|
||||
)
|
||||
})
|
||||
this.logger.error('-'.repeat(40))
|
||||
this.logger.error(
|
||||
`Sending transaction "${name}" on contract "${this.contractName}" failed.`
|
||||
)
|
||||
this.logger.error(`Sending transaction "${name}" on contract "${this.contractName}" failed.`)
|
||||
this.logger.error(`Error: ${err.message}`)
|
||||
this.logger.error(`From: ${from}`)
|
||||
this.logger.error(
|
||||
`Parameters: ${JSON.stringify(mappedArgs, null, 2)}`
|
||||
)
|
||||
this.logger.error(`Parameters: ${JSON.stringify(mappedArgs, null, 2)}`)
|
||||
this.logger.error('-'.repeat(40))
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
protected async call<T extends any>(
|
||||
name: string,
|
||||
args: any[],
|
||||
from?: string
|
||||
): Promise<T> {
|
||||
protected async call<T extends any>(name: string, args: any[], from?: string): Promise<T> {
|
||||
if (!this.contract.methods[name]) {
|
||||
throw new Error(
|
||||
`Method ${name} is not part of contract ${this.contractName}`
|
||||
)
|
||||
throw new Error(`Method ${name} is not part of contract ${this.contractName}`)
|
||||
}
|
||||
// Logger.log(name)
|
||||
try {
|
||||
const method = this.contract.methods[name](...args)
|
||||
return method.call(from ? { from } : null)
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`Calling method "${name}" on contract "${this.contractName}" failed. Args: ${args}`,
|
||||
err
|
||||
)
|
||||
this.logger.error(`Calling method "${name}" on contract "${this.contractName}" failed. Args: ${args}`, err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
protected getEvent(eventName: string, filter: { [key: string]: any }) {
|
||||
if (!this.contract.events[eventName]) {
|
||||
throw new Error(
|
||||
`Event ${eventName} is not part of contract ${this.contractName}`
|
||||
)
|
||||
throw new Error(`Event ${eventName} is not part of contract ${this.contractName}`)
|
||||
}
|
||||
return this.ocean.keeper.utils.eventHandler.getEvent(
|
||||
this,
|
||||
eventName,
|
||||
filter
|
||||
)
|
||||
return this.ocean.keeper.utils.eventHandler.getEvent(this, eventName, filter)
|
||||
}
|
||||
|
||||
private searchMethod(methodName: string, args: any[] = []) {
|
||||
@ -164,13 +128,9 @@ export abstract class ContractBase extends Instantiable {
|
||||
signature: (method as any).signature
|
||||
}))
|
||||
.filter((method: any) => method.name === methodName)
|
||||
const foundMethod =
|
||||
methods.find(({ inputs }) => inputs.length === args.length) ||
|
||||
methods[0]
|
||||
const foundMethod = methods.find(({ inputs }) => inputs.length === args.length) || methods[0]
|
||||
if (!foundMethod) {
|
||||
throw new Error(
|
||||
`Method "${methodName}" is not part of contract "${this.contractName}"`
|
||||
)
|
||||
throw new Error(`Method "${methodName}" is not part of contract "${this.contractName}"`)
|
||||
}
|
||||
return foundMethod
|
||||
}
|
||||
|
@ -3,9 +3,7 @@ import { zeroX, didPrefixed, didZeroX } from '../../utils'
|
||||
import { InstantiableConfig } from '../../Instantiable.abstract'
|
||||
|
||||
export default class DIDRegistry extends ContractBase {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<DIDRegistry> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<DIDRegistry> {
|
||||
const didRegistry: DIDRegistry = new DIDRegistry('DIDRegistry')
|
||||
await didRegistry.init(config)
|
||||
return didRegistry
|
||||
@ -18,12 +16,7 @@ export default class DIDRegistry extends ContractBase {
|
||||
value: string,
|
||||
ownerAddress: string
|
||||
) {
|
||||
return this.send('registerAttribute', ownerAddress, [
|
||||
zeroX(did),
|
||||
zeroX(checksum),
|
||||
providers.map(zeroX),
|
||||
value
|
||||
])
|
||||
return this.send('registerAttribute', ownerAddress, [zeroX(did), zeroX(checksum), providers.map(zeroX), value])
|
||||
}
|
||||
|
||||
public async getDIDOwner(did: string): Promise<string> {
|
||||
@ -46,46 +39,22 @@ export default class DIDRegistry extends ContractBase {
|
||||
.map(didPrefixed)
|
||||
}
|
||||
|
||||
public async getAttributesByDid(
|
||||
did: string
|
||||
): Promise<{ did: string; serviceEndpoint: string; checksum: string }> {
|
||||
public async getAttributesByDid(did: string): Promise<{ did: string; serviceEndpoint: string; checksum: string }> {
|
||||
return (await this.getPastEvents('DIDAttributeRegistered', {
|
||||
_did: didZeroX(did)
|
||||
})).map(
|
||||
({
|
||||
returnValues: {
|
||||
_did,
|
||||
_checksum: checksum,
|
||||
_value: serviceEndpoint
|
||||
}
|
||||
}) => ({
|
||||
did: didPrefixed(_did),
|
||||
serviceEndpoint,
|
||||
checksum
|
||||
})
|
||||
)[0]
|
||||
})).map(({ returnValues: { _did, _checksum: checksum, _value: serviceEndpoint } }) => ({
|
||||
did: didPrefixed(_did),
|
||||
serviceEndpoint,
|
||||
checksum
|
||||
}))[0]
|
||||
}
|
||||
|
||||
public async grantPermission(
|
||||
did: string,
|
||||
grantee: string,
|
||||
ownerAddress: string
|
||||
) {
|
||||
return this.send('grantPermission', ownerAddress, [
|
||||
zeroX(did),
|
||||
zeroX(grantee)
|
||||
])
|
||||
public async grantPermission(did: string, grantee: string, ownerAddress: string) {
|
||||
return this.send('grantPermission', ownerAddress, [zeroX(did), zeroX(grantee)])
|
||||
}
|
||||
|
||||
public async revokePermission(
|
||||
did: string,
|
||||
grantee: string,
|
||||
ownerAddress: string
|
||||
) {
|
||||
return this.send('revokePermission', ownerAddress, [
|
||||
zeroX(did),
|
||||
zeroX(grantee)
|
||||
])
|
||||
public async revokePermission(did: string, grantee: string, ownerAddress: string) {
|
||||
return this.send('revokePermission', ownerAddress, [zeroX(did), zeroX(grantee)])
|
||||
}
|
||||
|
||||
public async getPermission(did: string, grantee: string): Promise<boolean> {
|
||||
|
@ -2,18 +2,13 @@ import ContractBase from './ContractBase'
|
||||
import { InstantiableConfig } from '../../Instantiable.abstract'
|
||||
|
||||
export default class Dispenser extends ContractBase {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<Dispenser> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<Dispenser> {
|
||||
const dispenser: Dispenser = new Dispenser('Dispenser', true)
|
||||
await dispenser.init(config)
|
||||
return dispenser
|
||||
}
|
||||
|
||||
public async requestTokens(
|
||||
amount: number | string,
|
||||
receiverAddress: string
|
||||
) {
|
||||
public async requestTokens(amount: number | string, receiverAddress: string) {
|
||||
return this.send('requestTokens', receiverAddress, [String(amount)])
|
||||
}
|
||||
}
|
||||
|
@ -2,10 +2,7 @@ import ContractBase from './ContractBase'
|
||||
import { InstantiableConfig } from '../../Instantiable.abstract'
|
||||
|
||||
export default class GenericContract extends ContractBase {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig,
|
||||
contractName: string
|
||||
): Promise<ContractBase> {
|
||||
public static async getInstance(config: InstantiableConfig, contractName: string): Promise<ContractBase> {
|
||||
const contract: GenericContract = new GenericContract(contractName)
|
||||
await contract.init(config)
|
||||
return contract
|
||||
|
@ -3,9 +3,7 @@ import ContractBase from './ContractBase'
|
||||
import { InstantiableConfig } from '../../Instantiable.abstract'
|
||||
|
||||
export default class OceanToken extends ContractBase {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<OceanToken> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<OceanToken> {
|
||||
const token: OceanToken = new OceanToken('OceanToken')
|
||||
await token.init(config)
|
||||
return token
|
||||
@ -20,9 +18,7 @@ export default class OceanToken extends ContractBase {
|
||||
}
|
||||
|
||||
public async balanceOf(address: string): Promise<number> {
|
||||
return this.call('balanceOf', [address]).then((balance: string) =>
|
||||
new BigNumber(balance).toNumber()
|
||||
)
|
||||
return this.call('balanceOf', [address]).then((balance: string) => new BigNumber(balance).toNumber())
|
||||
}
|
||||
|
||||
public async transfer(to: string, amount: number, from: string) {
|
||||
|
@ -3,44 +3,23 @@ import { zeroX, didZeroX, didPrefixed } from '../../../utils'
|
||||
import { InstantiableConfig } from '../../../Instantiable.abstract'
|
||||
|
||||
export class AccessSecretStoreCondition extends Condition {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<AccessSecretStoreCondition> {
|
||||
return Condition.getInstance(
|
||||
config,
|
||||
'AccessSecretStoreCondition',
|
||||
AccessSecretStoreCondition
|
||||
)
|
||||
public static async getInstance(config: InstantiableConfig): Promise<AccessSecretStoreCondition> {
|
||||
return Condition.getInstance(config, 'AccessSecretStoreCondition', AccessSecretStoreCondition)
|
||||
}
|
||||
|
||||
public hashValues(did: string, grantee: string) {
|
||||
return super.hashValues(didZeroX(did), zeroX(grantee))
|
||||
}
|
||||
|
||||
public fulfill(
|
||||
agreementId: string,
|
||||
did: string,
|
||||
grantee: string,
|
||||
from?: string
|
||||
) {
|
||||
return super.fulfill(
|
||||
agreementId,
|
||||
[didZeroX(did), grantee].map(zeroX),
|
||||
from
|
||||
)
|
||||
public fulfill(agreementId: string, did: string, grantee: string, from?: string) {
|
||||
return super.fulfill(agreementId, [didZeroX(did), grantee].map(zeroX), from)
|
||||
}
|
||||
|
||||
public checkPermissions(grantee: string, did: string, from?: string) {
|
||||
return this.call<boolean>(
|
||||
'checkPermissions',
|
||||
[grantee, didZeroX(did)].map(zeroX),
|
||||
from
|
||||
)
|
||||
return this.call<boolean>('checkPermissions', [grantee, didZeroX(did)].map(zeroX), from)
|
||||
}
|
||||
|
||||
public async getGrantedDidByConsumer(
|
||||
consumer: string
|
||||
): Promise<{ did: string; agreementId: string }[]> {
|
||||
public async getGrantedDidByConsumer(consumer: string): Promise<{ did: string; agreementId: string }[]> {
|
||||
return (await this.getPastEvents('Fulfilled', {
|
||||
_grantee: zeroX(consumer)
|
||||
})).map(({ returnValues }) => ({
|
||||
|
@ -3,42 +3,19 @@ import { zeroX, didZeroX, didPrefixed } from '../../../utils'
|
||||
import { InstantiableConfig } from '../../../Instantiable.abstract'
|
||||
|
||||
export class ComputeExecutionCondition extends Condition {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<ComputeExecutionCondition> {
|
||||
return Condition.getInstance(
|
||||
config,
|
||||
'ComputeExecutionCondition',
|
||||
ComputeExecutionCondition
|
||||
)
|
||||
public static async getInstance(config: InstantiableConfig): Promise<ComputeExecutionCondition> {
|
||||
return Condition.getInstance(config, 'ComputeExecutionCondition', ComputeExecutionCondition)
|
||||
}
|
||||
|
||||
public hashValues(did: string, computeConsumer: string) {
|
||||
return super.hashValues(didZeroX(did), zeroX(computeConsumer))
|
||||
}
|
||||
|
||||
public fulfill(
|
||||
agreementId: string,
|
||||
did: string,
|
||||
computeConsumer: string,
|
||||
from?: string
|
||||
) {
|
||||
return super.fulfill(
|
||||
agreementId,
|
||||
[didZeroX(did), computeConsumer].map(zeroX),
|
||||
from
|
||||
)
|
||||
public fulfill(agreementId: string, did: string, computeConsumer: string, from?: string) {
|
||||
return super.fulfill(agreementId, [didZeroX(did), computeConsumer].map(zeroX), from)
|
||||
}
|
||||
|
||||
public wasComputeTriggered(
|
||||
did: string,
|
||||
computeConsumer: string,
|
||||
from?: string
|
||||
) {
|
||||
return this.call<boolean>(
|
||||
'wasComputeTriggered',
|
||||
[didZeroX(did), computeConsumer].map(zeroX),
|
||||
from
|
||||
)
|
||||
public wasComputeTriggered(did: string, computeConsumer: string, from?: string) {
|
||||
return this.call<boolean>('wasComputeTriggered', [didZeroX(did), computeConsumer].map(zeroX), from)
|
||||
}
|
||||
}
|
||||
|
@ -9,12 +9,7 @@ export enum ConditionState {
|
||||
Aborted = 3
|
||||
}
|
||||
|
||||
export const conditionStateNames = [
|
||||
'Uninitialized',
|
||||
'Unfulfilled',
|
||||
'Fulfilled',
|
||||
'Aborted'
|
||||
]
|
||||
export const conditionStateNames = ['Uninitialized', 'Unfulfilled', 'Fulfilled', 'Aborted']
|
||||
|
||||
export abstract class Condition extends ContractBase {
|
||||
public static async getInstance(
|
||||
|
@ -3,9 +3,7 @@ import { zeroX } from '../../../utils'
|
||||
import { InstantiableConfig } from '../../../Instantiable.abstract'
|
||||
|
||||
export class EscrowReward extends Condition {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<EscrowReward> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<EscrowReward> {
|
||||
return Condition.getInstance(config, 'EscrowReward', EscrowReward)
|
||||
}
|
||||
|
||||
@ -16,10 +14,7 @@ export class EscrowReward extends Condition {
|
||||
lockCondition: string,
|
||||
releaseCondition: string
|
||||
) {
|
||||
return super.hashValues(
|
||||
amount,
|
||||
...[receiver, sender, lockCondition, releaseCondition].map(zeroX)
|
||||
)
|
||||
return super.hashValues(amount, ...[receiver, sender, lockCondition, releaseCondition].map(zeroX))
|
||||
}
|
||||
|
||||
public fulfill(
|
||||
@ -33,12 +28,7 @@ export class EscrowReward extends Condition {
|
||||
) {
|
||||
return super.fulfill(
|
||||
agreementId,
|
||||
[
|
||||
amount,
|
||||
...[receiver, sender, lockCondition, releaseCondition].map(
|
||||
zeroX
|
||||
)
|
||||
],
|
||||
[amount, ...[receiver, sender, lockCondition, releaseCondition].map(zeroX)],
|
||||
from
|
||||
)
|
||||
}
|
||||
|
@ -3,30 +3,15 @@ import { zeroX } from '../../../utils'
|
||||
import { InstantiableConfig } from '../../../Instantiable.abstract'
|
||||
|
||||
export class LockRewardCondition extends Condition {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<LockRewardCondition> {
|
||||
return Condition.getInstance(
|
||||
config,
|
||||
'LockRewardCondition',
|
||||
LockRewardCondition
|
||||
)
|
||||
public static async getInstance(config: InstantiableConfig): Promise<LockRewardCondition> {
|
||||
return Condition.getInstance(config, 'LockRewardCondition', LockRewardCondition)
|
||||
}
|
||||
|
||||
public hashValues(rewardAddress: string, amount: number | string) {
|
||||
return super.hashValues(zeroX(rewardAddress), String(amount))
|
||||
}
|
||||
|
||||
public fulfill(
|
||||
agreementId: string,
|
||||
rewardAddress: string,
|
||||
amount: number | string,
|
||||
from?: string
|
||||
) {
|
||||
return super.fulfill(
|
||||
agreementId,
|
||||
[zeroX(rewardAddress), String(amount)],
|
||||
from
|
||||
)
|
||||
public fulfill(agreementId: string, rewardAddress: string, amount: number | string, from?: string) {
|
||||
return super.fulfill(agreementId, [zeroX(rewardAddress), String(amount)], from)
|
||||
}
|
||||
}
|
||||
|
@ -12,12 +12,8 @@ export interface AgreementData {
|
||||
}
|
||||
|
||||
export class AgreementStoreManager extends ContractBase {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<AgreementStoreManager> {
|
||||
const templateStoreManeger: AgreementStoreManager = new AgreementStoreManager(
|
||||
'AgreementStoreManager'
|
||||
)
|
||||
public static async getInstance(config: InstantiableConfig): Promise<AgreementStoreManager> {
|
||||
const templateStoreManeger: AgreementStoreManager = new AgreementStoreManager('AgreementStoreManager')
|
||||
await templateStoreManeger.init(config)
|
||||
return templateStoreManeger
|
||||
}
|
||||
@ -27,14 +23,10 @@ export class AgreementStoreManager extends ContractBase {
|
||||
}
|
||||
|
||||
public async getAgreement(agreementId: string) {
|
||||
const {
|
||||
did,
|
||||
didOwner,
|
||||
templateId,
|
||||
conditionIds,
|
||||
lastUpdatedBy,
|
||||
blockNumberUpdated
|
||||
} = await this.call('getAgreement', [zeroX(agreementId)])
|
||||
const { did, didOwner, templateId, conditionIds, lastUpdatedBy, blockNumberUpdated } = await this.call(
|
||||
'getAgreement',
|
||||
[zeroX(agreementId)]
|
||||
)
|
||||
return {
|
||||
did,
|
||||
didOwner,
|
||||
|
@ -14,12 +14,8 @@ export interface ConditionData {
|
||||
}
|
||||
|
||||
export class ConditionStoreManager extends ContractBase {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<ConditionStoreManager> {
|
||||
const templateStoreManeger: ConditionStoreManager = new ConditionStoreManager(
|
||||
'ConditionStoreManager'
|
||||
)
|
||||
public static async getInstance(config: InstantiableConfig): Promise<ConditionStoreManager> {
|
||||
const templateStoreManeger: ConditionStoreManager = new ConditionStoreManager('ConditionStoreManager')
|
||||
await templateStoreManeger.init(config)
|
||||
return templateStoreManeger
|
||||
}
|
||||
@ -29,15 +25,10 @@ export class ConditionStoreManager extends ContractBase {
|
||||
}
|
||||
|
||||
public async getCondition(conditionId: string) {
|
||||
const {
|
||||
typeRef,
|
||||
state,
|
||||
timeLock,
|
||||
timeOut,
|
||||
blockNumber,
|
||||
lastUpdatedBy,
|
||||
blockNumberUpdated
|
||||
} = await this.call('getCondition', [zeroX(conditionId)])
|
||||
const { typeRef, state, timeLock, timeOut, blockNumber, lastUpdatedBy, blockNumberUpdated } = await this.call(
|
||||
'getCondition',
|
||||
[zeroX(conditionId)]
|
||||
)
|
||||
return {
|
||||
typeRef,
|
||||
state: +state,
|
||||
|
@ -17,12 +17,8 @@ export interface TemplateMetadata {
|
||||
}
|
||||
|
||||
export class TemplateStoreManager extends ContractBase {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<TemplateStoreManager> {
|
||||
const templateStoreManeger: TemplateStoreManager = new TemplateStoreManager(
|
||||
'TemplateStoreManager'
|
||||
)
|
||||
public static async getInstance(config: InstantiableConfig): Promise<TemplateStoreManager> {
|
||||
const templateStoreManeger: TemplateStoreManager = new TemplateStoreManager('TemplateStoreManager')
|
||||
await templateStoreManeger.init(config)
|
||||
return templateStoreManeger
|
||||
}
|
||||
@ -31,11 +27,7 @@ export class TemplateStoreManager extends ContractBase {
|
||||
return this.call('owner', [])
|
||||
}
|
||||
|
||||
public async proposeTemplate(
|
||||
address: string,
|
||||
from?: string,
|
||||
ignoreExists?: boolean
|
||||
) {
|
||||
public async proposeTemplate(address: string, from?: string, ignoreExists?: boolean) {
|
||||
const template = await this.getTemplate(address)
|
||||
if (template.blockNumberUpdated !== 0) {
|
||||
this.logger.warn(`Template "${address}" already exist.`)
|
||||
@ -47,16 +39,10 @@ export class TemplateStoreManager extends ContractBase {
|
||||
}
|
||||
}
|
||||
|
||||
public async approveTemplate(
|
||||
address: string,
|
||||
from?: string,
|
||||
ignoreApproved?: boolean
|
||||
) {
|
||||
public async approveTemplate(address: string, from?: string, ignoreApproved?: boolean) {
|
||||
const template = await this.getTemplate(address)
|
||||
if (template.state !== TemplateState.Proposed) {
|
||||
this.logger.warn(
|
||||
`Template "${address}" is not in "proposed" state.`
|
||||
)
|
||||
this.logger.warn(`Template "${address}" is not in "proposed" state.`)
|
||||
if (!ignoreApproved) {
|
||||
throw new Error(`Template not in "proposed" state.`)
|
||||
}
|
||||
@ -70,12 +56,7 @@ export class TemplateStoreManager extends ContractBase {
|
||||
}
|
||||
|
||||
public async getTemplate(address: string) {
|
||||
const {
|
||||
state,
|
||||
owner,
|
||||
lastUpdatedBy,
|
||||
blockNumberUpdated
|
||||
} = await this.call('getTemplate', [zeroX(address)])
|
||||
const { state, owner, lastUpdatedBy, blockNumberUpdated } = await this.call('getTemplate', [zeroX(address)])
|
||||
return {
|
||||
state: +state,
|
||||
owner,
|
||||
|
@ -1,9 +1,5 @@
|
||||
import ContractBase from '../ContractBase'
|
||||
import {
|
||||
Condition,
|
||||
ConditionState,
|
||||
conditionStateNames
|
||||
} from '../conditions/Condition.abstract'
|
||||
import { Condition, ConditionState, conditionStateNames } from '../conditions/Condition.abstract'
|
||||
import { DDO } from '../../../ddo/DDO'
|
||||
import { ServiceAgreementTemplate } from '../../../ddo/ServiceAgreementTemplate'
|
||||
import { zeroX } from '../../../utils'
|
||||
@ -25,9 +21,7 @@ export abstract class AgreementTemplate extends ContractBase {
|
||||
conditionName: string,
|
||||
templateClass: any
|
||||
): Promise<AgreementTemplate & any> {
|
||||
const condition: AgreementTemplate = new (templateClass as any)(
|
||||
conditionName
|
||||
)
|
||||
const condition: AgreementTemplate = new (templateClass as any)(conditionName)
|
||||
await condition.init(config)
|
||||
return condition
|
||||
}
|
||||
@ -56,14 +50,7 @@ export abstract class AgreementTemplate extends ContractBase {
|
||||
) {
|
||||
return this.sendFrom(
|
||||
'createAgreement',
|
||||
[
|
||||
zeroX(agreementId),
|
||||
zeroX(did),
|
||||
conditionIds.map(zeroX),
|
||||
timeLocks,
|
||||
timeOuts,
|
||||
...extraArgs
|
||||
],
|
||||
[zeroX(agreementId), zeroX(did), conditionIds.map(zeroX), timeLocks, timeOuts, ...extraArgs],
|
||||
from
|
||||
)
|
||||
}
|
||||
@ -81,9 +68,7 @@ export abstract class AgreementTemplate extends ContractBase {
|
||||
* @return {Promise<Condition[]>} Conditions contracts.
|
||||
*/
|
||||
public async getConditions(): Promise<Condition[]> {
|
||||
return (await this.getConditionTypes()).map(address =>
|
||||
this.ocean.keeper.getConditionByAddress(address)
|
||||
)
|
||||
return (await this.getConditionTypes()).map(address => this.ocean.keeper.getConditionByAddress(address))
|
||||
}
|
||||
|
||||
/**
|
||||
@ -114,9 +99,7 @@ export abstract class AgreementTemplate extends ContractBase {
|
||||
from?: string
|
||||
): Promise<boolean>
|
||||
|
||||
public abstract async getServiceAgreementTemplate(): Promise<
|
||||
ServiceAgreementTemplate
|
||||
>
|
||||
public abstract async getServiceAgreementTemplate(): Promise<ServiceAgreementTemplate>
|
||||
|
||||
public async getServiceAgreementTemplateConditions() {
|
||||
const serviceAgreementTemplate = await this.getServiceAgreementTemplate()
|
||||
@ -127,9 +110,7 @@ export abstract class AgreementTemplate extends ContractBase {
|
||||
const name = (await this.getServiceAgreementTemplateConditions()).find(
|
||||
({ name: conditionRef }) => conditionRef === ref
|
||||
).contractName
|
||||
return (await this.getConditions()).find(
|
||||
condition => condition.contractName === name
|
||||
)
|
||||
return (await this.getConditions()).find(condition => condition.contractName === name)
|
||||
}
|
||||
|
||||
public async getServiceAgreementTemplateDependencies() {
|
||||
@ -142,9 +123,7 @@ export abstract class AgreementTemplate extends ContractBase {
|
||||
* @param {string} agreementId Agreement ID.
|
||||
* @return {Promise} Conditions status.
|
||||
*/
|
||||
public async getAgreementStatus(
|
||||
agreementId: string
|
||||
): Promise<AgreementConditionsStatus | false> {
|
||||
public async getAgreementStatus(agreementId: string): Promise<AgreementConditionsStatus | false> {
|
||||
const agreementStore = this.ocean.keeper.agreementStoreManager
|
||||
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 {
|
||||
contractName
|
||||
} = await this.getServiceAgreementTemplateConditionByRef(ref)
|
||||
const { contractName } = await this.getServiceAgreementTemplateConditionByRef(ref)
|
||||
return {
|
||||
ref,
|
||||
contractName,
|
||||
state: (await conditionStore.getCondition(
|
||||
conditionIdByConddition[contractName]
|
||||
)).state
|
||||
state: (await conditionStore.getCondition(conditionIdByConddition[contractName])).state
|
||||
}
|
||||
})
|
||||
const states = await Promise.all(statesPromises)
|
||||
@ -181,9 +156,7 @@ export abstract class AgreementTemplate extends ContractBase {
|
||||
return states.reduce((acc, { contractName, ref, state }) => {
|
||||
const blockers = dependencies[ref]
|
||||
.map(dependency => states.find(_ => _.ref === dependency))
|
||||
.filter(
|
||||
condition => condition.state !== ConditionState.Fulfilled
|
||||
)
|
||||
.filter(condition => condition.state !== ConditionState.Fulfilled)
|
||||
return {
|
||||
...acc,
|
||||
[ref]: {
|
||||
@ -211,22 +184,16 @@ export abstract class AgreementTemplate extends ContractBase {
|
||||
if (!status) {
|
||||
this.logger.bypass('Agreement not created yet!')
|
||||
}
|
||||
Object.values(status || []).forEach(
|
||||
({ condition, contractName, state, blocked, blockedBy }, i) => {
|
||||
if (i) {
|
||||
this.logger.bypass('-'.repeat(20))
|
||||
}
|
||||
this.logger.bypass(`${condition} (${contractName})`)
|
||||
this.logger.bypass(
|
||||
' Status:',
|
||||
state,
|
||||
`(${conditionStateNames[state]})`
|
||||
)
|
||||
if (blocked) {
|
||||
this.logger.bypass(' Blocked by:', blockedBy)
|
||||
}
|
||||
Object.values(status || []).forEach(({ condition, contractName, state, blocked, blockedBy }, i) => {
|
||||
if (i) {
|
||||
this.logger.bypass('-'.repeat(20))
|
||||
}
|
||||
)
|
||||
this.logger.bypass(`${condition} (${contractName})`)
|
||||
this.logger.bypass(' Status:', state, `(${conditionStateNames[state]})`)
|
||||
if (blocked) {
|
||||
this.logger.bypass(' Blocked by:', blockedBy)
|
||||
}
|
||||
})
|
||||
this.logger.bypass('-'.repeat(80))
|
||||
}
|
||||
|
||||
|
@ -26,15 +26,7 @@ export abstract class BaseEscrowTemplate extends AgreementTemplate {
|
||||
accessConsumer: string,
|
||||
from?: string
|
||||
) {
|
||||
return super.createAgreement(
|
||||
agreementId,
|
||||
did,
|
||||
conditionIds,
|
||||
timeLocks,
|
||||
timeOuts,
|
||||
[accessConsumer],
|
||||
from
|
||||
)
|
||||
return super.createAgreement(agreementId, did, conditionIds, timeLocks, timeOuts, [accessConsumer], from)
|
||||
}
|
||||
|
||||
public async getAgreementData(agreementId: string) {
|
||||
|
@ -13,11 +13,7 @@ export const escrowAccessSecretStoreTemplateServiceAgreementTemplate: ServiceAgr
|
||||
}
|
||||
}
|
||||
],
|
||||
fulfillmentOrder: [
|
||||
'lockReward.fulfill',
|
||||
'accessSecretStore.fulfill',
|
||||
'escrowReward.fulfill'
|
||||
],
|
||||
fulfillmentOrder: ['lockReward.fulfill', 'accessSecretStore.fulfill', 'escrowReward.fulfill'],
|
||||
conditionDependency: {
|
||||
lockReward: [],
|
||||
accessSecretStore: [],
|
||||
|
@ -7,26 +7,15 @@ import { InstantiableConfig } from '../../../Instantiable.abstract'
|
||||
import { escrowAccessSecretStoreTemplateServiceAgreementTemplate } from './EscrowAccessSecretStoreTemplate.serviceAgreementTemplate'
|
||||
|
||||
export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<EscrowAccessSecretStoreTemplate> {
|
||||
return AgreementTemplate.getInstance(
|
||||
config,
|
||||
'EscrowAccessSecretStoreTemplate',
|
||||
EscrowAccessSecretStoreTemplate
|
||||
)
|
||||
public static async getInstance(config: InstantiableConfig): Promise<EscrowAccessSecretStoreTemplate> {
|
||||
return AgreementTemplate.getInstance(config, 'EscrowAccessSecretStoreTemplate', EscrowAccessSecretStoreTemplate)
|
||||
}
|
||||
|
||||
public async getServiceAgreementTemplate() {
|
||||
return escrowAccessSecretStoreTemplateServiceAgreementTemplate
|
||||
}
|
||||
|
||||
public async createAgreementFromDDO(
|
||||
agreementId: string,
|
||||
ddo: DDO,
|
||||
consumer: string,
|
||||
from?: string
|
||||
) {
|
||||
public async createAgreementFromDDO(agreementId: string, ddo: DDO, consumer: string, from?: string) {
|
||||
return !!(await this.createFullAgreement(
|
||||
ddo.shortId(),
|
||||
ddo.findServiceByType('metadata').attributes.main.price,
|
||||
@ -36,12 +25,7 @@ export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate {
|
||||
))
|
||||
}
|
||||
|
||||
public async getAgreementIdsFromDDO(
|
||||
agreementId: string,
|
||||
ddo: DDO,
|
||||
consumer: string,
|
||||
from?: string
|
||||
) {
|
||||
public async getAgreementIdsFromDDO(agreementId: string, ddo: DDO, consumer: string, from?: string) {
|
||||
const {
|
||||
accessSecretStoreConditionId,
|
||||
lockRewardConditionId,
|
||||
@ -52,11 +36,7 @@ export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate {
|
||||
ddo.findServiceByType('metadata').attributes.main.price,
|
||||
consumer
|
||||
)
|
||||
return [
|
||||
accessSecretStoreConditionId,
|
||||
lockRewardConditionId,
|
||||
escrowRewardId
|
||||
]
|
||||
return [accessSecretStoreConditionId, lockRewardConditionId, escrowRewardId]
|
||||
}
|
||||
|
||||
/**
|
||||
@ -77,21 +57,12 @@ export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate {
|
||||
accessSecretStoreConditionId,
|
||||
lockRewardConditionId,
|
||||
escrowRewardId
|
||||
} = await this.createFullAgreementData(
|
||||
agreementId,
|
||||
did,
|
||||
amount,
|
||||
consumer
|
||||
)
|
||||
} = await this.createFullAgreementData(agreementId, did, amount, consumer)
|
||||
|
||||
await this.createAgreement(
|
||||
agreementId,
|
||||
did,
|
||||
[
|
||||
accessSecretStoreConditionId,
|
||||
lockRewardConditionId,
|
||||
escrowRewardId
|
||||
],
|
||||
[accessSecretStoreConditionId, lockRewardConditionId, escrowRewardId],
|
||||
[0, 0, 0],
|
||||
[0, 0, 0],
|
||||
consumer,
|
||||
@ -101,19 +72,10 @@ export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate {
|
||||
return zeroX(agreementId)
|
||||
}
|
||||
|
||||
private async createFullAgreementData(
|
||||
agreementId: string,
|
||||
did: string,
|
||||
amount: number | string,
|
||||
consumer: string
|
||||
) {
|
||||
private async createFullAgreementData(agreementId: string, did: string, amount: number | string, consumer: string) {
|
||||
const { didRegistry, conditions } = this.ocean.keeper
|
||||
|
||||
const {
|
||||
accessSecretStoreCondition,
|
||||
lockRewardCondition,
|
||||
escrowReward
|
||||
} = conditions
|
||||
const { accessSecretStoreCondition, lockRewardCondition, escrowReward } = conditions
|
||||
|
||||
const publisher = await didRegistry.getDIDOwner(did)
|
||||
|
||||
@ -122,11 +84,7 @@ export class EscrowAccessSecretStoreTemplate extends BaseEscrowTemplate {
|
||||
await escrowReward.getAddress(),
|
||||
amount
|
||||
)
|
||||
const accessSecretStoreConditionId = await accessSecretStoreCondition.generateIdHash(
|
||||
agreementId,
|
||||
did,
|
||||
consumer
|
||||
)
|
||||
const accessSecretStoreConditionId = await accessSecretStoreCondition.generateIdHash(agreementId, did, consumer)
|
||||
const escrowRewardId = await escrowReward.generateIdHash(
|
||||
agreementId,
|
||||
String(amount),
|
||||
|
@ -13,11 +13,7 @@ export const escrowComputeExecutionTemplateServiceAgreementTemplate: ServiceAgre
|
||||
}
|
||||
}
|
||||
],
|
||||
fulfillmentOrder: [
|
||||
'lockReward.fulfill',
|
||||
'serviceExecution.fulfill',
|
||||
'escrowReward.fulfill'
|
||||
],
|
||||
fulfillmentOrder: ['lockReward.fulfill', 'serviceExecution.fulfill', 'escrowReward.fulfill'],
|
||||
conditionDependency: {
|
||||
lockReward: [],
|
||||
serviceExecution: [],
|
||||
|
@ -7,26 +7,15 @@ import { InstantiableConfig } from '../../../Instantiable.abstract'
|
||||
import { escrowComputeExecutionTemplateServiceAgreementTemplate } from './EscrowComputeExecutionTemplate.serviceAgreementTemplate'
|
||||
|
||||
export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate {
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<EscrowComputeExecutionTemplate> {
|
||||
return AgreementTemplate.getInstance(
|
||||
config,
|
||||
'EscrowComputeExecutionTemplate',
|
||||
EscrowComputeExecutionTemplate
|
||||
)
|
||||
public static async getInstance(config: InstantiableConfig): Promise<EscrowComputeExecutionTemplate> {
|
||||
return AgreementTemplate.getInstance(config, 'EscrowComputeExecutionTemplate', EscrowComputeExecutionTemplate)
|
||||
}
|
||||
|
||||
public async getServiceAgreementTemplate() {
|
||||
return escrowComputeExecutionTemplateServiceAgreementTemplate
|
||||
}
|
||||
|
||||
public async createAgreementFromDDO(
|
||||
agreementId: string,
|
||||
ddo: DDO,
|
||||
consumer: string,
|
||||
from?: string
|
||||
) {
|
||||
public async createAgreementFromDDO(agreementId: string, ddo: DDO, consumer: string, from?: string) {
|
||||
return !!(await this.createFullAgreement(
|
||||
ddo.shortId(),
|
||||
ddo.findServiceByType('Metadata').metadata.base.price,
|
||||
@ -36,12 +25,7 @@ export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate {
|
||||
))
|
||||
}
|
||||
|
||||
public async getAgreementIdsFromDDO(
|
||||
agreementId: string,
|
||||
ddo: DDO,
|
||||
consumer: string,
|
||||
from?: string
|
||||
) {
|
||||
public async getAgreementIdsFromDDO(agreementId: string, ddo: DDO, consumer: string, from?: string) {
|
||||
const {
|
||||
computeExecutionConditionId,
|
||||
lockRewardConditionId,
|
||||
@ -52,11 +36,7 @@ export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate {
|
||||
ddo.findServiceByType('Metadata').metadata.base.price,
|
||||
consumer
|
||||
)
|
||||
return [
|
||||
computeExecutionConditionId,
|
||||
lockRewardConditionId,
|
||||
escrowRewardId
|
||||
]
|
||||
return [computeExecutionConditionId, lockRewardConditionId, escrowRewardId]
|
||||
}
|
||||
|
||||
/**
|
||||
@ -77,21 +57,12 @@ export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate {
|
||||
computeExecutionConditionId,
|
||||
lockRewardConditionId,
|
||||
escrowRewardId
|
||||
} = await this.createFullAgreementData(
|
||||
agreementId,
|
||||
did,
|
||||
amount,
|
||||
consumer
|
||||
)
|
||||
} = await this.createFullAgreementData(agreementId, did, amount, consumer)
|
||||
|
||||
await this.createAgreement(
|
||||
agreementId,
|
||||
did,
|
||||
[
|
||||
computeExecutionConditionId,
|
||||
lockRewardConditionId,
|
||||
escrowRewardId
|
||||
],
|
||||
[computeExecutionConditionId, lockRewardConditionId, escrowRewardId],
|
||||
[0, 0, 0],
|
||||
[0, 0, 0],
|
||||
consumer,
|
||||
@ -101,19 +72,10 @@ export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate {
|
||||
return zeroX(agreementId)
|
||||
}
|
||||
|
||||
private async createFullAgreementData(
|
||||
agreementId: string,
|
||||
did: string,
|
||||
amount: number | string,
|
||||
consumer: string
|
||||
) {
|
||||
private async createFullAgreementData(agreementId: string, did: string, amount: number | string, consumer: string) {
|
||||
const { didRegistry, conditions } = this.ocean.keeper
|
||||
|
||||
const {
|
||||
computeExecutionCondition,
|
||||
lockRewardCondition,
|
||||
escrowReward
|
||||
} = conditions
|
||||
const { computeExecutionCondition, lockRewardCondition, escrowReward } = conditions
|
||||
|
||||
const publisher = await didRegistry.getDIDOwner(did)
|
||||
|
||||
@ -122,11 +84,7 @@ export class EscrowComputeExecutionTemplate extends BaseEscrowTemplate {
|
||||
await escrowReward.getAddress(),
|
||||
amount
|
||||
)
|
||||
const computeExecutionConditionId = await computeExecutionCondition.generateIdHash(
|
||||
agreementId,
|
||||
did,
|
||||
consumer
|
||||
)
|
||||
const computeExecutionConditionId = await computeExecutionCondition.generateIdHash(agreementId, did, consumer)
|
||||
const escrowRewardId = await escrowReward.generateIdHash(
|
||||
agreementId,
|
||||
String(amount),
|
||||
|
@ -1,8 +1,4 @@
|
||||
export * from './AgreementTemplate.abstract'
|
||||
export { BaseEscrowTemplate } from './BaseEscrowTemplate.abstract'
|
||||
export {
|
||||
EscrowAccessSecretStoreTemplate
|
||||
} from './EscrowAccessSecretStoreTemplate'
|
||||
export {
|
||||
EscrowComputeExecutionTemplate
|
||||
} from './EscrowComputeExecutionTemplate'
|
||||
export { EscrowAccessSecretStoreTemplate } from './EscrowAccessSecretStoreTemplate'
|
||||
export { EscrowComputeExecutionTemplate } from './EscrowComputeExecutionTemplate'
|
||||
|
@ -87,11 +87,9 @@ export default class Account extends Instantiable {
|
||||
* @return {Promise<number>}
|
||||
*/
|
||||
public async getEtherBalance(): Promise<number> {
|
||||
return this.web3.eth
|
||||
.getBalance(this.id, 'latest')
|
||||
.then((balance: string): number => {
|
||||
return new BigNumber(balance).toNumber()
|
||||
})
|
||||
return this.web3.eth.getBalance(this.id, 'latest').then((balance: string): number => {
|
||||
return new BigNumber(balance).toNumber()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -14,10 +14,7 @@ import Keeper from '../keeper/Keeper'
|
||||
|
||||
import { Config } from '../models/Config'
|
||||
|
||||
import {
|
||||
Instantiable,
|
||||
generateIntantiableConfigFromConfig
|
||||
} from '../Instantiable.abstract'
|
||||
import { Instantiable, generateIntantiableConfigFromConfig } from '../Instantiable.abstract'
|
||||
|
||||
/**
|
||||
* Main interface for Ocean Protocol.
|
||||
@ -46,9 +43,7 @@ export class Ocean extends Instantiable {
|
||||
instance.auth = await OceanAuth.getInstance(instanceConfig)
|
||||
instance.assets = await OceanAssets.getInstance(instanceConfig)
|
||||
instance.agreements = await OceanAgreements.getInstance(instanceConfig)
|
||||
instance.secretStore = await OceanSecretStore.getInstance(
|
||||
instanceConfig
|
||||
)
|
||||
instance.secretStore = await OceanSecretStore.getInstance(instanceConfig)
|
||||
instance.tokens = await OceanTokens.getInstance(instanceConfig)
|
||||
instance.versions = await OceanVersions.getInstance(instanceConfig)
|
||||
|
||||
|
@ -10,9 +10,7 @@ export class OceanAccounts extends Instantiable {
|
||||
* Returns the instance of OceanAccounts.
|
||||
* @return {Promise<OceanAccounts>}
|
||||
*/
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<OceanAccounts> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<OceanAccounts> {
|
||||
const instance = new OceanAccounts()
|
||||
instance.setInstanceConfig(config)
|
||||
|
||||
@ -27,9 +25,7 @@ export class OceanAccounts extends Instantiable {
|
||||
// retrieve eth accounts
|
||||
const ethAccounts: string[] = await this.web3.eth.getAccounts()
|
||||
|
||||
const accountPromises = ethAccounts.map(
|
||||
address => new Account(address, this.instanceConfig)
|
||||
)
|
||||
const accountPromises = ethAccounts.map(address => new Account(address, this.instanceConfig))
|
||||
return Promise.all(accountPromises)
|
||||
}
|
||||
|
||||
@ -48,10 +44,7 @@ export class OceanAccounts extends Instantiable {
|
||||
* @param {number} amount Token amount.
|
||||
* @return {Promise<boolean>} Success.
|
||||
*/
|
||||
public async requestTokens(
|
||||
account: Account,
|
||||
amount: number
|
||||
): Promise<boolean> {
|
||||
public async requestTokens(account: Account, amount: number): Promise<boolean> {
|
||||
try {
|
||||
await account.requestTokens(amount)
|
||||
return true
|
||||
|
@ -21,14 +21,10 @@ export class OceanAgreements extends Instantiable {
|
||||
* Returns the instance of OceanAgreements.
|
||||
* @return {Promise<OceanAgreements>}
|
||||
*/
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<OceanAgreements> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<OceanAgreements> {
|
||||
const instance = new OceanAgreements()
|
||||
instance.setInstanceConfig(config)
|
||||
instance.conditions = await OceanAgreementsConditions.getInstance(
|
||||
config
|
||||
)
|
||||
instance.conditions = await OceanAgreementsConditions.getInstance(config)
|
||||
|
||||
return instance
|
||||
}
|
||||
@ -46,25 +42,15 @@ export class OceanAgreements extends Instantiable {
|
||||
* @param {Account} consumer Consumer account.
|
||||
* @return {Promise<AgreementPrepareResult>} Agreement ID and signaturee.
|
||||
*/
|
||||
public async prepare(
|
||||
did: string,
|
||||
index: number,
|
||||
consumer: Account
|
||||
): Promise<AgreementPrepareResult> {
|
||||
public async prepare(did: string, index: number, consumer: Account): Promise<AgreementPrepareResult> {
|
||||
const d: DID = DID.parse(did as string)
|
||||
const ddo = await this.ocean.aquarius.retrieveDDO(d)
|
||||
const agreementId: string = zeroX(generateId())
|
||||
|
||||
const templateName = ddo.findServiceByType('access')
|
||||
.serviceAgreementTemplate.contractName
|
||||
const templateName = ddo.findServiceByType('access').serviceAgreementTemplate.contractName
|
||||
const agreementConditionsIds = await this.ocean.keeper
|
||||
.getTemplateByName(templateName)
|
||||
.getAgreementIdsFromDDO(
|
||||
agreementId,
|
||||
ddo,
|
||||
consumer.getId(),
|
||||
consumer.getId()
|
||||
)
|
||||
.getAgreementIdsFromDDO(agreementId, ddo, consumer.getId(), consumer.getId())
|
||||
|
||||
const signature = await this.ocean.utils.agreements.signServiceAgreement(
|
||||
ddo,
|
||||
@ -100,9 +86,7 @@ export class OceanAgreements extends Instantiable {
|
||||
)
|
||||
|
||||
if (!result.ok) {
|
||||
throw new Error(
|
||||
'Error on initialize agreement: ' + (await result.text())
|
||||
)
|
||||
throw new Error('Error on initialize agreement: ' + (await result.text()))
|
||||
}
|
||||
}
|
||||
|
||||
@ -129,16 +113,10 @@ export class OceanAgreements extends Instantiable {
|
||||
const d: DID = DID.parse(did)
|
||||
const ddo = await this.ocean.aquarius.retrieveDDO(d)
|
||||
|
||||
const templateName = ddo.findServiceById<'access'>(index)
|
||||
.serviceAgreementTemplate.contractName
|
||||
const templateName = ddo.findServiceById<'access'>(index).serviceAgreementTemplate.contractName
|
||||
await this.ocean.keeper
|
||||
.getTemplateByName(templateName)
|
||||
.createAgreementFromDDO(
|
||||
agreementId,
|
||||
ddo,
|
||||
consumer.getId(),
|
||||
publisher.getId()
|
||||
)
|
||||
.createAgreementFromDDO(agreementId, ddo, consumer.getId(), publisher.getId())
|
||||
|
||||
return true
|
||||
}
|
||||
@ -149,25 +127,13 @@ export class OceanAgreements extends Instantiable {
|
||||
* @param {boolean} extended Returns a complete status with dependencies.
|
||||
* @return {Promise<any>}
|
||||
*/
|
||||
public async status(
|
||||
agreementId: string,
|
||||
extended?: false
|
||||
): Promise<{ [condition: string]: ConditionState }>
|
||||
public async status(agreementId: string, extended?: false): Promise<{ [condition: string]: ConditionState }>
|
||||
|
||||
public async status(
|
||||
agreementId: string,
|
||||
extended: true
|
||||
): Promise<AgreementConditionsStatus>
|
||||
public async status(agreementId: string, extended: true): Promise<AgreementConditionsStatus>
|
||||
|
||||
public async status(agreementId: string, extended: boolean = false) {
|
||||
const {
|
||||
templateId
|
||||
} = await this.ocean.keeper.agreementStoreManager.getAgreement(
|
||||
agreementId
|
||||
)
|
||||
const fullStatus = await this.ocean.keeper
|
||||
.getTemplateByAddress(templateId)
|
||||
.getAgreementStatus(agreementId)
|
||||
const { templateId } = await this.ocean.keeper.agreementStoreManager.getAgreement(agreementId)
|
||||
const fullStatus = await this.ocean.keeper.getTemplateByAddress(templateId).getAgreementStatus(agreementId)
|
||||
|
||||
if (!fullStatus) {
|
||||
return
|
||||
|
@ -9,9 +9,7 @@ export class OceanAgreementsConditions extends Instantiable {
|
||||
* Returns the instance of OceanAgreementsConditions.
|
||||
* @return {Promise<OceanAgreementsConditions>}
|
||||
*/
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<OceanAgreementsConditions> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<OceanAgreementsConditions> {
|
||||
const instance = new OceanAgreementsConditions()
|
||||
instance.setInstanceConfig(config)
|
||||
|
||||
@ -25,22 +23,11 @@ export class OceanAgreementsConditions extends Instantiable {
|
||||
* @param {number} amount Asset amount.
|
||||
* @param {Account} from Account of sender.
|
||||
*/
|
||||
public async lockReward(
|
||||
agreementId: string,
|
||||
amount: number | string,
|
||||
from?: Account
|
||||
) {
|
||||
const {
|
||||
lockRewardCondition,
|
||||
escrowReward
|
||||
} = this.ocean.keeper.conditions
|
||||
public async lockReward(agreementId: string, amount: number | string, from?: Account) {
|
||||
const { lockRewardCondition, escrowReward } = this.ocean.keeper.conditions
|
||||
|
||||
try {
|
||||
await this.ocean.keeper.token.approve(
|
||||
lockRewardCondition.getAddress(),
|
||||
amount,
|
||||
from.getId()
|
||||
)
|
||||
await this.ocean.keeper.token.approve(lockRewardCondition.getAddress(), amount, from.getId())
|
||||
|
||||
const receipt = await lockRewardCondition.fulfill(
|
||||
agreementId,
|
||||
@ -62,21 +49,11 @@ export class OceanAgreementsConditions extends Instantiable {
|
||||
* @param {string} grantee Consumer address.
|
||||
* @param {Account} from Account of sender.
|
||||
*/
|
||||
public async grantAccess(
|
||||
agreementId: string,
|
||||
did: string,
|
||||
grantee: string,
|
||||
from?: Account
|
||||
) {
|
||||
public async grantAccess(agreementId: string, did: string, grantee: string, from?: Account) {
|
||||
try {
|
||||
const { accessSecretStoreCondition } = this.ocean.keeper.conditions
|
||||
|
||||
const receipt = await accessSecretStoreCondition.fulfill(
|
||||
agreementId,
|
||||
did,
|
||||
grantee,
|
||||
from && from.getId()
|
||||
)
|
||||
const receipt = await accessSecretStoreCondition.fulfill(agreementId, did, grantee, from && from.getId())
|
||||
return !!receipt.events.Fulfilled
|
||||
} catch {
|
||||
return false
|
||||
@ -90,21 +67,11 @@ export class OceanAgreementsConditions extends Instantiable {
|
||||
* @param {string} grantee Consumer address.
|
||||
* @param {Account} from Account of sender.
|
||||
*/
|
||||
public async grantServiceExecution(
|
||||
agreementId: string,
|
||||
did: string,
|
||||
grantee: string,
|
||||
from?: Account
|
||||
) {
|
||||
public async grantServiceExecution(agreementId: string, did: string, grantee: string, from?: Account) {
|
||||
try {
|
||||
const { computeExecutionCondition } = this.ocean.keeper.conditions
|
||||
|
||||
const receipt = await computeExecutionCondition.fulfill(
|
||||
agreementId,
|
||||
did,
|
||||
grantee,
|
||||
from && from.getId()
|
||||
)
|
||||
const receipt = await computeExecutionCondition.fulfill(agreementId, did, grantee, from && from.getId())
|
||||
return !!receipt.events.Fulfilled
|
||||
} catch {
|
||||
return false
|
||||
@ -133,17 +100,9 @@ export class OceanAgreementsConditions extends Instantiable {
|
||||
from?: Account
|
||||
) {
|
||||
try {
|
||||
const {
|
||||
escrowReward,
|
||||
accessSecretStoreCondition,
|
||||
lockRewardCondition
|
||||
} = this.ocean.keeper.conditions
|
||||
const { escrowReward, accessSecretStoreCondition, lockRewardCondition } = this.ocean.keeper.conditions
|
||||
|
||||
const conditionIdAccess = await accessSecretStoreCondition.generateIdHash(
|
||||
agreementId,
|
||||
did,
|
||||
consumer
|
||||
)
|
||||
const conditionIdAccess = await accessSecretStoreCondition.generateIdHash(agreementId, did, consumer)
|
||||
const conditionIdLock = await lockRewardCondition.generateIdHash(
|
||||
agreementId,
|
||||
escrowReward.getAddress(),
|
||||
|
@ -4,12 +4,7 @@ import { MetaData } from '../ddo/MetaData'
|
||||
import { Service } from '../ddo/Service'
|
||||
import Account from './Account'
|
||||
import DID from './DID'
|
||||
import {
|
||||
fillConditionsWithDDO,
|
||||
SubscribablePromise,
|
||||
generateId,
|
||||
zeroX
|
||||
} from '../utils'
|
||||
import { fillConditionsWithDDO, SubscribablePromise, generateId, zeroX } from '../utils'
|
||||
import { Instantiable, InstantiableConfig } from '../Instantiable.abstract'
|
||||
|
||||
export enum CreateProgressStep {
|
||||
@ -38,9 +33,7 @@ export class OceanAssets extends Instantiable {
|
||||
* Returns the instance of OceanAssets.
|
||||
* @return {Promise<OceanAssets>}
|
||||
*/
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<OceanAssets> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<OceanAssets> {
|
||||
const instance = new OceanAssets()
|
||||
instance.setInstanceConfig(config)
|
||||
|
||||
@ -53,9 +46,7 @@ export class OceanAssets extends Instantiable {
|
||||
* @return {Promise<DDO>}
|
||||
*/
|
||||
public async resolve(did: string): Promise<DDO> {
|
||||
const {
|
||||
serviceEndpoint
|
||||
} = await this.ocean.keeper.didRegistry.getAttributesByDid(did)
|
||||
const { serviceEndpoint } = await this.ocean.keeper.didRegistry.getAttributesByDid(did)
|
||||
return this.ocean.aquarius.retrieveDDOByUrl(serviceEndpoint)
|
||||
}
|
||||
|
||||
@ -79,11 +70,7 @@ export class OceanAssets extends Instantiable {
|
||||
|
||||
this.logger.log('Encrypting files')
|
||||
observer.next(CreateProgressStep.EncryptingFiles)
|
||||
const encryptedFiles = await this.ocean.secretStore.encrypt(
|
||||
did.getId(),
|
||||
metadata.main.files,
|
||||
publisher
|
||||
)
|
||||
const encryptedFiles = await this.ocean.secretStore.encrypt(did.getId(), metadata.main.files, publisher)
|
||||
this.logger.log('Files encrypted')
|
||||
observer.next(CreateProgressStep.FilesEncrypted)
|
||||
|
||||
@ -139,13 +126,11 @@ export class OceanAssets extends Instantiable {
|
||||
...metadata.main,
|
||||
contentUrls: undefined,
|
||||
encryptedFiles,
|
||||
files: metadata.main.files.map(
|
||||
(file, index) => ({
|
||||
...file,
|
||||
index,
|
||||
url: undefined
|
||||
})
|
||||
)
|
||||
files: metadata.main.files.map((file, index) => ({
|
||||
...file,
|
||||
index,
|
||||
url: undefined
|
||||
}))
|
||||
} as any
|
||||
}
|
||||
},
|
||||
@ -153,10 +138,7 @@ export class OceanAssets extends Instantiable {
|
||||
]
|
||||
// Remove duplications
|
||||
.reverse()
|
||||
.filter(
|
||||
({ type }, i, list) =>
|
||||
list.findIndex(({ type: t }) => t === type) === i
|
||||
)
|
||||
.filter(({ type }, i, list) => list.findIndex(({ type: t }) => t === type) === i)
|
||||
.reverse()
|
||||
// Adding index
|
||||
.map(_ => ({
|
||||
@ -173,11 +155,7 @@ export class OceanAssets extends Instantiable {
|
||||
ddo.addChecksum()
|
||||
this.logger.log('Generating proof')
|
||||
observer.next(CreateProgressStep.GeneratingProof)
|
||||
await ddo.addProof(
|
||||
this.ocean,
|
||||
publisher.getId(),
|
||||
publisher.getPassword()
|
||||
)
|
||||
await ddo.addProof(this.ocean, publisher.getId(), publisher.getPassword())
|
||||
this.logger.log('Proof generated')
|
||||
observer.next(CreateProgressStep.ProofGenerated)
|
||||
|
||||
@ -242,16 +220,12 @@ export class OceanAssets extends Instantiable {
|
||||
const { serviceEndpoint } = accessService
|
||||
|
||||
if (!serviceEndpoint) {
|
||||
throw new Error(
|
||||
'Consume asset failed, service definition is missing the `serviceEndpoint`.'
|
||||
)
|
||||
throw new Error('Consume asset failed, service definition is missing the `serviceEndpoint`.')
|
||||
}
|
||||
|
||||
this.logger.log('Consuming files')
|
||||
|
||||
resultPath = resultPath
|
||||
? `${resultPath}/datafile.${ddo.shortId()}.${serviceIndex}/`
|
||||
: undefined
|
||||
resultPath = resultPath ? `${resultPath}/datafile.${ddo.shortId()}.${serviceIndex}/` : undefined
|
||||
|
||||
if (!useSecretStore) {
|
||||
await this.ocean.brizo.consumeService(
|
||||
@ -265,16 +239,13 @@ export class OceanAssets extends Instantiable {
|
||||
} else {
|
||||
const files = await this.ocean.secretStore.decrypt(
|
||||
did,
|
||||
ddo.findServiceByType('metadata').attributes.main
|
||||
.encryptedFiles,
|
||||
ddo.findServiceByType('metadata').attributes.main.encryptedFiles,
|
||||
consumerAccount,
|
||||
ddo.findServiceByType('authorization').serviceEndpoint
|
||||
)
|
||||
const downloads = files
|
||||
.filter(({ index: i }) => index === -1 || index === i)
|
||||
.map(({ url, index: i }) =>
|
||||
this.ocean.utils.fetch.downloadFile(url, resultPath, i)
|
||||
)
|
||||
.map(({ url, index: i }) => this.ocean.utils.fetch.downloadFile(url, resultPath, i))
|
||||
await Promise.all(downloads)
|
||||
}
|
||||
this.logger.log('Files consumed')
|
||||
@ -293,11 +264,7 @@ export class OceanAssets extends Instantiable {
|
||||
* @param {Account} consumer Consumer account.
|
||||
* @return {Promise<string>} Returns Agreement ID
|
||||
*/
|
||||
public order(
|
||||
did: string,
|
||||
index: number,
|
||||
consumer: Account
|
||||
): SubscribablePromise<OrderProgressStep, string> {
|
||||
public order(did: string, index: number, consumer: Account): SubscribablePromise<OrderProgressStep, string> {
|
||||
return new SubscribablePromise(async observer => {
|
||||
const oceanAgreements = this.ocean.agreements
|
||||
|
||||
@ -305,8 +272,7 @@ export class OceanAssets extends Instantiable {
|
||||
const ddo = await this.resolve(did)
|
||||
|
||||
const { keeper } = this.ocean
|
||||
const templateName = ddo.findServiceByType('access')
|
||||
.serviceAgreementTemplate.contractName
|
||||
const templateName = ddo.findServiceByType('access').serviceAgreementTemplate.contractName
|
||||
const template = keeper.getTemplateByName(templateName)
|
||||
const accessCondition = keeper.conditions.accessSecretStoreCondition
|
||||
|
||||
@ -321,16 +287,10 @@ export class OceanAssets extends Instantiable {
|
||||
|
||||
this.logger.log('Locking payment')
|
||||
|
||||
const accessGranted = accessCondition
|
||||
.getConditionFulfilledEvent(agreementId)
|
||||
.once()
|
||||
const accessGranted = accessCondition.getConditionFulfilledEvent(agreementId).once()
|
||||
|
||||
observer.next(OrderProgressStep.LockingPayment)
|
||||
const paid = await oceanAgreements.conditions.lockReward(
|
||||
agreementId,
|
||||
attributes.main.price,
|
||||
consumer
|
||||
)
|
||||
const paid = await oceanAgreements.conditions.lockReward(agreementId, attributes.main.price, consumer)
|
||||
observer.next(OrderProgressStep.LockedPayment)
|
||||
|
||||
if (paid) {
|
||||
@ -350,14 +310,7 @@ export class OceanAssets extends Instantiable {
|
||||
|
||||
observer.next(OrderProgressStep.CreatingAgreement)
|
||||
this.logger.log('Creating agreement')
|
||||
await oceanAgreements.create(
|
||||
did,
|
||||
agreementId,
|
||||
index,
|
||||
undefined,
|
||||
consumer,
|
||||
consumer
|
||||
)
|
||||
await oceanAgreements.create(did, agreementId, index, undefined, consumer, consumer)
|
||||
this.logger.log('Agreement created')
|
||||
|
||||
try {
|
||||
@ -379,15 +332,10 @@ export class OceanAssets extends Instantiable {
|
||||
const ddo = await this.resolve(did)
|
||||
const checksum = ddo.getChecksum()
|
||||
const { creator, signatureValue } = ddo.proof
|
||||
const signer = await this.ocean.utils.signature.verifyText(
|
||||
checksum,
|
||||
signatureValue
|
||||
)
|
||||
const signer = await this.ocean.utils.signature.verifyText(checksum, signatureValue)
|
||||
|
||||
if (signer.toLowerCase() !== creator.toLowerCase()) {
|
||||
this.logger.warn(
|
||||
`Owner of ${ddo.id} doesn't match. Expected ${creator} instead of ${signer}.`
|
||||
)
|
||||
this.logger.warn(`Owner of ${ddo.id} doesn't match. Expected ${creator} instead of ${signer}.`)
|
||||
}
|
||||
|
||||
return creator
|
||||
@ -408,9 +356,9 @@ export class OceanAssets extends Instantiable {
|
||||
* @return {Promise<string[]>} List of DIDs.
|
||||
*/
|
||||
public async consumerAssets(consumer: string) {
|
||||
return (await this.ocean.keeper.conditions.accessSecretStoreCondition.getGrantedDidByConsumer(
|
||||
consumer
|
||||
)).map(({ did }) => did)
|
||||
return (await this.ocean.keeper.conditions.accessSecretStoreCondition.getGrantedDidByConsumer(consumer)).map(
|
||||
({ did }) => did
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -13,9 +13,7 @@ export class OceanAuth extends Instantiable {
|
||||
* Returns the instance of OceanAuth.
|
||||
* @return {Promise<OceanAuth>}
|
||||
*/
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<OceanAuth> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<OceanAuth> {
|
||||
const instance = new OceanAuth()
|
||||
instance.setInstanceConfig(config)
|
||||
|
||||
@ -32,11 +30,7 @@ export class OceanAuth extends Instantiable {
|
||||
const message = `${this.getMessage()}\n${time}`
|
||||
|
||||
try {
|
||||
const signature = await this.ocean.utils.signature.signText(
|
||||
message,
|
||||
account.getId(),
|
||||
account.getPassword()
|
||||
)
|
||||
const signature = await this.ocean.utils.signature.signText(message, account.getId(), account.getPassword())
|
||||
|
||||
return `${signature}-${time}`
|
||||
} catch {
|
||||
@ -59,9 +53,7 @@ export class OceanAuth extends Instantiable {
|
||||
return `0x${'0'.repeat(40)}`
|
||||
}
|
||||
|
||||
return this.web3.utils.toChecksumAddress(
|
||||
await this.ocean.utils.signature.verifyText(message, signature)
|
||||
)
|
||||
return this.web3.utils.toChecksumAddress(await this.ocean.utils.signature.verifyText(message, signature))
|
||||
}
|
||||
|
||||
/**
|
||||
@ -129,9 +121,7 @@ export class OceanAuth extends Instantiable {
|
||||
try {
|
||||
localStorage.getItem('')
|
||||
} catch {
|
||||
throw new Error(
|
||||
'LocalStorage is not supported. This feature is only available on browsers.'
|
||||
)
|
||||
throw new Error('LocalStorage is not supported. This feature is only available on browsers.')
|
||||
}
|
||||
return localStorage
|
||||
}
|
||||
|
@ -13,9 +13,7 @@ export class OceanSecretStore extends Instantiable {
|
||||
* Returns the instance of OceanSecretStore.
|
||||
* @return {Promise<OceanSecretStore>}
|
||||
*/
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<OceanSecretStore> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<OceanSecretStore> {
|
||||
const instance = new OceanSecretStore()
|
||||
instance.setInstanceConfig(config)
|
||||
|
||||
@ -30,25 +28,12 @@ export class OceanSecretStore extends Instantiable {
|
||||
* @param {string} publisher Publisher account.
|
||||
* @return {Promise<string>} Encrypted text.
|
||||
*/
|
||||
public async encrypt(
|
||||
did: string,
|
||||
document: any,
|
||||
publisher: Account
|
||||
): Promise<string> {
|
||||
public async encrypt(did: string, document: any, publisher: Account): Promise<string> {
|
||||
const signature =
|
||||
(await publisher.getToken()) ||
|
||||
(await this.ocean.utils.signature.signText(
|
||||
noDidPrefixed(did),
|
||||
publisher.getId(),
|
||||
publisher.getPassword()
|
||||
))
|
||||
(await this.ocean.utils.signature.signText(noDidPrefixed(did), publisher.getId(), publisher.getPassword()))
|
||||
|
||||
return this.ocean.brizo.encrypt(
|
||||
noDidPrefixed(did),
|
||||
signature,
|
||||
document,
|
||||
publisher.getId()
|
||||
)
|
||||
return this.ocean.brizo.encrypt(noDidPrefixed(did), signature, document, publisher.getId())
|
||||
}
|
||||
|
||||
/**
|
||||
@ -59,16 +44,8 @@ export class OceanSecretStore extends Instantiable {
|
||||
* @param {string} consumer cONSUMER account.
|
||||
* @return {Promise<string>} Encrypted text.
|
||||
*/
|
||||
public async decrypt(
|
||||
did: string,
|
||||
content: string,
|
||||
consumer?: Account,
|
||||
secretStoreUrl?: string
|
||||
): Promise<any> {
|
||||
return this.getSecretStoreByAccount(
|
||||
consumer,
|
||||
secretStoreUrl
|
||||
).decryptDocument(noDidPrefixed(did), content)
|
||||
public async decrypt(did: string, content: string, consumer?: Account, secretStoreUrl?: string): Promise<any> {
|
||||
return this.getSecretStoreByAccount(consumer, secretStoreUrl).decryptDocument(noDidPrefixed(did), content)
|
||||
}
|
||||
|
||||
private getSecretStoreByAccount(account: Account, secretStoreUrl?: string) {
|
||||
@ -86,13 +63,7 @@ export class OceanSecretStore extends Instantiable {
|
||||
}
|
||||
|
||||
private getSecretStore(config: SecretStoreConfig): SecretStore {
|
||||
const {
|
||||
secretStoreUri,
|
||||
parityUri,
|
||||
password,
|
||||
address,
|
||||
threshold
|
||||
} = config
|
||||
const { secretStoreUri, parityUri, password, address, threshold } = config
|
||||
config = { secretStoreUri, parityUri, password, address, threshold }
|
||||
|
||||
return new SecretStore(config)
|
||||
|
@ -9,9 +9,7 @@ export class OceanTokens extends Instantiable {
|
||||
* Returns the instance of OceanTokens.
|
||||
* @return {Promise<OceanTokens>}
|
||||
*/
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<OceanTokens> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<OceanTokens> {
|
||||
const instance = new OceanTokens()
|
||||
instance.setInstanceConfig(config)
|
||||
|
||||
@ -25,11 +23,7 @@ export class OceanTokens extends Instantiable {
|
||||
* @param {Account} from Sender account address.
|
||||
* @return {Promise<boolean>} Success,
|
||||
*/
|
||||
public async transfer(
|
||||
to: string,
|
||||
amount: number,
|
||||
from: Account
|
||||
): Promise<boolean> {
|
||||
public async transfer(to: string, amount: number, from: Account): Promise<boolean> {
|
||||
this.ocean.keeper.token.transfer(to, amount, from.getId())
|
||||
return true
|
||||
}
|
||||
|
@ -42,9 +42,7 @@ export class OceanVersions extends Instantiable {
|
||||
* Returns the instance of OceanVersions.
|
||||
* @return {Promise<OceanVersions>}
|
||||
*/
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<OceanVersions> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<OceanVersions> {
|
||||
const instance = new OceanVersions()
|
||||
instance.setInstanceConfig(config)
|
||||
|
||||
@ -99,10 +97,7 @@ export class OceanVersions extends Instantiable {
|
||||
|
||||
// Aquarius
|
||||
try {
|
||||
const {
|
||||
software: name,
|
||||
version
|
||||
} = await this.ocean.aquarius.getVersionInfo()
|
||||
const { software: name, version } = await this.ocean.aquarius.getVersionInfo()
|
||||
versions.aquarius = {
|
||||
name,
|
||||
status: OceanPlatformTechStatus.Working,
|
||||
@ -124,9 +119,7 @@ export class OceanVersions extends Instantiable {
|
||||
.reduce((acc, network) => ({ ...acc, [network]: true }), {})
|
||||
|
||||
let contractStatus = true
|
||||
const contractList = techs
|
||||
.map(({ contracts }) => contracts)
|
||||
.filter(_ => !!_)
|
||||
const contractList = techs.map(({ contracts }) => contracts).filter(_ => !!_)
|
||||
Array.from(contractList.map(Object.keys))
|
||||
.reduce((acc, _) => [...acc, ..._], [])
|
||||
.filter((_, i, list) => list.indexOf(_) === i)
|
||||
@ -146,9 +139,7 @@ export class OceanVersions extends Instantiable {
|
||||
})
|
||||
|
||||
versions.status = {
|
||||
ok: !techs.find(
|
||||
({ status }) => status !== OceanPlatformTechStatus.Working
|
||||
),
|
||||
ok: !techs.find(({ status }) => status !== OceanPlatformTechStatus.Working),
|
||||
network: Object.keys(networks).length === 1,
|
||||
contracts: contractStatus
|
||||
}
|
||||
|
@ -12,9 +12,7 @@ export class OceanUtils extends Instantiable {
|
||||
* Returns the instance of OceanUtils.
|
||||
* @return {Promise<OceanUtils>}
|
||||
*/
|
||||
public static async getInstance(
|
||||
config: InstantiableConfig
|
||||
): Promise<OceanUtils> {
|
||||
public static async getInstance(config: InstantiableConfig): Promise<OceanUtils> {
|
||||
const instance = new OceanUtils()
|
||||
instance.setInstanceConfig(config)
|
||||
|
||||
|
@ -19,14 +19,8 @@ export class ServiceAgreement extends Instantiable {
|
||||
consumer: Account
|
||||
): Promise<string> {
|
||||
const service = ddo.findServiceById<'access'>(index)
|
||||
const timelockValues: number[] = this.getTimeValuesFromService(
|
||||
service,
|
||||
'timelock'
|
||||
)
|
||||
const timeoutValues: number[] = this.getTimeValuesFromService(
|
||||
service,
|
||||
'timeout'
|
||||
)
|
||||
const timelockValues: number[] = this.getTimeValuesFromService(service, 'timelock')
|
||||
const timeoutValues: number[] = this.getTimeValuesFromService(service, 'timeout')
|
||||
|
||||
if (!service.templateId) {
|
||||
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')
|
||||
}
|
||||
|
||||
private getTimeValuesFromService(
|
||||
service: ServiceAccess,
|
||||
type: 'timeout' | 'timelock'
|
||||
): number[] {
|
||||
private getTimeValuesFromService(service: ServiceAccess, type: 'timeout' | 'timelock'): number[] {
|
||||
const timeoutValues: number[] = service.serviceAgreementTemplate.conditions.map(
|
||||
(condition: ServiceAgreementTemplateCondition) => condition[type]
|
||||
)
|
||||
|
@ -6,15 +6,8 @@ export class SignatureUtils extends Instantiable {
|
||||
this.setInstanceConfig(config)
|
||||
}
|
||||
|
||||
public async signText(
|
||||
text: string,
|
||||
publicKey: string,
|
||||
password?: string
|
||||
): Promise<string> {
|
||||
const isMetaMask =
|
||||
this.web3 &&
|
||||
this.web3.currentProvider &&
|
||||
this.web3.currentProvider.isMetaMask
|
||||
public async signText(text: string, publicKey: string, password?: string): Promise<string> {
|
||||
const isMetaMask = this.web3 && this.web3.currentProvider && this.web3.currentProvider.isMetaMask
|
||||
try {
|
||||
return await this.web3.eth.personal.sign(text, publicKey, password)
|
||||
} catch (e) {
|
||||
|
@ -43,20 +43,14 @@ export class WebServiceConnector extends Instantiable {
|
||||
})
|
||||
}
|
||||
|
||||
public async downloadFile(
|
||||
url: string,
|
||||
destination?: string,
|
||||
index?: number
|
||||
): Promise<string> {
|
||||
public async downloadFile(url: string, destination?: string, index?: number): Promise<string> {
|
||||
const response = await this.get(url)
|
||||
if (!response.ok) {
|
||||
throw new Error('Response error.')
|
||||
}
|
||||
let filename
|
||||
try {
|
||||
filename = response.headers
|
||||
.get('content-disposition')
|
||||
.match(/attachment;filename=(.+)/)[1]
|
||||
filename = response.headers.get('content-disposition').match(/attachment;filename=(.+)/)[1]
|
||||
} catch {
|
||||
try {
|
||||
filename = url.split('/').pop()
|
||||
@ -69,9 +63,7 @@ export class WebServiceConnector extends Instantiable {
|
||||
// eslint-disable-next-line no-async-promise-executor
|
||||
await new Promise(async (resolve, reject) => {
|
||||
fs.mkdirSync(destination, { recursive: true })
|
||||
const fileStream = fs.createWriteStream(
|
||||
`${destination}${filename}`
|
||||
)
|
||||
const fileStream = fs.createWriteStream(`${destination}${filename}`)
|
||||
response.body.pipe(fileStream)
|
||||
response.body.on('error', reject)
|
||||
fileStream.on('finish', resolve)
|
||||
|
12
src/squid.ts
12
src/squid.ts
@ -24,14 +24,4 @@ export {
|
||||
export { AgreementTemplate } from './keeper/contracts/templates'
|
||||
export { Condition, ConditionState } from './keeper/contracts/conditions'
|
||||
|
||||
export {
|
||||
Ocean,
|
||||
Account,
|
||||
Config,
|
||||
DID,
|
||||
Logger,
|
||||
Keeper,
|
||||
conditions,
|
||||
templates,
|
||||
utils
|
||||
}
|
||||
export { Ocean, Account, Config, DID, Logger, Keeper, conditions, templates, utils }
|
||||
|
@ -4,11 +4,7 @@ import { LoggerInstance } from './Logger'
|
||||
export const zeroX = (input: string) => zeroXTransformer(input, true)
|
||||
export const noZeroX = (input: string) => zeroXTransformer(input, false)
|
||||
export function zeroXTransformer(input: string = '', zeroOutput: boolean) {
|
||||
const { valid, output } = inputMatch(
|
||||
input,
|
||||
/^(?:0x)*([a-f0-9]+)$/i,
|
||||
'zeroXTransformer'
|
||||
)
|
||||
const { valid, output } = inputMatch(input, /^(?:0x)*([a-f0-9]+)$/i, 'zeroXTransformer')
|
||||
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 noDidPrefixed = (input: string) => didTransformer(input, false)
|
||||
export function didTransformer(input: string = '', prefixOutput: boolean) {
|
||||
const { valid, output } = inputMatch(
|
||||
input,
|
||||
/^(?:0x|did:op:)*([a-f0-9]{64})$/i,
|
||||
'didTransformer'
|
||||
)
|
||||
const { valid, output } = inputMatch(input, /^(?:0x|did:op:)*([a-f0-9]{64})$/i, 'didTransformer')
|
||||
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))
|
||||
|
||||
// Shared functions
|
||||
function inputMatch(
|
||||
input: string,
|
||||
regexp: RegExp,
|
||||
conversorName: string
|
||||
): { valid: boolean; output: string } {
|
||||
function inputMatch(input: string, regexp: RegExp, conversorName: string): { valid: boolean; output: string } {
|
||||
if (typeof input !== 'string') {
|
||||
LoggerInstance.debug('Not input string:')
|
||||
LoggerInstance.debug(input)
|
||||
throw new Error(
|
||||
`[${conversorName}] Expected string, input type: ${typeof input}`
|
||||
)
|
||||
throw new Error(`[${conversorName}] Expected string, input type: ${typeof input}`)
|
||||
}
|
||||
const match = input.match(regexp)
|
||||
if (!match) {
|
||||
|
@ -1,8 +1,5 @@
|
||||
import { DDO } from '../ddo/DDO'
|
||||
import {
|
||||
ServiceAgreementTemplateCondition,
|
||||
ServiceAgreementTemplateParameter
|
||||
} from '../ddo/ServiceAgreementTemplate'
|
||||
import { ServiceAgreementTemplateCondition, ServiceAgreementTemplateParameter } from '../ddo/ServiceAgreementTemplate'
|
||||
|
||||
function fillParameterWithDDO(
|
||||
parameter: ServiceAgreementTemplateParameter,
|
||||
@ -12,9 +9,7 @@ function fillParameterWithDDO(
|
||||
switch (name) {
|
||||
case 'amount':
|
||||
case 'price':
|
||||
return String(
|
||||
ddo.findServiceByType('metadata').attributes.main.price
|
||||
)
|
||||
return String(ddo.findServiceByType('metadata').attributes.main.price)
|
||||
case 'assetId':
|
||||
case 'documentId':
|
||||
case 'documentKeyId':
|
||||
|
@ -8,9 +8,7 @@ const zipObject = (keys = [], values = []) => {
|
||||
)
|
||||
}
|
||||
|
||||
export const objectPromiseAll = async (obj: {
|
||||
[key: string]: Promise<any>
|
||||
}) => {
|
||||
export const objectPromiseAll = async (obj: { [key: string]: Promise<any> }) => {
|
||||
const keys = Object.keys(obj)
|
||||
const result = await Promise.all(Object.values(obj))
|
||||
return zipObject(keys, result)
|
||||
|
@ -7,11 +7,7 @@ export class SubscribableObserver<T, P> {
|
||||
onError?: (error: any) => void
|
||||
}>()
|
||||
|
||||
public subscribe(
|
||||
onNext?: (next: T) => void,
|
||||
onComplete?: (complete: P) => void,
|
||||
onError?: (error: any) => void
|
||||
) {
|
||||
public subscribe(onNext?: (next: T) => void, onComplete?: (complete: P) => void, onError?: (error: any) => void) {
|
||||
if (this.completed) {
|
||||
throw new Error('Observer completed.')
|
||||
}
|
||||
@ -40,9 +36,7 @@ export class SubscribableObserver<T, P> {
|
||||
private emit(type: 'onNext' | 'onComplete' | 'onError', value: any) {
|
||||
Array.from(this.subscriptions)
|
||||
.map(subscription => subscription[type])
|
||||
.filter(
|
||||
(callback: any) => callback && typeof callback === 'function'
|
||||
)
|
||||
.filter((callback: any) => callback && typeof callback === 'function')
|
||||
.forEach((callback: any) => callback(value))
|
||||
}
|
||||
|
||||
|
@ -12,9 +12,7 @@ export class SubscribablePromise<T extends any, P extends any> {
|
||||
this
|
||||
)
|
||||
|
||||
constructor(
|
||||
executor: (observer: SubscribableObserver<T, P>) => void | Promise<P>
|
||||
) {
|
||||
constructor(executor: (observer: SubscribableObserver<T, P>) => void | Promise<P>) {
|
||||
// Defear
|
||||
setTimeout(() => this.init(executor), 1)
|
||||
}
|
||||
@ -28,10 +26,7 @@ export class SubscribablePromise<T extends any, P extends any> {
|
||||
return this
|
||||
}
|
||||
|
||||
public then(
|
||||
onfulfilled?: (value: P) => any,
|
||||
onrejected?: (error: any) => any
|
||||
) {
|
||||
public then(onfulfilled?: (value: P) => any, onrejected?: (error: any) => any) {
|
||||
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)
|
||||
}
|
||||
|
||||
private init(
|
||||
executor: (observer: SubscribableObserver<T, P>) => void | Promise<P>
|
||||
) {
|
||||
private init(executor: (observer: SubscribableObserver<T, P>) => void | Promise<P>) {
|
||||
const execution = executor(this.observer)
|
||||
|
||||
Promise.resolve(execution as any)
|
||||
|
@ -17,12 +17,12 @@ describe('Aquarius', () => {
|
||||
let ocean: Ocean
|
||||
let aquarius: Aquarius
|
||||
/* eslint-disable @typescript-eslint/camelcase */
|
||||
const getResults = (
|
||||
results: DDO[],
|
||||
page = 0,
|
||||
total_pages = 1,
|
||||
total_results = 1
|
||||
) => ({ results, page, total_pages, total_results })
|
||||
const getResults = (results: DDO[], page = 0, total_pages = 1, total_results = 1) => ({
|
||||
results,
|
||||
page,
|
||||
total_pages,
|
||||
total_results
|
||||
})
|
||||
/* eslint-enable @typescript-eslint/camelcase */
|
||||
|
||||
beforeEach(async () => {
|
||||
@ -48,9 +48,7 @@ describe('Aquarius', () => {
|
||||
} as SearchQuery
|
||||
|
||||
it('should query metadata', async () => {
|
||||
spy.on(ocean.utils.fetch, 'post', () =>
|
||||
reponsify(getResults([new DDO()]))
|
||||
)
|
||||
spy.on(ocean.utils.fetch, 'post', () => reponsify(getResults([new DDO()])))
|
||||
|
||||
const result = await aquarius.queryMetadata(query)
|
||||
assert.typeOf(result.results, 'array')
|
||||
@ -61,9 +59,7 @@ describe('Aquarius', () => {
|
||||
})
|
||||
|
||||
it('should query metadata and return real ddo', async () => {
|
||||
spy.on(ocean.utils.fetch, 'post', () =>
|
||||
reponsify(getResults([new DDO()]))
|
||||
)
|
||||
spy.on(ocean.utils.fetch, 'post', () => reponsify(getResults([new DDO()])))
|
||||
|
||||
const result = await aquarius.queryMetadata(query)
|
||||
assert.typeOf(result.results, 'array')
|
||||
@ -86,9 +82,7 @@ describe('Aquarius', () => {
|
||||
} as SearchQuery
|
||||
|
||||
it('should query metadata by text', async () => {
|
||||
spy.on(ocean.utils.fetch, 'get', () =>
|
||||
reponsify(getResults([new DDO()]))
|
||||
)
|
||||
spy.on(ocean.utils.fetch, 'get', () => reponsify(getResults([new DDO()])))
|
||||
|
||||
const result = await aquarius.queryMetadataByText(query)
|
||||
assert.typeOf(result.results, 'array')
|
||||
@ -99,9 +93,7 @@ describe('Aquarius', () => {
|
||||
})
|
||||
|
||||
it('should query metadata and return real ddo', async () => {
|
||||
spy.on(ocean.utils.fetch, 'get', () =>
|
||||
reponsify(getResults([new DDO()]))
|
||||
)
|
||||
spy.on(ocean.utils.fetch, 'get', () => reponsify(getResults([new DDO()])))
|
||||
|
||||
const result = await aquarius.queryMetadataByText(query)
|
||||
assert.typeOf(result.results, 'array')
|
||||
|
@ -46,8 +46,7 @@ describe('DDO', () => {
|
||||
},
|
||||
{
|
||||
type: 'CredentialRepositoryService',
|
||||
serviceEndpoint:
|
||||
'https://repository.example.com/service/8377464'
|
||||
serviceEndpoint: 'https://repository.example.com/service/8377464'
|
||||
},
|
||||
{
|
||||
type: 'XdiService',
|
||||
@ -55,8 +54,7 @@ describe('DDO', () => {
|
||||
},
|
||||
{
|
||||
type: 'HubService',
|
||||
serviceEndpoint:
|
||||
'https://hub.example.com/.identity/did:op:0123456789abcdef/'
|
||||
serviceEndpoint: 'https://hub.example.com/.identity/did:op:0123456789abcdef/'
|
||||
},
|
||||
{
|
||||
type: 'MessagingService',
|
||||
@ -89,8 +87,7 @@ describe('DDO', () => {
|
||||
{
|
||||
type: 'metadata',
|
||||
index: 0,
|
||||
serviceEndpoint:
|
||||
'http://myaquarius.org/api/v1/provider/assets/metadata/{did}',
|
||||
serviceEndpoint: 'http://myaquarius.org/api/v1/provider/assets/metadata/{did}',
|
||||
attributes: {
|
||||
main: {
|
||||
name: 'UK Weather information 2011',
|
||||
@ -106,8 +103,7 @@ describe('DDO', () => {
|
||||
checksum: 'efb2c764274b745f5fc37f97c6b0e761',
|
||||
contentLength: 4535431,
|
||||
contentType: 'application/json',
|
||||
resourceId:
|
||||
'access-log2018-02-13-15-17-29-18386C502CAEA932'
|
||||
resourceId: 'access-log2018-02-13-15-17-29-18386C502CAEA932'
|
||||
},
|
||||
{
|
||||
index: 1,
|
||||
@ -128,11 +124,9 @@ describe('DDO', () => {
|
||||
schema: 'Binary Voting'
|
||||
},
|
||||
additionalInformation: {
|
||||
description:
|
||||
'Weather information of UK including temperature and humidity',
|
||||
description: 'Weather information of UK including temperature and humidity',
|
||||
copyrightHolder: 'Met Office',
|
||||
workExample:
|
||||
'423432fsd,51.509865,-0.118092,2011-01-01T10:55:11+00:00,7.2,68',
|
||||
workExample: '423432fsd,51.509865,-0.118092,2011-01-01T10:55:11+00:00,7.2,68',
|
||||
links: [
|
||||
{
|
||||
sample1:
|
||||
@ -143,29 +137,20 @@ describe('DDO', () => {
|
||||
'http://data.ceda.ac.uk/badc/ukcp09/data/gridded-land-obs/gridded-land-obs-averages-25km/'
|
||||
},
|
||||
{
|
||||
fieldsDescription:
|
||||
'http://data.ceda.ac.uk/badc/ukcp09/'
|
||||
fieldsDescription: 'http://data.ceda.ac.uk/badc/ukcp09/'
|
||||
}
|
||||
],
|
||||
inLanguage: 'en',
|
||||
categories: ['Economy', 'Data Science'],
|
||||
tags: [
|
||||
'weather',
|
||||
'uk',
|
||||
'2011',
|
||||
'temperature',
|
||||
'humidity'
|
||||
],
|
||||
tags: ['weather', 'uk', '2011', 'temperature', 'humidity'],
|
||||
updateFrequency: 'yearly',
|
||||
structuredMarkup: [
|
||||
{
|
||||
uri:
|
||||
'http://skos.um.es/unescothes/C01194/jsonld',
|
||||
uri: 'http://skos.um.es/unescothes/C01194/jsonld',
|
||||
mediaType: 'application/ld+json'
|
||||
},
|
||||
{
|
||||
uri:
|
||||
'http://skos.um.es/unescothes/C01194/turtle',
|
||||
uri: 'http://skos.um.es/unescothes/C01194/turtle',
|
||||
mediaType: 'text/turtle'
|
||||
}
|
||||
]
|
||||
@ -234,10 +219,7 @@ describe('DDO', () => {
|
||||
assert.instanceOf(ddo, DDO)
|
||||
|
||||
assert.equal(ddo.id, testDDO.id)
|
||||
assert.equal(
|
||||
ddo.publicKey[0].publicKeyPem,
|
||||
testDDO.publicKey[0].publicKeyPem
|
||||
)
|
||||
assert.equal(ddo.publicKey[0].publicKeyPem, testDDO.publicKey[0].publicKeyPem)
|
||||
})
|
||||
|
||||
it('should properly deserialize from json file', async () => {
|
||||
@ -245,10 +227,7 @@ describe('DDO', () => {
|
||||
assert(ddo)
|
||||
|
||||
assert.equal(ddo.id, jsonDDO.id)
|
||||
assert.equal(
|
||||
ddo.publicKey[0].publicKeyPem,
|
||||
jsonDDO.publicKey[0].publicKeyPem
|
||||
)
|
||||
assert.equal(ddo.publicKey[0].publicKeyPem, jsonDDO.publicKey[0].publicKeyPem)
|
||||
})
|
||||
})
|
||||
|
||||
@ -257,10 +236,7 @@ describe('DDO', () => {
|
||||
const ddo = new DDO(testDDO)
|
||||
const checksum = ddo.getChecksum()
|
||||
|
||||
assert.equal(
|
||||
checksum,
|
||||
'0x15f27a7a3c7b15d2b06dec7347c6b8da168adddd7df51a8ebbbe87b59b80049b'
|
||||
)
|
||||
assert.equal(checksum, '0x15f27a7a3c7b15d2b06dec7347c6b8da168adddd7df51a8ebbbe87b59b80049b')
|
||||
})
|
||||
})
|
||||
|
||||
@ -269,11 +245,7 @@ describe('DDO', () => {
|
||||
const signature = `0x${'a'.repeat(130)}`
|
||||
|
||||
it('should properly generate the proof', async () => {
|
||||
const signTextSpy = spy.on(
|
||||
ocean.utils.signature,
|
||||
'signText',
|
||||
() => signature
|
||||
)
|
||||
const signTextSpy = spy.on(ocean.utils.signature, 'signText', () => signature)
|
||||
const ddo = new DDO(testDDO)
|
||||
const checksum = ddo.getChecksum()
|
||||
const proof = await ddo.generateProof(ocean, publicKey)
|
||||
@ -298,11 +270,7 @@ describe('DDO', () => {
|
||||
signaturValue: 'test'
|
||||
} as any
|
||||
const ddo = new DDO(testDDO)
|
||||
const generateProofSpy = spy.on(
|
||||
ddo,
|
||||
'generateProof',
|
||||
() => fakeProof
|
||||
)
|
||||
const generateProofSpy = spy.on(ddo, 'generateProof', () => fakeProof)
|
||||
await ddo.addProof(web3, publicKey)
|
||||
|
||||
assert.equal(ddo.proof, fakeProof)
|
||||
|
@ -30,11 +30,9 @@ describe('ContractWrapperBase', () => {
|
||||
})
|
||||
|
||||
it('should fail to call on an unknown contract function', done => {
|
||||
wrappedContract
|
||||
.sendMock('balanceOfxxx', '0x00', ['0x00'])
|
||||
.catch(() => {
|
||||
done()
|
||||
})
|
||||
wrappedContract.sendMock('balanceOfxxx', '0x00', ['0x00']).catch(() => {
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should fail to call on an contract function with wrong set of parameters', done => {
|
||||
@ -46,11 +44,9 @@ describe('ContractWrapperBase', () => {
|
||||
|
||||
describe('#send()', () => {
|
||||
it('should fail to call on an unknown contract function', done => {
|
||||
wrappedContract
|
||||
.sendMock('transferxxx', accounts[0].getId(), [])
|
||||
.catch(() => {
|
||||
done()
|
||||
})
|
||||
wrappedContract.sendMock('transferxxx', accounts[0].getId(), []).catch(() => {
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
@ -17,17 +17,12 @@ describe('ContractEvent', () => {
|
||||
eventHandler = new EventHandler((ocean as any).instanceConfig)
|
||||
account = (await ocean.accounts.list())[0].getId()
|
||||
|
||||
executeTransaction = () =>
|
||||
ocean.keeper.dispenser.requestTokens(10, account)
|
||||
executeTransaction = () => ocean.keeper.dispenser.requestTokens(10, account)
|
||||
})
|
||||
|
||||
describe('#subscribe()', () => {
|
||||
it('should be able to listen to events', async () => {
|
||||
const event = eventHandler.getEvent(
|
||||
ocean.keeper.token,
|
||||
'Transfer',
|
||||
{ to: account }
|
||||
)
|
||||
const event = eventHandler.getEvent(ocean.keeper.token, 'Transfer', { to: account })
|
||||
let validResolve = false
|
||||
let subscription: ContractEventSubscription
|
||||
|
||||
@ -57,11 +52,7 @@ describe('ContractEvent', () => {
|
||||
describe('#once()', () => {
|
||||
it('should listen to event only once', async () => {
|
||||
const to = account
|
||||
const event = eventHandler.getEvent(
|
||||
ocean.keeper.token,
|
||||
'Transfer',
|
||||
{ to }
|
||||
)
|
||||
const event = eventHandler.getEvent(ocean.keeper.token, 'Transfer', { to })
|
||||
let canBeRejected = false
|
||||
|
||||
const waitUntilEvent = new Promise((resolve, reject) => {
|
||||
@ -85,11 +76,7 @@ describe('ContractEvent', () => {
|
||||
|
||||
it('should get the event like a promise', async () => {
|
||||
const to = account
|
||||
const event = eventHandler.getEvent(
|
||||
ocean.keeper.token,
|
||||
'Transfer',
|
||||
{ to }
|
||||
)
|
||||
const event = eventHandler.getEvent(ocean.keeper.token, 'Transfer', { to })
|
||||
|
||||
const waitUntilEvent = event.once()
|
||||
|
||||
|
@ -21,13 +21,7 @@ describe('DIDRegistry', () => {
|
||||
const ownerAccount: Account = (await ocean.accounts.list())[0]
|
||||
const did = generateId()
|
||||
const data = 'my nice provider, is nice'
|
||||
const receipt = await didRegistry.registerAttribute(
|
||||
did,
|
||||
`0123456789abcdef`,
|
||||
[],
|
||||
data,
|
||||
ownerAccount.getId()
|
||||
)
|
||||
const receipt = await didRegistry.registerAttribute(did, `0123456789abcdef`, [], data, ownerAccount.getId())
|
||||
assert(receipt.status)
|
||||
assert(receipt.events.DIDAttributeRegistered)
|
||||
})
|
||||
@ -38,13 +32,7 @@ describe('DIDRegistry', () => {
|
||||
{
|
||||
// register the first attribute
|
||||
const data = 'my nice provider, is nice'
|
||||
await didRegistry.registerAttribute(
|
||||
did,
|
||||
'0123456789abcdef',
|
||||
[],
|
||||
data,
|
||||
ownerAccount.getId()
|
||||
)
|
||||
await didRegistry.registerAttribute(did, '0123456789abcdef', [], data, ownerAccount.getId())
|
||||
}
|
||||
{
|
||||
// register the second attribute with the same did
|
||||
@ -67,21 +55,11 @@ describe('DIDRegistry', () => {
|
||||
const ownerAccount: Account = (await ocean.accounts.list())[0]
|
||||
const did = generateId()
|
||||
const data = 'my nice provider, is nice'
|
||||
await didRegistry.registerAttribute(
|
||||
did,
|
||||
'0123456789abcdef',
|
||||
[],
|
||||
data,
|
||||
ownerAccount.getId()
|
||||
)
|
||||
await didRegistry.registerAttribute(did, '0123456789abcdef', [], data, ownerAccount.getId())
|
||||
|
||||
const owner = await didRegistry.getDIDOwner(did)
|
||||
|
||||
assert.equal(
|
||||
owner,
|
||||
ownerAccount.getId(),
|
||||
`Got ${owner} but expected ${ownerAccount.getId()}`
|
||||
)
|
||||
assert.equal(owner, ownerAccount.getId(), `Got ${owner} but expected ${ownerAccount.getId()}`)
|
||||
})
|
||||
|
||||
it('should get 0x0 for a not registered did', async () => {
|
||||
|
@ -27,11 +27,7 @@ describe('EventHandler', () => {
|
||||
assert.isDefined(subscription)
|
||||
|
||||
const countAfter = eventHandler.count
|
||||
assert.equal(
|
||||
countBefore + 1,
|
||||
countAfter,
|
||||
'The event seems not added.'
|
||||
)
|
||||
assert.equal(countBefore + 1, countAfter, 'The event seems not added.')
|
||||
|
||||
subscription.unsubscribe()
|
||||
})
|
||||
@ -58,11 +54,7 @@ describe('EventHandler', () => {
|
||||
eventHandler.unsubscribe(callback)
|
||||
|
||||
const countAfter = eventHandler.count
|
||||
assert.equal(
|
||||
countBefore,
|
||||
countAfter,
|
||||
'The event seems not removed.'
|
||||
)
|
||||
assert.equal(countBefore, countAfter, 'The event seems not removed.')
|
||||
})
|
||||
})
|
||||
|
||||
|
@ -20,33 +20,23 @@ export default class TestContractHandler extends ContractHandler {
|
||||
Logger.log('Trying to deploy contracts')
|
||||
|
||||
// Libraries
|
||||
const epochLibrary = await TestContractHandler.deployContract(
|
||||
'EpochLibrary',
|
||||
deployerAddress
|
||||
)
|
||||
const didRegistryLibrary = await TestContractHandler.deployContract(
|
||||
'DIDRegistryLibrary',
|
||||
deployerAddress
|
||||
)
|
||||
const epochLibrary = await TestContractHandler.deployContract('EpochLibrary', deployerAddress)
|
||||
const didRegistryLibrary = await TestContractHandler.deployContract('DIDRegistryLibrary', deployerAddress)
|
||||
|
||||
// Contracts
|
||||
const token = await TestContractHandler.deployContract(
|
||||
'OceanToken',
|
||||
const token = await TestContractHandler.deployContract('OceanToken', deployerAddress, [
|
||||
deployerAddress,
|
||||
[deployerAddress, deployerAddress]
|
||||
)
|
||||
deployerAddress
|
||||
])
|
||||
|
||||
const dispenser = await TestContractHandler.deployContract(
|
||||
'Dispenser',
|
||||
deployerAddress,
|
||||
[token.options.address, deployerAddress]
|
||||
)
|
||||
const dispenser = await TestContractHandler.deployContract('Dispenser', deployerAddress, [
|
||||
token.options.address,
|
||||
deployerAddress
|
||||
])
|
||||
|
||||
// Add dispenser as Token minter
|
||||
if (!token.$initialized) {
|
||||
await token.methods
|
||||
.addMinter(dispenser.options.address)
|
||||
.send({ from: deployerAddress })
|
||||
await token.methods.addMinter(dispenser.options.address).send({ from: deployerAddress })
|
||||
}
|
||||
|
||||
const didRegistry = await TestContractHandler.deployContract(
|
||||
@ -59,11 +49,9 @@ export default class TestContractHandler extends ContractHandler {
|
||||
)
|
||||
|
||||
// Managers
|
||||
const templateStoreManager = await TestContractHandler.deployContract(
|
||||
'TemplateStoreManager',
|
||||
deployerAddress,
|
||||
[deployerAddress]
|
||||
)
|
||||
const templateStoreManager = await TestContractHandler.deployContract('TemplateStoreManager', deployerAddress, [
|
||||
deployerAddress
|
||||
])
|
||||
const conditionStoreManager = await TestContractHandler.deployContract(
|
||||
'ConditionStoreManager',
|
||||
deployerAddress,
|
||||
@ -84,49 +72,33 @@ export default class TestContractHandler extends ContractHandler {
|
||||
)
|
||||
|
||||
// Conditions
|
||||
const lockRewardCondition = await TestContractHandler.deployContract(
|
||||
'LockRewardCondition',
|
||||
const lockRewardCondition = await TestContractHandler.deployContract('LockRewardCondition', deployerAddress, [
|
||||
deployerAddress,
|
||||
[
|
||||
deployerAddress,
|
||||
conditionStoreManager.options.address,
|
||||
token.options.address
|
||||
]
|
||||
)
|
||||
conditionStoreManager.options.address,
|
||||
token.options.address
|
||||
])
|
||||
const accessSecretStoreCondition = await TestContractHandler.deployContract(
|
||||
'AccessSecretStoreCondition',
|
||||
deployerAddress,
|
||||
[
|
||||
deployerAddress,
|
||||
conditionStoreManager.options.address,
|
||||
agreementStoreManager.options.address
|
||||
]
|
||||
[deployerAddress, conditionStoreManager.options.address, agreementStoreManager.options.address]
|
||||
)
|
||||
|
||||
// Conditions rewards
|
||||
const escrowReward = await TestContractHandler.deployContract(
|
||||
'EscrowReward',
|
||||
const escrowReward = await TestContractHandler.deployContract('EscrowReward', deployerAddress, [
|
||||
deployerAddress,
|
||||
[
|
||||
deployerAddress,
|
||||
conditionStoreManager.options.address,
|
||||
token.options.address
|
||||
]
|
||||
)
|
||||
conditionStoreManager.options.address,
|
||||
token.options.address
|
||||
])
|
||||
|
||||
// Templates
|
||||
await TestContractHandler.deployContract(
|
||||
'EscrowAccessSecretStoreTemplate',
|
||||
await TestContractHandler.deployContract('EscrowAccessSecretStoreTemplate', deployerAddress, [
|
||||
deployerAddress,
|
||||
[
|
||||
deployerAddress,
|
||||
agreementStoreManager.options.address,
|
||||
didRegistry.options.address,
|
||||
accessSecretStoreCondition.options.address,
|
||||
lockRewardCondition.options.address,
|
||||
escrowReward.options.address
|
||||
]
|
||||
)
|
||||
agreementStoreManager.options.address,
|
||||
didRegistry.options.address,
|
||||
accessSecretStoreCondition.options.address,
|
||||
lockRewardCondition.options.address,
|
||||
escrowReward.options.address
|
||||
])
|
||||
}
|
||||
|
||||
private static async deployContract(
|
||||
@ -156,10 +128,7 @@ export default class TestContractHandler extends ContractHandler {
|
||||
gasPrice: 10000000000
|
||||
}
|
||||
const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${name}.development.json`)
|
||||
const tempContract = new web3.eth.Contract(
|
||||
artifact.abi,
|
||||
artifact.address
|
||||
)
|
||||
const tempContract = new web3.eth.Contract(artifact.abi, artifact.address)
|
||||
const isZos = !!tempContract.methods.initialize
|
||||
|
||||
Logger.debug({
|
||||
@ -176,42 +145,27 @@ export default class TestContractHandler extends ContractHandler {
|
||||
|
||||
contractInstance = await tempContract
|
||||
.deploy({
|
||||
data: TestContractHandler.replaceTokens(
|
||||
artifact.bytecode.toString(),
|
||||
tokens
|
||||
),
|
||||
data: TestContractHandler.replaceTokens(artifact.bytecode.toString(), tokens),
|
||||
arguments: isZos ? undefined : args
|
||||
})
|
||||
.send(sendConfig)
|
||||
if (isZos) {
|
||||
await contractInstance.methods
|
||||
.initialize(...args)
|
||||
.send(sendConfig)
|
||||
await contractInstance.methods.initialize(...args).send(sendConfig)
|
||||
}
|
||||
contractInstance.testContract = true
|
||||
ContractHandler.setContract(name, where, contractInstance)
|
||||
// Logger.log("Deployed", name, "at", contractInstance.options.address);
|
||||
} catch (err) {
|
||||
Logger.error(
|
||||
'Deployment failed for',
|
||||
name,
|
||||
'with args',
|
||||
JSON.stringify(args, null, 2),
|
||||
err.message
|
||||
)
|
||||
Logger.error('Deployment failed for', name, 'with args', JSON.stringify(args, null, 2), err.message)
|
||||
throw err
|
||||
}
|
||||
|
||||
return contractInstance
|
||||
}
|
||||
|
||||
private static replaceTokens(
|
||||
bytecode: string,
|
||||
tokens: { [name: string]: string }
|
||||
): string {
|
||||
private static replaceTokens(bytecode: string, tokens: { [name: string]: string }): string {
|
||||
return Object.entries(tokens).reduce(
|
||||
(acc, [token, address]) =>
|
||||
acc.replace(new RegExp(`_+${token}_+`, 'g'), address.substr(2)),
|
||||
(acc, [token, address]) => acc.replace(new RegExp(`_+${token}_+`, 'g'), address.substr(2)),
|
||||
bytecode
|
||||
)
|
||||
}
|
||||
|
@ -13,8 +13,7 @@ describe('AccessSecretStoreCondition', () => {
|
||||
|
||||
before(async () => {
|
||||
await TestContractHandler.prepareContracts()
|
||||
condition = (await Ocean.getInstance(config)).keeper.conditions
|
||||
.accessSecretStoreCondition
|
||||
condition = (await Ocean.getInstance(config)).keeper.conditions.accessSecretStoreCondition
|
||||
})
|
||||
|
||||
describe('#hashValues()', () => {
|
||||
|
@ -21,27 +21,13 @@ describe('EscrowReward', () => {
|
||||
await TestContractHandler.prepareContracts()
|
||||
condition = keeper.conditions.escrowReward
|
||||
|
||||
lockCondition = await keeper.conditions.lockRewardCondition.generateIdHash(
|
||||
agreementId,
|
||||
publisher,
|
||||
amount
|
||||
)
|
||||
releaseCondition = await keeper.conditions.accessSecretStoreCondition.generateIdHash(
|
||||
agreementId,
|
||||
did,
|
||||
consumer
|
||||
)
|
||||
lockCondition = await keeper.conditions.lockRewardCondition.generateIdHash(agreementId, publisher, amount)
|
||||
releaseCondition = await keeper.conditions.accessSecretStoreCondition.generateIdHash(agreementId, did, consumer)
|
||||
})
|
||||
|
||||
describe('#hashValues()', () => {
|
||||
it('should hash the values', async () => {
|
||||
const hash = await condition.hashValues(
|
||||
amount,
|
||||
consumer,
|
||||
publisher,
|
||||
lockCondition,
|
||||
releaseCondition
|
||||
)
|
||||
const hash = await condition.hashValues(amount, consumer, publisher, lockCondition, releaseCondition)
|
||||
|
||||
assert.match(hash, /^0x[a-f0-9]{64}$/i)
|
||||
})
|
||||
@ -49,13 +35,7 @@ describe('EscrowReward', () => {
|
||||
|
||||
describe('#generateId()', () => {
|
||||
it('should generate an ID', async () => {
|
||||
const hash = await condition.hashValues(
|
||||
amount,
|
||||
consumer,
|
||||
publisher,
|
||||
lockCondition,
|
||||
releaseCondition
|
||||
)
|
||||
const hash = await condition.hashValues(amount, consumer, publisher, lockCondition, releaseCondition)
|
||||
const id = await condition.generateId(agreementId, hash)
|
||||
|
||||
assert.match(id, /^0x[a-f0-9]{64}$/i)
|
||||
|
@ -13,8 +13,7 @@ describe('LockRewardCondition', () => {
|
||||
|
||||
before(async () => {
|
||||
await TestContractHandler.prepareContracts()
|
||||
condition = (await Ocean.getInstance(config)).keeper.conditions
|
||||
.lockRewardCondition
|
||||
condition = (await Ocean.getInstance(config)).keeper.conditions.lockRewardCondition
|
||||
})
|
||||
|
||||
describe('#hashValues()', () => {
|
||||
|
@ -15,9 +15,7 @@ export default class WebServiceConnectorMock extends WebServiceConnector {
|
||||
return this.returnData ? this.returnData : {}
|
||||
},
|
||||
text: () => {
|
||||
return this.returnData
|
||||
? JSON.stringify(this.returnData.toString())
|
||||
: ''
|
||||
return this.returnData ? JSON.stringify(this.returnData.toString()) : ''
|
||||
}
|
||||
})
|
||||
})
|
||||
|
@ -39,10 +39,7 @@ describe('Account', () => {
|
||||
const balance = await account.getEtherBalance()
|
||||
const web3 = Web3Provider.getWeb3()
|
||||
|
||||
assert(
|
||||
Number(web3.utils.toWei('100', 'ether')) === balance,
|
||||
`ether did not match ${balance}`
|
||||
)
|
||||
assert(Number(web3.utils.toWei('100', 'ether')) === balance, `ether did not match ${balance}`)
|
||||
})
|
||||
})
|
||||
|
||||
@ -52,10 +49,7 @@ describe('Account', () => {
|
||||
const balance = await account.getBalance()
|
||||
const web3 = Web3Provider.getWeb3()
|
||||
|
||||
assert(
|
||||
Number(web3.utils.toWei('100', 'ether')) === balance.eth,
|
||||
`ether did not match ${balance.eth}`
|
||||
)
|
||||
assert(Number(web3.utils.toWei('100', 'ether')) === balance.eth, `ether did not match ${balance.eth}`)
|
||||
assert(balance.ocn === 0, `tokens did not match ${balance.ocn}`)
|
||||
})
|
||||
})
|
||||
|
@ -54,11 +54,7 @@ describe('OceanAuth', () => {
|
||||
|
||||
describe('#store()', () => {
|
||||
it('should sign and store the token', async () => {
|
||||
const writeTokenSpy = spy.on(
|
||||
oceanAuth as any,
|
||||
'writeToken',
|
||||
() => {}
|
||||
)
|
||||
const writeTokenSpy = spy.on(oceanAuth as any, 'writeToken', () => {})
|
||||
|
||||
await oceanAuth.store(account)
|
||||
|
||||
|
@ -27,17 +27,9 @@ describe('OceanSecretStore', () => {
|
||||
|
||||
describe('#encrypt()', () => {
|
||||
it('should encrypt a content', async () => {
|
||||
const secretStoreEncryptSpy = spy.on(
|
||||
ocean.brizo,
|
||||
'encrypt',
|
||||
() => 'encryptedResult'
|
||||
)
|
||||
const secretStoreEncryptSpy = spy.on(ocean.brizo, 'encrypt', () => 'encryptedResult')
|
||||
|
||||
const result = await oceanSecretStore.encrypt(
|
||||
did,
|
||||
'test',
|
||||
accounts[0]
|
||||
)
|
||||
const result = await oceanSecretStore.encrypt(did, 'test', accounts[0])
|
||||
|
||||
expect(secretStoreEncryptSpy).to.have.been.called.with(did, 'test')
|
||||
|
||||
|
@ -38,33 +38,18 @@ describe('SignatureUtils', () => {
|
||||
})
|
||||
|
||||
it('should sign a text as expected using password', async () => {
|
||||
const signed = await ocean.utils.signature.signText(
|
||||
text,
|
||||
publicKey,
|
||||
'test'
|
||||
)
|
||||
const signed = await ocean.utils.signature.signText(text, publicKey, 'test')
|
||||
|
||||
assert.equal(signed, signature)
|
||||
expect(personalSignSpy).to.have.been.called.with(
|
||||
text,
|
||||
publicKey,
|
||||
'test'
|
||||
)
|
||||
expect(personalSignSpy).to.have.been.called.with(text, publicKey, 'test')
|
||||
})
|
||||
})
|
||||
|
||||
describe('#verifyText', () => {
|
||||
it('should recover the privateKey of a signed message', async () => {
|
||||
const personalRecoverSpy = spy.on(
|
||||
web3.eth.personal,
|
||||
'ecRecover',
|
||||
() => publicKey
|
||||
)
|
||||
const personalRecoverSpy = spy.on(web3.eth.personal, 'ecRecover', () => publicKey)
|
||||
|
||||
const verifiedPublicKey = await ocean.utils.signature.verifyText(
|
||||
text,
|
||||
signature
|
||||
)
|
||||
const verifiedPublicKey = await ocean.utils.signature.verifyText(text, signature)
|
||||
|
||||
assert.equal(publicKey, verifiedPublicKey)
|
||||
expect(personalRecoverSpy).to.have.been.called.with(text, signature)
|
||||
|
@ -1,10 +1,5 @@
|
||||
import { assert } from 'chai'
|
||||
import {
|
||||
zeroX,
|
||||
noZeroX,
|
||||
didPrefixed,
|
||||
noDidPrefixed
|
||||
} from '../../src/utils/ConversionTypeHelpers'
|
||||
import { zeroX, noZeroX, didPrefixed, noDidPrefixed } from '../../src/utils/ConversionTypeHelpers'
|
||||
|
||||
describe('ConversionTypeHelpers', () => {
|
||||
describe('#zeroXTransformer()', () => {
|
||||
|
Loading…
Reference in New Issue
Block a user