Data Persistence
So far we have avoided creating variables in the contract, because the virtual machine works in an isolated context. Everything that happens in the method will be deleted after its execution. To persist data we use objects that interface the contract with the blockchain.
import BywiseUtils, { StorageValue } from 'bywise-utils.js';
class HelloWorldContract {
value1 = new StorageValue('some text');
value2 = "some text";
setValue1(newValue) {
this.value1.set(newValue);
}
getValue1() { // @view
return this.value1.get();
}
setValue1InReadMethod(newValue) { // @view
this.value1.set(newValue);
}
setValue2(newValue) {
this.value2 = newValue;
}
getValue2() { // @view
return this.value2;
}
setValue2InReadMethod(newValue) { // @view
this.value2 = newValue;
}
}
BywiseUtils.exportContract(new HelloWorldContract());
In this example, the only variable that can be changed is value1
because it is an instance of StorageValue. It can also only be changed by WRITE, method with @view
discards all changes.
There are three types of storable variables:
- StorageValue: Storage of a variable of type
any
- StorageMap: Equivalent to javascript
Map()
- StorageList: List storage
Example StorageValue:
import BywiseUtils, { StorageValue } from 'bywise-utils.js';
class StorageContract {
value = new StorageValue('');
setValue(newValue) {
this.value.set(newValue);
}
getValue() { // @view
return this.value.get();
}
}
BywiseUtils.exportContract(new StorageContract());
Example StorageMap:
import BywiseUtils, { StorageMap } from 'bywise-utils.js';
class StorageContract {
value = new StorageMap('some default value');
setValue(key, newValue) {
this.value.set(key, newValue);
}
hasValue(key) { // @view
return this.value.has(key) ? 'Yes' : 'No';
}
getValue(key) { // @view
return this.value.get(key);
}
delValue(key) {
this.value.del(key);
}
}
BywiseUtils.exportContract(new StorageContract());
Example StorageList:
import BywiseUtils, { StorageList } from 'bywise-utils.js';
class StorageContract {
value = new StorageList();
pushValue( newValue) {
this.value.push(newValue);
}
popValue() {
return this.value.pop();
}
setValue(index, newValue) {
this.value.set(index, newValue);
}
size() { // @view
return this.value.size();
}
getValue(index) { // @view
return this.value.get(index);
}
}
BywiseUtils.exportContract(new StorageContract());
It is also possible to create composite types for example a map of lists:
import BywiseUtils, { StorageMap, StorageList } from 'bywise-utils.js';
class StorageContract {
map = new StorageMap();
pushValueByKey(key, newValue) {
if (!this.map.has(key)) {
this.map.set(key, new StorageList());
}
this.map.getStorageList(key).push(newValue);
}
getSizeByKey(key) { // @view
if (!this.map.has(key)) {
return '0'
}
return this.map.getStorageList(key).size();
}
}
BywiseUtils.exportContract(new StorageContract());