Container¶
Class Name | Container |
---|---|
Extends | Logger |
Source | container.ts |
Examples | container.spec.ts |
TL;DR: usage examples and a data flow can be found here.
The Container
is an API layer over DataContract and combines its functionalities into a more use case oriented straight forward interface.
To reduce complexity the most common usage patterns from DataContract have been set as fixed in the Container
implementation. Therefore the Container
follows these principles:
- data is always encrypted
- each entry gets an own key for encryption
- each entry get an own role for granting write permissions
- an identity always is created for the container
- adding verifications adds the verification topic to the contract description to allow listing of all verifications of this container
- a property called
type
is added to theContainer
at creation type and marks its template type
constructor¶
new Container(options, config);
Create new Container
instance. This will not create a smart contract contract but is used to
load existing containers. To create a new contract, use the static create function.
Parameters¶
options
-ContainerOptions
: runtime for new containercontractLoader
-ContractLoader
:ContractLoader
instancecryptoProvider
-CryptoProvider
:CryptoProvider
instancedataContract
-DataContract
:DataContract
instancedescription
-Description
:Description
instanceexecutor
-Executor
:Executor
instancenameResolver
-NameResolver
:NameResolver
instancerightsAndRoles
-RightsAndRoles
:RightsAndRoles
instancesharing
-Sharing
:Sharing
instanceverifications
-Verifications
:Verifications
instanceweb3
-Web3
:Web3
instancelog
-Function
(optional): function to use for logging:(message, level) => {...}
logLevel
-LogLevel
(optional): messages with this level will be logged withlog
logLog
-LogLogInterface
(optional): container for collecting log messageslogLogLevel
-LogLevel
(optional): messages with this level will be pushed tologLog
config
-DigitalTwinconfIg
: config for new containeraccountId
-string
: identity or account of user, that interacts with containeraddress
-string
: address of aDataContract
instance, can be ENS or contract address
Returns¶
Container
instance
Example¶
const container = new Container(
runtime,
{
accountId: '0x0000000000000000000000000000000000000000',
address: 'samplecontainer.somewhere.evan',
},
);
= Creating Containers =¶
create¶
Container.create(runtime, config);
Creates a new digital container contract on the blockchain.
Note, that this function is static. It is used on the Container
class object and returns a Container
class instance.
The options argument has the same structure as the options object that is passed to the constructor as it is used for the new Container
instance. The config
argument requires a proper value for the property description
.
Parameters¶
options
-ContainerOptions
: runtime for new containercontractLoader
-ContractLoader
:ContractLoader
instancecryptoProvider
-CryptoProvider
:CryptoProvider
instancedataContract
-DataContract
:DataContract
instancedescription
-Description
:Description
instanceexecutor
-Executor
:Executor
instancenameResolver
-NameResolver
:NameResolver
instancerightsAndRoles
-RightsAndRoles
:RightsAndRoles
instancesharing
-Sharing
:Sharing
instanceverifications
-Verifications
:Verifications
instanceweb3
-Web3
:Web3
instancelog
-Function
(optional): function to use for logging:(message, level) => {...}
logLevel
-LogLevel
(optional): messages with this level will be logged withlog
logLog
-LogLogInterface
(optional): container for collecting log messageslogLogLevel
-LogLevel
(optional): messages with this level will be pushed tologLog
config
-DigitalTwinconfIg
: config for new containeraccountId
-string
: identity or account of user, that interacts with containeraddress
-string
: ENS address used for containerdescription
-string
: description has to be passed to.create
to apply it to to contractfactoryAddress
-string
(optional): factory address can be passed to.create
for customer container factoryplugin
-string|ContainerPlugin
(optional): plugin to be used in.create
, can be string with name or aContainerPlugin
Returns¶
Promise
returns Container
: new instance bound to new DataContract
Example¶
const container = await Container.create(options, config);
console.log(await container.getContractAddress());
// Output:
// 0x0000000000000000000000000000000000001234
clone¶
Container.clone(options, config, source[, copyValues]);
Clone Container
instance into plugin and creates new Container
with it.
Cloning containers:
is done with identity or account from
config.accountId
, which will be owner of the new contractcopies all fields from source container to new container (including roles, that have permissions on them)
copies values for entry-fields (no lists) to new container, if
copyValues
is setdoes not copy role membership
config.accountId
is the owner of the new contract and also a member of the contract (role 0 and 1)- other roles receive permissions on fields, but do not get members added to them
does not copy sharings
- a new sharing with new keys is generated for this container
- only the owner of the container receives keys shared to it for this container
does not copy verifications
does not copy the description
config.description
is used for the cloned contract- fields are dynamically added to the description when generating the clone
Parameters¶
options
-ContainerOptions
: runtime for new containercontractLoader
-ContractLoader
:ContractLoader
instancecryptoProvider
-CryptoProvider
:CryptoProvider
instancedataContract
-DataContract
:DataContract
instancedescription
-Description
:Description
instanceexecutor
-Executor
:Executor
instancenameResolver
-NameResolver
:NameResolver
instancerightsAndRoles
-RightsAndRoles
:RightsAndRoles
instancesharing
-Sharing
:Sharing
instanceverifications
-Verifications
:Verifications
instanceweb3
-Web3
:Web3
instancelog
-Function
(optional): function to use for logging:(message, level) => {...}
logLevel
-LogLevel
(optional): messages with this level will be logged withlog
logLog
-LogLogInterface
(optional): container for collecting log messageslogLogLevel
-LogLevel
(optional): messages with this level will be pushed tologLog
config
-DigitalTwinconfIg
: config for new containeraccountId
-string
: identity or account of user, that interacts with containeraddress
-string
: ENS address used for containerdescription
-string
: description has to be passed to.create
to apply it to to contractfactoryAddress
-string
(optional): factory address can be passed to.create
for customer container factoryplugin
-string|ContainerPlugin
(optional): plugin to be used in.create
, can be string with name or aContainerPlugin
source
-Container
: container to clonecopyValues
-boolean
: copy entry values from source contract to new contract
Returns¶
Promise
returns Container
: new instance bound to new DataContract
and a copy of source
Example¶
const container = await Container.create(options, config);
console.log(await container.getContractAddress());
// Output:
// 0x0000000000000000000000000000000000001234
const clone = await Container.clone(options, config, container);
console.log(await container.getContractAddress());
// Output:
// 0x0000000000000000000000000000000000005678
deleteContainerPlugin¶
container.deleteContainerPlugin(profile);
Remove a container plugin from a users profile.
Returns¶
Promise
returns void
getContainerPlugin¶
container.getContainerPlugin(profile, name);
Get one container plugin for a users profile by name.
Returns¶
Promise
returns ContainerPlugin
Example¶
const accountId1 = '0x0000000000000000000000000000000000000001';
const plugin = await Container.getContainerPlugin(profile, 'awesomeplugin');
// create container with accountId1
const container = await Container.create(options, {
...config,
accountId: accountId1,
description: plugin.description,
plugin: plugin,
});
getContainerPlugins¶
container.getContainerPlugins(profile);
Get all container plugins for a users profile
Parameters¶
Profile
-Profile
: profile instanceloadContracts
- boolean (default = true): run loadBcContract directly for all saved entries (if false, unresolved ipld tree will be returned as value)
Returns¶
Promise
returns Array<ContainerPlugin>
Example¶
const accountId1 = '0x0000000000000000000000000000000000000001';
const plugins = await Container.getContainerPlugins(profile);
// create container with accountId1
const container = await Container.create(options, {
...config,
accountId: accountId1,
description: plugins['awesomeplugin'].description,
plugin: plugins['awesomeplugin'],
});
saveContainerPlugin¶
container.saveContainerPlugin(profile, name, plugin);
Persists a plugin including an dbcp description to the users profile.
Parameters¶
Profile
-Profile
: profile instancename
-string
: plugin nameplugin
-ContainerPlugin
: container plugin objectbeforeName
-strinf
: remove previous plugin instance when it was renamed
Returns¶
Promise
returns void
toPlugin¶
container.toPlugin([getValues]);
Export current container state as plugin. If getValues
is true
, exports entry values as
well.
This plugin can be passed to create and used to create new containers.
Parameters¶
getValues
-boolean
: export entry values or not (list entries are always excluded)
Returns¶
Promise
returns ContainerPlugin
: plugin build from current container
Example¶
const sampleValue = 123;
await container.setEntry('numberField', sampleValue);
console.dir(await container.toPlugin(true));
= Entries =¶
setEntry¶
container.setEntry(entryName, value);
Set a value for an entry.
Parameters¶
entryName
-string
: name of an entry in the containervalue
-any
: value to set
Returns¶
Promise
returns void
: resolved when done
Example¶
const sampleValue = 123;
await container.setEntry('numberField', sampleValue);
console.log(await container.getEntry('numberField'));
// Output:
// 123
getEntry¶
container.getEntry(entryName);
Return entry from contract.
Parameters¶
entryName
-string
: entry name
Returns¶
Promise
returns any
: entry value
Example¶
Entries can be retrieved with:
const sampleValue = 123;
await container.setEntry('numberField', sampleValue);
console.log(await container.getEntry('numberField'));
// Output:
// 123
removeEntries¶
container.removeEntries(entries);
Remove multiple entries from the container, including data keys and sharings. Can also pass a single property instead of an array. Retrieves dynamically all sharings for the passed entries and runs unshareProperties for them.
Parameters¶
entries
-string
/string[]
: name / list of entries, that should be removed
Returns¶
Promise
returns void
: resolved when done
Example¶
const accountId1 = '0x0000000000000000000000000000000000000001';
const accountId2 = '0x0000000000000000000000000000000000000002';
// open container with accountId1
const container = new Container(options, { ...config, accountId: accountId1 });
// assuming, that entry 'myField' has been shared with accountId2
// remove the whole property from the container
await container.removeEntries(['myField']);
// fetch value with accountId2 and with accountId1
const accountId2Container = new Container(options, { ...config, accountId: accountId2 });
let value;
try {
value = await accountId2Container.getEntry('myField');
console.log(value);
} catch (ex) {
console.error('could not get entry');
}
// also the owner cannot get this entry anymore
try {
value = await container.getEntry('myField');
console.log(value);
} catch (ex) {
console.error('could not get entry');
}
// Output:
// could not get entry
= List Entries =¶
addListEntries¶
container.addListEntries(listName, values);
Add list entries to a list list property.
List entries can be added in bulk, so the value argument is an array with values. This array can be arbitrarily large up to a certain degree. Values are inserted on the blockchain side and adding very large arrays this way may take more gas during the contract transaction, than may fit into a single transaction. If this is the case, values can be added in chunks (multiple transactions).
Parameters¶
listName
-string
: name of the list in the containervalues
-any[]
: values to add
Returns¶
Promise
returns void
: resolved when done
Example¶
const listName = 'exampleList';
console.log(await container.getListEntryCount(listName));
// Output:
// 0
const sampleValue = {
foo: 'sample',
bar: 123,
};
await container.addListEntries(listName, [sampleValue]);
console.log(await container.getListEntryCount(listName));
// Output:
// 1
console.dir(await container.getListEntries(listName));
// Output:
// [{
// foo: 'sample',
// bar: 123,
// }]
getListEntryCount¶
container.getListEntryCount(listName);
Return number of entries in the list. Does not try to actually fetch and decrypt values, but just returns the count.
Parameters¶
listName
-string
: name of a list in the container
Returns¶
Promise
returns number
: list entry count
Example¶
const listName = 'exampleList';
console.log(await container.getListEntryCount(listName));
// Output:
// 0
const sampleValue = {
foo: 'sample',
bar: 123,
};
await container.addListEntries(listName, [sampleValue]);
console.log(await container.getListEntryCount(listName));
// Output:
// 1
console.dir(await container.getListEntries(listName));
// Output:
// [{
// foo: 'sample',
// bar: 123,
// }]
getListEntries¶
container.getListEntries(listName, count, offset, reverse);
Return list entries from contract. Note, that in the current implementation, this function retrieves the entries one at a time and may take a longer time when querying large lists, so be aware of that, when you retrieve lists with many entries. Keep in mind if only the listName is passed it will not retrieve the entire list instead only the first 10 elements in the list.
Parameters¶
listName
-string
: name of the list in the containercount
-number
(optional): number of elements to retrieve, defaults to10
offset
-number
(optional): skip this many items when retrieving, defaults to0
reverse
-boolean
(optional): retrieve items in reverse order, defaults tofalse
Returns¶
Promise
returns any[]
: list entries
Example¶
const listName = 'exampleList';
console.log(await container.getListEntryCount(listName));
// Output:
// 0
const sampleValue = [ 'Hello', 'welcome', 'to', 'evan', 'network' ];
await container.addListEntries(listName, [sampleValue]);
console.log(await container.getListEntryCount(listName));
// Output:
// 5
console.dir(await container.getListEntries(listName));
// Output:
// [ 'Hello', 'welcome', 'to', 'evan', 'network' ]
console.log(await container.getListEntries(listName, 2));
//Output:
// [ 'Hello', 'welcome' ]
console.log(await container.getListEntries(listName, 10, 2));
//Output
// [ 'to', 'evan', 'network' ]
console.log(await container.getListEntries('testList', 10, 0, true));
//Output:
// [ 'network', 'evan', 'to', 'welcome', 'Hello' ]
getListEntry¶
container.getListEntry(listName, index);
Return a single list entry from contract.
Parameters¶
listName
-string
: name of the list in the containerindex
-number
: list entry id to retrieve
Returns¶
Promise
returns any
: list entry
Example¶
const listName = 'exampleList';
console.log(await container.getListEntryCount(listName));
// Output:
// 0
const sampleValue = {
foo: 'sample',
bar: 123,
};
await container.addListEntries(listName, [sampleValue]);
const count = await container.getListEntryCount(listName);
console.log(count);
// Output:
// 1
console.dir(await container.getListEntry(listName, count - 1));
// Output:
// {
// foo: 'sample',
// bar: 123,
// }
= Store multiple properties =¶
storeData¶
container.storeData(data);
- Store data to a container. This allows to
- store data into already existing entries and/or list entries
- implicitely create new entries and/or list entries (the same logic for deciding on their type is applied as in setEntry/addListEntries is applied here)
- in case of entries, their value is overwritten
- in case of list entries, given values are added to the list
Parameters¶
data
-object
: object with keys, that are names of lists or entries and values, that are the values to store to them
Returns¶
Promise
returns void
: resolved when done
Example¶
const sampleValue = 123;
await container.storeData({
'numberField': sampleValue,
});
console.log(await container.getEntry('numberField'));
// Output:
// 123
= Verifying Containers =¶
addVerifications¶
container.addVerifications(verifications);
Add verifications to this container; this will also add verifications to contract description.
If the calling account is the owner of the identity of the container
- the description will is automatically updated with tags for verifications
- verifications issued with this function will be accepted automatically
See interface ContainerVerificationEntry
for input data format.
Parameters¶
verifications
-ContainerVerificationEntry[]
: list of verifications to add
Returns¶
Promise
returns void
: resolved when done
getOwner¶
container.getOwner();
Gets the owner identity or account for the container.
Returns¶
Promise
returns string
: owner identity or account
getVerifications¶
container.getVerifications();
Gets verifications from description and fetches list of verifications for each of them.
See Verifications
documentation for details on output data format.
Returns¶
Promise
returns any
: list of verification lists from Verifications
, getVerifications
Example¶
await container.addVerifications([{ topic: 'exampleVerification' }]);
const verifications = await container.getVerifications());
= Working with Container Descriptions =¶
getDescription¶
container.getDescription();
Get description from container contract.
Returns¶
Promise
returns any
: public part of the description
Example¶
const description = await container.getDescription();
console.dir(description);
// Output:
// { name: 'test container',
// description: 'container from test run',
// author: 'evan GmbH',
// version: '0.1.0',
// dbcpVersion: 2,
// identity:
// '0x70c969a64e880fc904110ce9ab72ba5f95f706a252ac085ae0525bd7a284337c',
// dataSchema: { type: { type: 'string', '$id': 'type_schema' } } }
setDescription¶
container.setDescription(description);
Write given description to containers DBCP.
Parameters¶
description
-any
: description (public part)
Returns¶
Promise
returns void
: resolved when done
Example¶
// get current description
const description = await container.getDescription();
console.dir(description);
// Output:
// { name: 'test container',
// description: 'container from test run',
// author: 'evan GmbH',
// version: '0.1.0',
// dbcpVersion: 2,
// identity:
// '0x70c969a64e880fc904110ce9ab72ba5f95f706a252ac085ae0525bd7a284337c',
// dataSchema: { type: { type: 'string', '$id': 'type_schema' } } }
// update description
description.version = '0.1.1';
await container.setDescription(description);
// fetch again
console.dir(await container.getDescription());
// Output:
// { name: 'test container',
// description: 'container from test run',
// author: 'evan GmbH',
// version: '0.1.1',
// dbcpVersion: 2,
// identity:
// '0x70c969a64e880fc904110ce9ab72ba5f95f706a252ac085ae0525bd7a284337c',
// dataSchema: { type: { type: 'string', '$id': 'type_schema' } } }
= Utilities =¶
getContractAddress¶
container.getContractAddress();
Get contract address of underlying DataContract
.
Returns¶
Promise
returns string
: address of the DataContract
Example¶
const container = await Container.create(options, config);
console.log(await container.getContractAddress());
// Output:
// 0x0000000000000000000000000000000000001234
ensureProperty¶
container.ensureProperty(propertyName, dataSchema[, propertyType]);
Ensure that container supports given property.
Returns¶
Promise
returns void
: resolved when done
Example¶
await container.ensureProperty('testField', Container.defaultSchemas.stringEntry);
Additional Components¶
Interfaces¶
ContainerConfig¶
config properties, specific to Container instances
accountId
-string
: identity or account of user, that interacts with containeraddress
-string
(optional): address of aDataContract
instance, can be ENS or contract addressdescription
-string
(optional): description has to be passed to.create
to apply it to to contractfactoryAddress
-string
(optional): factory address can be passed to.create
for customer container factoryplugin
-string|ContainerPlugin
(optional): plugin to be used in.create
, can be string with name or aContainerPlugin
ContainerFile¶
description and content of a single file, usually used in arrays (add/get/set operations)
name
-string
: filename, e.g.animal-animal-photography-cat-96938.jpg
fileType
-string
: mime type of the file, e.g.image/jpeg
file
-Buffer
: file data as Buffer
ContainerPlugin¶
base definition of a container instance, covers properties setup and permissions
description
-any
: type of the template (equals name of the template)template
-ContainerTemplate
: template for container instances, covers properties setup and permissions
ContainerTemplate¶
template for container instances, covers properties setup and permissions
type
-string
: type of the template (equals name of the template)properties
-{ [id: string]: ContainerTemplateProperty; }
(optional): list of properties included in this template, key is field name, value is property setup
ContainerTemplateProperty¶
config for sharing multiple fields to one identity or account (read and/or readWrite access)
dataSchema
-any
: Ajv data schema for fieldpermissions
-{ [id: number]: string[] }
: permissions for this template, key is role id, value is array with ‘set’ and/or ‘remove’type
-string
: type of property (entry/list)value
-any
(optional): value of property
ContainerVerificationEntry¶
data for verifications for containers
topic
-string
: verification pathdescriptionDomain
-string
(optional): domain, where the description of this verification is storeddisableSubverifications
-boolean
(optional): if set, verification created in a sub-path are invalid by default, defaults tofalse
expirationDate
-number
(optional): expiration date, verifications do not expire if omitted, defaults to0
verificationValue
-string
(optional): reference to additional verification details
Public Properties¶
defaultDescription (static)¶
Default description used when no specific description is given to .create.
defaultSchemas (static)¶
Predefined simple schemas, contains basic schemas for files, number, object, string entries and their list variants.
defaultTemplate (static)¶
Default template used when no specific description is given to .create. Default template is metadata
.
profileTemplatesKey (static)¶
Key that is used in user profile to store templates, default is templates.datacontainer.digitaltwin.evan
templates (static)¶
Predefined templates for containers, currently only contains the metadata
template.