How to Write Smart Contracts and Create dApps using C#
5 Steps to Create a dApp on the aelf blockchain using C#
Smart contracts are self-executing contracts where the terms of the agreement are written in code. They operate on blockchain technology, providing a secure and decentralised way to execute agreements without intermediaries. Decentralised Applications (dApps) are applications that run on a peer-to-peer network of computers, rather than a single computer, offering advantages in terms of security and decentralisation. As mentioned in our previous article about the Popular Web3 Programming Languages in 2024, C# stands as an efficient and scalable programming language for Web3 development. Hence, in this article, we’ll teach you how to write smart contracts and create a dApp on the aelf blockchain using C#.
Prerequisites
Before diving into smart contracts and dApp development, you should have a basic understanding of blockchain technology, including its decentralised nature and consensus mechanisms. A strong foundation in C# programming is essential, as the tutorial will leverage C# for development. Additionally, setting up your development environment is crucial. This typically involves installing an Integrated Development Environment (IDE) like Visual Studio Code, which is well-suited for C# development.
Step 1: Setting Up The Development Environment
To begin developing, the first step involves setting up the development environment. This entails installing necessary tools such as blockchain-specific tools, SDKs, and any essential plugins to support blockchain development within your Integrated Development Environment (IDE). Additionally, depending on the platform, you may need to configure a local node or connect to a test network to facilitate blockchain node setup. This foundational step lays the groundwork for efficient and effective blockchain development. Refer to this page on how to set up a local node on the aelf blockchain.
aelf testnet: Node URL | Explorer
aelf sidechain (tDVW): Node URL | Explorer
Step 2: Writing a Smart Contract in C#
In the second step of the process, you’ll delve into writing a smart contract using C#. Begin by familiarising yourself with the syntax specific to smart contracts in C#. Next, focus on coding the business logic of your contract, which may entail creating functions for transactions, data storage, and other essential operations. It’s crucial to prioritise security considerations during this stage, ensuring that your contract is robust enough to handle exceptions and edge cases effectively. By meticulously addressing these aspects, you can develop a smart contract that is not only functional but also secure and reliable.
Hello World example (Protobuf)
syntax = "proto3";
import "aelf/options.proto";
import "google/protobuf/empty.proto";
import "google/protobuf/wrappers.proto";
// The namespace of this class
option csharp_namespace = "AElf.Contracts.HelloWorld";
service HelloWorld {
// The name of the state class the smart contract is going to use to access blockchain state
option (aelf.csharp_state) = "AElf.Contracts.HelloWorld.HelloWorldState";
// Actions (methods that modify contract state)
// Stores the value in contract state
rpc Update (google.protobuf.StringValue) returns (google.protobuf.Empty) {
}
// Views (methods that don't modify contract state)
// Get the value stored from contract state
rpc Read (google.protobuf.Empty) returns (google.protobuf.StringValue) {
option (aelf.is_view) = true;
}
}
// An event that will be emitted from contract method call
message UpdatedMessage {
option (aelf.is_event) = true;
string value = 1;
}
Hello World example (C#)
using AElf.Sdk.CSharp;
using Google.Protobuf.WellKnownTypes;
namespace AElf.Contracts.HelloWorld
{
// Contract class must inherit the base class generated from the proto file
public class HelloWorld : HelloWorldContainer.HelloWorldBase
{
// A method that modifies the contract state
public override Empty Update(StringValue input)
{
// Set the message value in the contract state
State.Message.Value = input.Value;
// Emit an event to notify listeners about something happened during the execution of this method
Context.Fire(new UpdatedMessage
{
Value = input.Value
});
return new Empty();
}
// A method that read the contract state
public override StringValue Read(Empty input)
{
// Retrieve the value from the state
var value = State.Message.Value;
// Wrap the value in the return type
return new StringValue
{
Value = value
};
}
}
}
Step 3: Testing the Smart Contract
In the third step of the development process, you will focus on testing the smart contract thoroughly. This involves two key aspects: unit testing and testing on test networks. Firstly, you’ll write and execute unit tests for your contract to validate the functionality of each function, ensuring they behave as intended. Subsequently, you’ll deploy your contract to a test network and interact with it to assess its performance in a simulated environment, offering insights into its behaviour under real-world conditions. By rigorously testing the smart contract through these methods, you can identify and address any potential issues or bugs, ultimately ensuring its reliability and effectiveness before deployment to the main network.
Hello World example — Tests (C#)
using System.Threading.Tasks;
using Google.Protobuf.WellKnownTypes;
using Shouldly;
using Xunit;
namespace AElf.Contracts.HelloWorld
{
// This class is unit test class, and it inherit TestBase. Write your unit test code inside it
public class HelloWorldTests : TestBase
{
[Fact]
public async Task Update_ShouldUpdateMessageAndFireEvent()
{
// Arrange
var inputValue = "Hello, World!";
var input = new StringValue { Value = inputValue };
// Act
await HelloWorldStub.Update.SendAsync(input);
// Assert
var updatedMessage = await HelloWorldStub.Read.CallAsync(new Empty());
updatedMessage.Value.ShouldBe(inputValue);
}
}
}
Step 4: Developing the dApp Interface
Developing a decentralised application (dApp) interface entails crafting a user-friendly front-end that interacts seamlessly with the blockchain. To achieve this, developers utilise web development technologies such as HTML, CSS, and JavaScript to design the visual and interactive components of the dApp. This web interface serves as the gateway for users to engage with the dApp’s functionalities, offering an intuitive and responsive design that aligns with the application’s objectives. The next crucial step is integrating this front-end with the dApp’s underlying smart contract. This is where C# libraries or frameworks come into play, enabling the front-end to communicate with the blockchain. Developers leverage these tools to send transactions, query blockchain data, and listen for events triggered by the smart contract. By effectively combining these elements, developers can create a dApp interface that not only looks appealing but also provides a seamless and efficient user experience, bridging the gap between traditional web applications and blockchain-based functionalities.
Hello World example — Front-end (JavaScript)
import detectProvider from 'detect-provider';
const provider = await detectProvider();
if (provider) {
// From now on, this should always be true:
startApp(provider); // initialize your app (startApp: This is a user-defined function.)
} else {
console.log('Please install Portkey!');
}
// get accounts
const accounts = await provider.request({ method: 'requestAccounts' });
// {AELF:["AELF_Address"],tDVV:["tDVV_Address"]}
// get chain
const chain = await provider.getChain('AELF');
// get contract
const yourC = await chain.getContract('your contract address');
// Update
const req = await yourC.callSendMethod('Update', accounts.AELF[0], "New value");
// Read
const req = await yourC.callViewMethod('Read', '');
Step 5: Deploying the dApp
Deploying a decentralised application (dApp) built on C# onto the blockchain involves a series of strategic decisions and technical steps to ensure its successful launch. Firstly, developers must choose the deployment environment, weighing the options between deploying on a test network or the main network. The test network offers a risk-free environment to test the dApp’s functionalities and smart contract interactions without real-world consequences, while the main network is where the dApp will run in a live, production environment, involving real transactions and users.
Once the environment is selected, the next step is the smart contract deployment. This requires utilising the tools and frameworks provided by the target blockchain platform, which facilitates the process of uploading and initiating the smart contract on the chosen network.
Finally, the deployment of the dApp itself involves hosting the front-end application. Developers have the option to host it on a traditional server such as Amazon Web Service (AWS) or opt for decentralised storage solutions such as InterPlanetary File System (IFPS), which align with the ethos of decentralisation inherent to blockchain technology. Decentralised storage not only enhances security and resistance to censorship but also promotes data integrity and availability, making it a fitting choice for dApp deployment.
Take your Web3 Development to the Next Level with C#
Web3 development using C# represents a cutting-edge intersection of blockchain technology and modern programming. It involves leveraging the robust and versatile nature of C# to build dApps and smart contracts, primarily on blockchain platforms that are compatible with the .NET framework. This approach is particularly appealing due to C#’s strong object-oriented features and comprehensive library ecosystem. Developers can harness these capabilities to create secure, efficient, and scalable decentralised applications. As the Web3 landscape continues to evolve, C# is emerging as a powerful tool for developers looking to innovate and build on the decentralised web. aelf is committed to providing a developer-friendly environment that addresses the unique challenges and opportunities of developing in the Web3 space. To further ease developers into Web3 development using C#, we will be conducting a Developer Workshop titled ‘Hands-on Smart Contract Workshop: Writing & Deploying with C#’ on 29 Feb in Singapore. Do sign up here!
Here are some developer resources and if you have any questions on building on the aelf blockchain, feel free to reach out to the team on Telegram:
- AElfProject: https://github.com/AElfProject
- AElf Documentation: https://docs.aelf.io/
- Portkey: https://github.com/Portkey-Wallet/
- Portkey Documentation: https://doc.portkey.finance/
About aelf
aelf, a high-performance Layer 1 featuring multi-sidechain technology for unlimited scalability. aelf blockchain is designed to power the development of Web3 and support its continuous advancement into the future. Founded in 2017 with its global hub based in Singapore, aelf is one of the pioneers of the mainchain-sidechain architecture concept. Incorporating key foundational components, including AEDPoS, aelf’s variation of a Delegated Proof-of-Stake (DPoS) consensus protocol; parallel processing; peer-to-peer (P2P) network communication; cross-chain bridges, and a dynamic side chain indexing mechanism, aelf delivers a highly efficient, safe, and modular ecosystem with high throughput, scalability, and interoperability.
aelf facilitates the building, integrating, and deploying of smart contracts and decentralised apps (dApps) on its blockchain with its native C# software development kit (SDK) and SDKs in other languages, including Java, JS, Python, and Go. aelf’s ecosystem also houses a range of dApps to support a flourishing blockchain network. aelf is committed to fostering innovation within its ecosystem and remains dedicated to driving the development of Web3 and the adoption of blockchain technology.
Find out more about aelf and stay connected with our community: