1. Створіть контракт, який матиме змінну-лічильник. Додайте функції для:
Збільшення лічильника.
Зменшення лічильника.
Отримання поточного значення лічильника.
// SPDX-License-Identifier: MIT
pragma solidity ^ 0.8.20 ;
contract Counter {
int256 private count;
function increment () public {
count += 1 ;
}
function decrement () public {
count -= 1 ;
}
function getCount () public view returns (int256 ) {
return count;
}
}
2. Реалізуйте контракт для управління списком задач:
Додайте задачі (рядки).
Видаляйте задачі.
Зчитуйте всі задачі.
Використовуйте масив для зберігання задач.
// SPDX-License-Identifier: MIT
pragma solidity ^ 0.8.20 ;
contract TodoList {
string [] private tasks;
function addTask (string memory _task ) public {
tasks.push (_task);
}
function deleteTask (uint256 index ) public {
require (index < tasks.length , "Invalid index " );
for (uint256 i = index; i < tasks.length - 1 ; i++ ) {
tasks[i] = tasks[i + 1 ];
}
tasks.pop ();
}
function getTasks () public view returns (string [] memory ) {
return tasks;
}
}
3. Створіть контракт, який дозволяє додавати товари (структура з полями назва, ціна).
Реалізуйте функцію додавання товару.
Зробіть функцію для покупки товару з перевіркою балансу на рахунку покупця (використовуйте змінну msg.value).
Додайте можливість отримати список усіх доступних товарів.
// SPDX-License-Identifier: MIT
pragma solidity ^ 0.8.20 ;
contract Store {
struct Product {
string name;
uint256 price;
bool available;
}
Product[] private products;
address public owner;
constructor () {
owner = msg .sender ;
}
function addProduct (string memory _name , uint256 _price ) public {
products.push (Product (_name, _price, true ));
}
function buyProduct (uint256 index ) public payable {
require (index < products.length , "Product not exist " );
Product storage product = products[index];
require (product.available, "Product already sold " );
require (msg .value >= product.price, "Not enough money " );
product.available = false ;
payable (owner).transfer (product.price);
if (msg .value > product.price) {
payable (msg .sender ).transfer (msg .value - product.price);
}
}
function getProducts () public view returns (Product[] memory ) {
return products;
}
}
4. Реалізуйте просту систему голосування:
Створіть масив або структуру для кандидатів (наприклад, імена).
Додайте функцію, що дозволяє голосувати за кандидата.
Зробіть функцію для перегляду результатів голосування.
// SPDX-License-Identifier: MIT
pragma solidity ^ 0.8.20 ;
contract Voting {
struct Candidate {
string name;
uint256 voteCount;
}
Candidate[] private candidates;
constructor (string [] memory candidateNames ) {
for (uint i = 0 ; i < candidateNames.length ; i++ ) {
candidates.push (Candidate (candidateNames[i], 0 ));
}
}
function vote (uint256 candidateIndex ) public {
require (candidateIndex < candidates.length , "Candidate not exist " );
candidates[candidateIndex].voteCount += 1 ;
}
function getResults () public view returns (Candidate[] memory ) {
return candidates;
}
}
5. Реалізуйте контракт, що підтримує систему підписок:
Користувачі можуть сплачувати за доступ до послуги на визначений період.
Реалізуйте функції перевірки активної підписки користувача.
Додайте можливість адміністратору змінювати вартість підписки.
// SPDX-License-Identifier: MIT
pragma solidity ^ 0.8.20 ;
contract SubscriptionService {
address public admin;
uint256 public subscriptionPrice;
uint256 public subscriptionDuration;
mapping (address => uint256 ) public subscriptionEnd;
constructor (uint256 _price , uint256 _duration ) {
admin = msg .sender ;
subscriptionPrice = _price;
subscriptionDuration = _duration;
}
function subscribe () public payable {
require (msg .value >= subscriptionPrice, "Not enough money " );
if (subscriptionEnd[msg .sender ] < block .timestamp ) {
subscriptionEnd[msg .sender ] = block .timestamp + subscriptionDuration;
} else {
subscriptionEnd[msg .sender ] += subscriptionDuration;
}
payable (admin).transfer (msg .value );
}
function hasActiveSubscription (address user ) public view returns (bool ) {
return subscriptionEnd[user] > block .timestamp ;
}
function changeSubscriptionPrice (uint256 _newPrice ) public {
require (msg .sender == admin, "admin can change price " );
subscriptionPrice = _newPrice;
}
}
6. Реалізуйте контракт, який дозволяє спільноті голосувати за проекти для фінансування:
Користувачі можуть пропонувати свої проекти з описом і необхідною сумою.
Кожен користувач може голосувати за проект.
Реалізуйте логіку розподілу коштів на основі голосів.
// SPDX-License-Identifier: MIT
pragma solidity ^ 0.8.20 ;
contract ProjectFunding {
struct Project {
string name;
string description;
uint256 requiredAmount;
uint256 votes;
address payable author;
bool funded;
}
Project[] private projects;
address public admin;
mapping (uint256 => mapping (address => bool )) public hasVoted;
constructor () {
admin = msg .sender ;
}
function depositFunds () public payable {}
function proposeProject (
string memory _name ,
string memory _description ,
uint256 _requiredAmount
) public {
projects.push (
Project ({
name: _name,
description: _description,
requiredAmount: _requiredAmount,
votes: 0 ,
author: payable (msg .sender ),
funded: false
})
);
}
function voteForProject (uint256 _projectIndex ) public {
require (_projectIndex < projects.length , "Project does not exist " );
require (! hasVoted[_projectIndex][msg .sender ], "You already voted " );
hasVoted[_projectIndex][msg .sender ] = true ;
projects[_projectIndex].votes++ ;
}
function getProjects () public view returns (Project[] memory ) {
return projects;
}
function getWinningProject () public view returns (uint256 ) {
require (projects.length > 0 , "No projects available " );
uint256 winningIndex = 0 ;
for (uint256 i = 1 ; i < projects.length ; i++ ) {
if (projects[i].votes > projects[winningIndex].votes) {
winningIndex = i;
}
}
return winningIndex;
}
function fundWinningProject () public {
require (msg .sender == admin, "admin can fund projects " );
require (projects.length > 0 , "No projects available " );
uint256 winningIndex = getWinningProject ();
Project storage winner = projects[winningIndex];
require (! winner.funded, "Project already funded " );
require (address (this ).balance >= winner.requiredAmount, "Not enough money " );
winner.funded = true ;
(bool success , ) = winner.author.call {value: winner.requiredAmount}("" );
require (success, "Transfer failed " );
}
function getContractBalance () public view returns (uint256 ) {
return address (this ).balance;
}
}