#3 Loading a smart contract in a smart way in Nethereum

Xuntos
Building a Dapp on Ethereum
3 min readAug 24, 2018

--

In our Dapp the blockchain will mainly be used to decentralize the data storage. Our solution stack consists of several technologies. We use Angular for presentation, .NET Core with C# for the API and the Ethereum blockchain as datalayer. This means that most of our application will consist of loading data from smart contracts into C# models so we can work with them. In this blog we will dive into the solution we devised for loading the data of a smart contract in a way that doesn’t involve writing a seperate getter in C# for every state variable in a contract.

First things first, we set up a smart contract in solidity with a getter for all state variables (we can’t get around this since state variables aren’t accessible without getters). Let’s take the person contract from the last blog (#2 The search for finding smart contracts) and add two extra state variables.

The new PersonContract

Now take a look at the C# class that corresponds to that.

That is all we need in the PersonContract class to be able to load all data from a person contract in this model. The reason for that is, we moved all the magical calls to a method in the MasterContract class. This method loops through all the contract get functions with names that can be mapped to the properties of the C# class. For example getName() maps to Name and getStreetName() maps to StreetName.

Using this piece of code we can just call PopulateFromContract on a PersonContract object with the proper instance of the contract we want to load the data from. If we combine this with the process we described in #2 The search for finding smart contracts we can load pretty much any contract we push on the blockchain without the trouble of writing all the calls to the blockchain for every property. A bit like how Json.Net converts JSON to a class with JsonConvert.DeserializeObject.

Because we can find them using the AddressListContract and we know what ABI to use due to it being saved within the contract instance.

All in this method of loading contracts makes it very easy to add properties to a type of smart contract or add a new smart contract all together. We just make it in solidity and have the C# class inherit the MasterContract class.

We also made a similar way of setting all the state variables from the values we have in C#, but we will save that for a future entry in this series.

To recap, we made a method in C# that allows us to load all accessible data from a contract instance without needing to write property specific code. This enables faster development of contracts in our .NET Core because adding properties or new types of contract.

Give us a clap if you want to see the code we use to set state variables or if you thought this post was helpful in your journey with Nethereum!

--

--