DEV Community

Petros Demetrakopoulos
Petros Demetrakopoulos

Posted on

Using data models over Ethereum blockchain with EthAir Balloons

Back to basics:
First of all, let's remember what blockchains are: A blockchain in Layman's terms is a kind of distributed database that offers more transparency and more security than other databases. This means that their main role is to store data.

Ethereum blockchain is amazing because it was the first to offer the capability of running code over it with Smart contracts and Solidity, the language behind them. But Solidity smart contracts may be a real hell even for experienced developers as their development is very time consuming, they cannot be easily tested and they have many limitations such as not many available data types, the limited number of parameters you can pass into a function, lack of object-oriented concepts, etc. It feels more like a very primitive programming language than a modern one that allows more complex data structures and functions.

And here comes EthAir Balloons, a spin-off project of my thesis as an undergraduate student in CS School of Athens University of Economics and Business.

EthAir Balloons is a strictly typed ORM library for Ethereum blockchain. It allows you to use Ethereum blockchain as persistent storage in an organized and model-oriented way without writing custom complex Smart contracts. We could tell it is for Ethereum based blockchains what Mongoose is for MongoDB.

We will do a walkthrough to the library by showing how you can very easily create and deploy a new model and then perform all the CRUD operations.

Assuming we have already created a new Node.js project and an index.js file, we can proceed to the installation of the library by typing npm i --save ethairballoons in the root directory of the project.

Now, in the index.js file we add the following lines:

var ethAirBalloons = require('ethairballoons');
var path = require('path');
var savePath = path.resolve(__dirname + '/contracts');

var ethAirBalloonsProvider = ethAirBalloons('http://localhost:8545', savePath); 
//ethereum blockchain provider URL, path to save auto generated smart contracts

var Car = ethAirBalloonsProvider.createSchema({
        name: "Car",
        contractName: "carsContract",
        properties: [
            {
                name: "model",
                type: "bytes32",
                primaryKey: true
            },
            { 
                name: "engine",
                type: "bytes32",
            },
            {   name: "cylinders",
                type: "uint"
            }
        ]
    });
Enter fullscreen mode Exit fullscreen mode

As you can see, we can initiate an instance of ethairballoons (or what I like to call an "ethAirBalloons provider") using only 2 arguments:

1) the URL of the Ethereum blockchain provider that we want to use (in the example it is set to a local ganache-cli provider),

2) the path where we want to save the automatically generated smart contracts of your models.

After the provider initialisation, we can create new data schemas using the createSchema() function and pass the schema details in JS object format. Of course you can (an it is advised) keep the schema definitions in separate .JSON files and then import them using the require() statement in the top of your file.

Now that our data schema is set, it is time to deploy it in the blockchain, in this point I would like to rememeber that we do so in a local ganache-cli instance (which is an Ethereum blockchain simulator) and not in the actual ethereum network. As transaction fees may be huge, it is strongly advised to only deploy EthAir Balloons models in private Ethereum blockchains or locally using ganache-cli.

We deploy our model by calling the deploy() function as shown below:

Car.deploy(function (success, err) {
    if (!err) {
        console.log('Deployed successfully');
    }
});
Enter fullscreen mode Exit fullscreen mode

This function generates the solidity Smart contract of our model and deploys it in the Ethereum based blockchain that we set in the previous step. It returns a boolean indicating if the deploy is successfull and an error object that will be undefined if the deploy is successfull. After deploy completes wecan call the other functions of the model.

Model functions

EthAir Balloons implement all the functions needed to perform CRUD operations.

save()

This function saves a new record in the blockchain. Make sure to set the primary key field in the object you want to save, otherwise an error will be returned. It returns the saved object and an error object that will be undefined if the object is saved successfully.

An example is shown below:

var newCarObject = {model:'Audi A4', engine: 'V8', wheels: 4};
Car.save(newCarObject, function (objectSaved, err) {
   if (!err) {
       console.log('object saved');
   }
});
Enter fullscreen mode Exit fullscreen mode

find()

This function returns all the records of our Model.

Car.find(function (allRecords, err) {
   if (!err) {
       console.log(allRecords);
   }
});
Enter fullscreen mode Exit fullscreen mode

findById()

This function returns the record with a specific primary key value if exists. Otherwise it will return an error object mentioning that 'record with this id does not exist'.

Car.findById('Audi A4', function (record, err) {
   if (!err) {
       console.log(record);
   } 
});
Enter fullscreen mode Exit fullscreen mode

deleteById()

Deletes the record with a specific primary key value if exists. Otherwise it will return an error object mentioning that 'record with this id does not exist'.

Car.deleteById('Audi A4', function (success, err) {
   if (!err) {
       console.log('object deleted successfully');
   } 
});
Enter fullscreen mode Exit fullscreen mode

updateById()

Updates the record with a specific primary key value if exists. Otherwise it will return an error object mentioning that 'record with this id does not exist'. It returns the updated record.

The first parameter is the primary key value of the record we want to update. The second parameter is the updated object.

var updatedCarObject = { engine: 'V9', wheels: 4 };
Car.updateById('Audi A4', updatedCarObject, function (updatedObject, err) {
   if (!err) {
       console.log('object updated successfully');
   } 
});
Enter fullscreen mode Exit fullscreen mode

That's all folks!

I hope you find it interesting and that it will be useful in future projects!

Top comments (1)

Collapse
 
demetrakopetros profile image
Petros Demetrakopoulos

EthAir Balloons just updated to version 1.1.0 with major fixes and improvements and it is available on npm.
npmjs.com/package/ethairballoons