Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
27 views28 pages

Solidity Smart Contract Examples

Blockchain technology report

Uploaded by

honeykavya1806
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views28 pages

Solidity Smart Contract Examples

Blockchain technology report

Uploaded by

honeykavya1806
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Activity - 1

Problem Statement: Hello World Contract

Create a simple Solidity smart contract that prints "Hello, World!"

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract HelloWorld {
string public greeting = "Hello, World!";

function getGreeting() public view returns (string memory) {


return greeting;
}
}

Output:
fi
Activity - 2
Problem Statement: Token Creation

Develop a basic ERC-20 token smart contract, including functions for transfer,
balance, and approval.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract SimpleToken {
string public name = "Simple Token";
string public symbol = "ST";
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;

event Transfer(address indexed from, address indexed to, uint256 value);

constructor(uint256 initialSupply) {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
}

function transfer(address to, uint256 value) public returns (bool success) {


require(to != address(0), "Invalid address");
require(balanceOf[msg.sender] >= value, "Insu cient balance");

balanceOf[msg.sender] -= value;
balanceOf[to] += value;

emit Transfer(msg.sender, to, value);


return true;
}
}
fi
ffi
Output:
Activity - 3
Problem Statement: ICO Crowdsale

Design a simple ICO (Initial Coin O ering) contract that allows users to buy tokens
and the owner to withdraw funds.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract SimpleICO {
address public owner;
uint256 public tokenPrice;
uint256 public totalTokens;
uint256 public tokensSold;
mapping(address => uint256) public balances;

event TokensPurchased(address indexed buyer, uint256 amount);


event FundsWithdrawn(address owner, uint256 amount);

constructor(uint256 _tokenPrice, uint256 _totalTokens) {


owner = msg.sender;
tokenPrice = _tokenPrice;
totalTokens = _totalTokens;
tokensSold = 0;
}

function buyTokens(address buyer, uint256 value) public {


require(tokensSold + value / tokenPrice <= totalTokens, "Not enough tokens
available");
uint256 numberOfTokens = value / tokenPrice;
balances[buyer] += numberOfTokens;
tokensSold += numberOfTokens;
emit TokensPurchased(buyer, numberOfTokens);
}

function withdrawFunds() public {


require(msg.sender == owner, "Only the owner can withdraw funds");
uint256 balance = address(this).balance;
payable(owner).transfer(balance);
emit FundsWithdrawn(owner, balance);
}
}
fi
ff
Output:
Activity - 4
Problem Statement: Voting Contract

Build a voting contract where users can submit and vote on proposals. Implement
safeguards to prevent double voting.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract SimpleVoting {
mapping(address => bool) public hasVoted;
mapping(string => uint256) public proposalVotes;
string[] public proposals;
event Voted(address indexed voter, string proposal);

function addProposal(string memory proposal) public {


proposals.push(proposal);
}

function vote(string memory proposal) public {


require(!hasVoted[msg.sender], "You have already voted.");
require(proposalExists(proposal), "Invalid proposal.");
proposalVotes[proposal]++;
hasVoted[msg.sender] = true;

emit Voted(msg.sender, proposal);


}

function getProposalVotes(string memory proposal) public view returns (uint256) {


return proposalVotes[proposal];
}

function proposalExists(string memory proposal) internal view returns (bool) {


for (uint256 i = 0; i < proposals.length; i++) {
if (keccak256(abi.encodePacked(proposals[i])) ==
keccak256(abi.encodePacked(proposal))) {
return true;
}
}
return false;
}
}
fi
Output:
Activity - 5
Problem Statement: Escrow Contract

Create an escrow smart contract that holds funds until prede ned conditions are met.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract SimpleEscrow {
address public payer;
address public payee;
uint256 public amount;
bool public released;

event FundsDeposited(address indexed payer, uint256 amount);


event FundsReleased(address indexed payee, uint256 amount);

constructor(address _payee) {
payer = msg.sender;
payee = _payee;
}

function deposit() public payable {


require(msg.sender == payer, "Only the payer can deposit funds");
amount += msg.value;
emit FundsDeposited(payer, msg.value);
}

function release() public {


require(msg.sender == payee, "Only the payee can release funds");
require(amount > 0, "No funds to release");
require(!released, "Funds already released");

released = true;
(bool success, ) = payable(payee).call{value: amount}("");
require(success, "Transfer failed");
emit FundsReleased(payee, amount);
}
}
fi
fi
Output:
Activity - 6
Problem Statement: Wallet Contract

Construct a wallet contract that allows funds to be locked until a speci ed time.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract TimelockWallet {
address public owner;
uint256 public releaseTime;
uint256 public balance;

event FundsDeposited(address indexed from, uint256 amount);


event FundsWithdrawn(address indexed to, uint256 amount);

constructor(uint256 _releaseTime) {
owner = msg.sender;
releaseTime = _releaseTime;
}

modi er onlyOwner() {
require(msg.sender == owner, "Only the owner can perform this action");
_;
}

modi er onlyAfter(uint256 _time) {


require(block.timestamp >= _time, "Action can only be performed after the speci ed
time");
_;
}

function deposit() public payable {


require(msg.value > 0, "Must send Ether with the deposit");
balance += msg.value;
emit FundsDeposited(msg.sender, msg.value);
}

function withdraw() public onlyOwner onlyAfter(releaseTime) {


require(balance > 0, "No funds to withdraw");
uint256 amountToWithdraw = balance;
balance = 0;
fi
fi
fi
fi
fi
(bool success, ) = payable(owner).call{value: amountToWithdraw}("");
require(success, "Transfer failed");
emit FundsWithdrawn(owner, amountToWithdraw);
}
}

Output:
Activity - 7
Problem Statement: Multi Signature Wallet

Implement a multi-signature wallet that requires multiple parties to approve


transactions.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract MultiSigWallet {
address public owner;
address public signer1;
address public signer2;
address public signer3;

event Deposit(address indexed sender, uint256 value);


event Transfer(address indexed to, uint256 value);

constructor(address _signer1, address _signer2, address _signer3) {


owner = msg.sender;
signer1 = _signer1;
signer2 = _signer2;
signer3 = _signer3;
}

receive() external payable {


emit Deposit(msg.sender, msg.value);
}

function transfer(address payable to, uint256 value) public {


require(msg.sender == owner || msg.sender == signer1 || msg.sender == signer2 ||
msg.sender == signer3, "Not authorized");
require(address(this).balance >= value, "Insu cient balance");

to.transfer(value);
emit Transfer(to, value);
}
}
fi
ffi
Output:
Activity - 8
Problem Statement: Decentralised Exchange

Design a simpli ed decentralised exchange where users can trade tokens.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract SimpleDecentralizedExchange {
address public owner;
uint256 public tokenBalance;

event TokensPurchased(address indexed buyer, uint256 ethValue, uint256


tokenAmount);
event TokensSold(address indexed seller, uint256 ethValue, uint256 tokenAmount);

constructor() {
owner = msg.sender;
}

modi er onlyOwner() {
require(msg.sender == owner, "Only the owner can perform this action");
_;
}

function buyTokens() public payable {


uint256 ethValue = msg.value;
uint256 tokenAmount = ethValue; // 1 Ether = 1 Token (simpli ed rate)

tokenBalance += tokenAmount;
emit TokensPurchased(msg.sender, ethValue, tokenAmount);
}

function sellTokens(uint256 _tokenAmount) public {


require(_tokenAmount > 0, "Invalid token amount");
uint256 ethValue = _tokenAmount; // 1 Token = 1 Ether (simpli ed rate)

require(tokenBalance >= _tokenAmount, "Insu cient token balance");

tokenBalance -= _tokenAmount;

payable(msg.sender).transfer(ethValue);
fi
fi
fi
ffi
fi
fi
emit TokensSold(msg.sender, ethValue, _tokenAmount);
}

function depositTokens(uint256 _tokenAmount) public onlyOwner {


tokenBalance += _tokenAmount;
}

function withdrawTokens(uint256 _tokenAmount) public onlyOwner {


require(tokenBalance >= _tokenAmount, "Insu cient token balance");
tokenBalance -= _tokenAmount;
}

function getContractBalance() public view returns (uint256) {


return address(this).balance;
}

function getContractTokenBalance() public view returns (uint256) {


return tokenBalance;
}
}

Output:
ffi
Activity - 9
Problem Statement: NFT Contract

Create a basic NFT contract, allowing the minting and transferring of unique
tokens.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract BasicNFT {
string public name;
string public symbol;

struct Token {
address owner;
string tokenURI;
}

Token[] public tokens;


mapping(uint256 => address) public tokenOwners;

constructor(string memory _name, string memory _symbol) {


name = _name;
symbol = _symbol;
}

function mint(string memory _tokenURI) public {


uint256 tokenId = tokens.length;
tokens.push(Token(msg.sender, _tokenURI));
tokenOwners[tokenId] = msg.sender;
}

function transfer(address _to, uint256 _tokenId) public {


require(tokenOwners[_tokenId] == msg.sender, "You don't own this token");
tokenOwners[_tokenId] = _to;
}

function getTokenURI(uint256 _tokenId) public view returns (string memory) {


return tokens[_tokenId].tokenURI;
}
}
fi
Output:
Activity - 10
Problem Statement: Lottery Contract

Develop a lottery contract with an entry fee and randomised winner selection.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract Lottery {
address public manager;
address[] public players;

event LotteryStarted();
event WinnerSelected(address winner);

constructor() {
manager = msg.sender;
}

function enter() public payable {


require(msg.value > 0.01 ether, "Entry fee is at least 0.01 Ether");
players.push(msg.sender);
}

function random() private view returns (uint) {


return uint(keccak256(abi.encodePacked(block.di culty, block.timestamp, players)));
}

function pickWinner() public restricted {


require(players.length > 0, "No players in the lottery");

uint index = random() % players.length;


address winner = players[index];
emit WinnerSelected(winner);

// Transfer the entire contract balance to the winner


payable(winner).transfer(address(this).balance);

// Reset the player array for the next round


players = new address[](0);
}
fi
ffi
modi er restricted() {
require(msg.sender == manager, "Only the manager can call this function");
_;
}

function getPlayers() public view returns (address[] memory) {


return players;
}
}

Output:
fi
Activity - 11
Problem Statement: Supply Chain Contract

Build a supply chain contract that tracks the movement of goods from producer to
consumer.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract SimpleSupplyChain {
address public producer;
address public consumer;
bool public delivered;

event ProductProduced();
event ProductShipped();
event ProductDelivered();

constructor() {
producer = msg.sender;
delivered = false;
}

modi er onlyProducer() {
require(msg.sender == producer, "Only the producer can perform this action");
_;
}

modi er onlyConsumer() {
require(msg.sender == consumer, "Only the consumer can perform this action");
_;
}

function produceProduct() public onlyProducer {


emit ProductProduced();
}

function shipProduct(address _consumer) public onlyProducer {


consumer = _consumer;
emit ProductShipped();
}
fi
fi
fi
function con rmDelivery() public onlyConsumer {
delivered = true;
emit ProductDelivered();
}
}

Output:
fi
Activity - 12
Problem Statement: KYC Contract

Build a contract that veri es user identity using KYC (Know Your Customer)
principles.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract KYC {
address public owner;

enum KYCStatus { NotSubmitted, Pending, Approved, Rejected }

struct KYCData {
KYCStatus status;
string data; // In a real KYC system, this would be more detailed user data
}

mapping(address => KYCData) public kycRecords;

event KYCSubmitted(address user);


event KYCApproved(address user);
event KYCRejected(address user);

constructor() {
owner = msg.sender;
}

modi er onlyOwner() {
require(msg.sender == owner, "Only the owner can perform this action");
_;
}

function submitKYC(string memory _data) public {


require(kycRecords[msg.sender].status == KYCStatus.NotSubmitted, "KYC already
submitted");
kycRecords[msg.sender] = KYCData(KYCStatus.Pending, _data);
emit KYCSubmitted(msg.sender);
}

function approveKYC(address _user) public onlyOwner {


fi
fi
fi
require(kycRecords[_user].status == KYCStatus.Pending, "KYC is not pending");
kycRecords[_user].status = KYCStatus.Approved;
emit KYCApproved(_user);
}

function rejectKYC(address _user) public onlyOwner {


require(kycRecords[_user].status == KYCStatus.Pending, "KYC is not pending");
kycRecords[_user].status = KYCStatus.Rejected;
emit KYCRejected(_user);
}
}

Output:
Activity - 13
Problem Statement: Subscription Contract

Develop a contract for subscription-based services, enabling users to pay on a


recurring basis.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract SubscriptionService {
address public owner;
uint256 public subscriptionPrice;
uint256 public nextPaymentDue;

event SubscriptionRenewed(address user, uint256 nextPaymentDue);

constructor(uint256 _subscriptionPrice) {
owner = msg.sender;
subscriptionPrice = _subscriptionPrice;
nextPaymentDue = block.timestamp + 30 days; // Initial subscription is for 30 days
}

modi er onlyOwner() {
require(msg.sender == owner, "Only the owner can perform this action");
_;
}

modi er subscriptionDue() {
require(block.timestamp >= nextPaymentDue, "Subscription payment is due");
_;
}

function setSubscriptionPrice(uint256 _newPrice) public onlyOwner {


subscriptionPrice = _newPrice;
}

function renewSubscription() public payable subscriptionDue {


require(msg.value >= subscriptionPrice, "Insu cient payment for subscription
renewal");

uint256 extraAmount = msg.value - subscriptionPrice;


if (extraAmount > 0) {
fi
fi
fi
ffi
payable(msg.sender).transfer(extraAmount); // Refund extra payment
}

nextPaymentDue = nextPaymentDue + 30 days; // Renew for another 30 days


emit SubscriptionRenewed(msg.sender, nextPaymentDue);
}
}

Output:
Activity - 14
Problem Statement: Stake Contract

Design a contract that allows users to stake tokens in return for rewards.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

// SPDX-License-Identi er: MIT


pragma solidity ^0.8.0;

contract SimpleStaking {
address public owner;
uint256 public rewardRate;
uint256 public totalStaked;

mapping(address => uint256) public stakedBalances;


mapping(address => uint256) public rewards;

event Staked(address staker, uint256 amount);


event Unstaked(address staker, uint256 amount);
event RewardClaimed(address staker, uint256 amount);

constructor(uint256 _rewardRate) {
owner = msg.sender;
rewardRate = _rewardRate;
}

modi er onlyOwner() {
require(msg.sender == owner, "Only the owner can perform this action");
_;
}

function stake() public payable {


require(msg.value > 0, "Amount must be greater than 0");
stakedBalances[msg.sender] += msg.value;
totalStaked += msg.value;
emit Staked(msg.sender, msg.value);
}

function unstake(uint256 _amount) public {


require(stakedBalances[msg.sender] >= _amount, "Insu cient staked balance");
stakedBalances[msg.sender] -= _amount;
totalStaked -= _amount;
payable(msg.sender).transfer(_amount);
fi
fi
ffi
emit Unstaked(msg.sender, _amount);
}

function claimReward() public {


uint256 reward = (stakedBalances[msg.sender] * rewardRate) / 100;
require(reward > 0, "No rewards to claim");
rewards[msg.sender] += reward;
emit RewardClaimed(msg.sender, reward);
}

function withdrawRewards() public {


uint256 reward = rewards[msg.sender];
require(reward > 0, "No rewards to withdraw");
rewards[msg.sender] = 0;
payable(msg.sender).transfer(reward);
}
}

Output:
Activity - 15
Problem Statement: Pet Shop Contract

Design a contract that allows users to purchase pets from the shop.

Pre-Requisites:

1. Remix Engine
2. Solidity Compiler

Program:

pragma solidity 0.5.16;

contract Adoption {
address[16] public adopters;

function adopt(uint petId) public returns (uint) {


require(petId>=0 && petId<=15);
adopters[petId]=msg.sender;
return petId;
}

function getAdopters() public view returns(address[16] memory) {


return adopters;
}
}

Output:

You might also like