0
0
Blockchain / Solidityprogramming~30 mins

Library contracts in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Library Contracts
📖 Scenario: You are building a simple blockchain project where you want to reuse common functions across multiple smart contracts. Instead of copying code, you will create a library contract that other contracts can call. This helps keep your code clean and efficient.
🎯 Goal: Create a library contract with a function to add two numbers. Then create a main contract that uses this library to add two numbers and show the result.
📋 What You'll Learn
Create a library contract named MathLib with a function add(uint a, uint b) returns (uint) that returns the sum of a and b.
Create a contract named Calculator that uses MathLib to add two numbers.
In Calculator, create a function calculateSum(uint x, uint y) returns (uint) that calls MathLib.add and returns the result.
Write a function to get the sum and print it.
💡 Why This Matters
🌍 Real World
Library contracts help developers reuse common code in blockchain projects, making smart contracts smaller and easier to maintain.
💼 Career
Understanding library contracts is important for blockchain developers to write efficient and modular smart contracts used in decentralized applications.
Progress0 / 4 steps
1
Create the library contract
Create a library contract called MathLib with a public function add that takes two uint parameters a and b and returns their sum as uint.
Blockchain / Solidity
Need a hint?

Use the library keyword to create a library contract. The add function should be public and pure because it does not change or read state.

2
Create the main contract and import the library
Create a contract called Calculator. Inside it, add a function calculateSum that takes two uint parameters x and y. This function will use MathLib.add to add the two numbers and return the result.
Blockchain / Solidity
Need a hint?

Define the Calculator contract and inside it create the calculateSum function. Call the library function using MathLib.add(x, y).

3
Add a function to call and print the sum
Inside the Calculator contract, add a public function called getSum that calls calculateSum with the numbers 5 and 7 and returns the result.
Blockchain / Solidity
Need a hint?

Create a simple function getSum that calls calculateSum with fixed numbers and returns the result.

4
Print the result of the sum
Write a line of code to call getSum() from the Calculator contract and print the result.
Blockchain / Solidity
Need a hint?

Solidity contracts do not print like normal programs. You get the result by calling the function from outside the contract (like a test or blockchain interface). The sum of 5 and 7 is 12.