bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 41쪽 중 20쪽
lls Smart Contract Method
: It interacts with the blockchain smart contract to update the task status by passind the
completed
status as an argument.
Next, we'll write the
Delete the Task
function.
Delete the Task
Write a function to delete an existing task.
Scroll down to find the comment
// step 6 - Delete the Task
.
Replace the existing
deleteTask
function with this code snippet:
home/index.tsx
// step 6 - Delete the Task
const
deleteTask
=
async
(
data
:
ITodoObject
)
=>
{
let
deleteLoadingId
;
try
{
// Start Loading
deleteLoadingId
=
toast
.
loading
(
"Removing a Task.."
)
;
setDeletingId
(
data
.
taskId
)
;
// set Deleting Id for Loading on Button
// Call UpdateTask Function of Smart Contract and update the status as "Removed"
await
smartContract
?.
callSendMethod
(
"UpdateTask"
,
currentWalletAddress
as
string
,
{
...
data
,
status
:
TASK_STATUS
.
removed
}
)
;
// Update Loading Message with Success
toast
.
update
(
deleteLoadingId
,
{
render
:
"Task Successfully Removed"
,
type
:
"success"
,
isLoading
:
false
,
}
)
;
// Get New Data from Contract
await
getTodoData
(
)
;
}
catch
(
error
:
any
)
{
// Update Loading Message with Error
toast
.
update
(
deleteLoadingId
as
Id
,
{
render
:
error
.
message
,
type
:
"error"
,
isLoading
:
false
,
}
)
;
}
finally
{
setDeletingId
(
null
)
;
// Remove Loading Message
removeNotification
(
deleteLoadingId
as
Id
)
;
}
}
;
What This Function Does:
Calls Smart Contract Method
: It interacts with the blockchain smart contract to delete the existing task by passing status as "removed".
Next, we'll write the
Handle Submit Form
function.
Configure Submit Form
Scroll down to find the comment
// step 7 - Handle Submit Form
.
Replace the existing
onSubmit
function with this code snippet:
home/index.tsx
// step 7 - Handle Submit Form
const
onSubmit
=
async
(
values
:
{
name
:
string
;
description
:
string
}
)
=>
{
// Check Whether Contract Initialized or not
if
(
isContractInitialized
!==
true
)
{
await
initializeContract
(
)
;
// initialize the contract if it's not initialized before
}
// Check Whether Form is for Create or Update the Task
if
(
!
!
updateId
)
{
await
updateTask
(
values
)
;
// Call updateTask for Update the task
}
else
{
await
createNewTask
(
values
)
;
// Call createNewTask for Create a new task
}
}
;
What This Function Does:
Check initialized contract
: It checks whether the smart contract is initialized or not by using
initializeContract
function.
Update Task
: Call the
updateTask
function if updatedId has any value.
Create Task
: Call the
createNewTask
function if updatedId does not have any value.
Here, we have completed functions to
Create Task
,
Update Task
and
Delete Task
and now it's time to write a function to
Fetch Tasks
from the smart contract.
Fetch All Tasks
Scroll up to find the comment
// step 8 - Fetch All Tasks
.
Replace the existing
getTodoData
function with this code snippet:
home/index.tsx
// step 8 - Fetch All Tasks
const
getTodoData
=
async
(
)
=>
{
try
{
const
result
=
await
smartContract
?.
callViewMethod
(
"ListTasks"
,
{
value
:
currentWalletAddress
,
}
)
;
console
.
log
(
"result"
,
result
?.
data
)
;
setTodoData
(
result
?.
data
?
result
?.
data
.
tasks
:
[
]
)
;
}
catch
(
error
)
{
console
.
log
(
"error======"
,
error
)
;
}
finally
{
setLoading
(
false
)
;
}
}
;
Here's what the function does:
Fetches Task Data:
It calls
ListTasks
to get the list of all ToDo tasks from the ToDo smart contract.
Set Tasks on State:
Get the result data from the smart contract and set an array of all tasks into
todoData
State.
We have prepared necessary function to fetch all the tasks created from a connected user's wallet.
Now that we've written all the necessary frontend functions and components, we're ready to run the ToDo dApp application in the next step.
Run Application
In this step, we will run the ToDo dApp application.
To begin, run the following command on your terminal.
Terminal
npm
run dev
info
Note
: Ensure that you are running this command under the
todo/2-dapp
folder.
You should observe the following as shown below.
Upon clicking on the
localhost URL
, you should be directed to the ToDo dApp landing page as shown below.
tip
If you are developing and testing this with github codespace, you can use port forward to test the web server that is running in codespace, here is the link on how to use port forward for codespace
https://docs.github.com/en/codespaces/developing-in-a-codespace/forwarding-ports-in-your-codespace
Usually codespace will automatically forward port, you should see a pop-up message at the bottom right of your codespace browser window as shown in the diagram below:
Click the link to open the ToDo dApp in the browser.
Create Portkey Wallet
info
Portkey is the first AA wallet from aelf's ecosystem, migrating users, developers and projects from Web2 to Web3 with DID solution.
Users can swiftly log into Portkey via their Web2 social info with no private keys or mnemonics required. Underpinned by social recovery and decentralized guardian design, Portkey safeguards users' assets from centralized control and theft. Portkey has a unique payment delegation mechanism which enables interested parties to function as delegatees to pay for user activities on users' behalf. This means that users can create accounts for free and fees for other usages may also be covered in Portkey.
Portkey also provides crypto on/off-ramp services, allowing users to exchange fiat with crypto freely. It supports the storage and management of various digital assets such as tokens, NFTs, etc. The compatibility with multi-chains and seamless connection to all kinds of DApps makes Portkey a great way to enter the world of Web3.
With DID solution as its core, Portkey provides both Portkey Wallet and Portkey SDKs.
For more information, you may visit the official documentation for Portkey at
https://doc.portkey.finance/
.
Download the Chrome extension for Portkey from
https://chromewebstore.google.com/detail/portkey-wallet/iglbgmakmggfkoidiagnhknlndljlolb
.
info
The Portkey extension supports Chrome browser only (for now). Please ensure that you are using Chrome browser.
You may download Chrome from
https://www.google.com/intl/en_sg/chrome/
.
Once you have downloaded the extension, you should see the following on your browser as shown below.
Click on
Get Start
and you should see the following interface as shown below.
Sign up
Switch to
aelf Testnet
network by selecting it:
danger
Please make sure you are using
aelf Testnet
in order to be able to receive your testnet tokens from the Faucet.
Proceed to sign up with a Google Account or your preferred login method and complete the necessary accounts creation prompts and you should observe the following interface once you have signed up.
With that, you have successfully created your very first Portkey wallet within seconds. How easy was that?
info
It is highly recommended to pin the Portkey wallet extension for easier access and navigation to your Portkey wallet!
Next, click on ‘Open Portkey’ and you should now observe the following as shown below.
Connect Portkey Wallet
Click on
"Connect Wallet"
to connect your Portkey wallet.
The button will change to
"Your Wallet Address"
when the connection is successful.
Create a New Task
Click on
"Add New"
button to create a new task.
You will see the pop-up modal with form to create a new task. Please fill all the necessary fields like
Name
,
Description
and
Category
.
Click on
Create New Task
Button.
Now, You will receive a transaction request on your portkey wallet to
Sign
the transaction.
Click on
Sign
the transaction.
After the transaction is successfully processed, your first task will be created✅.
Your task item looks like below with the following details -
Name
,
Description
,
Last Updated Time
,
Create Date and Time
,
You will be able to perform these following action for a selected task -
Edit
,
Complete
, and
Remove
.
As we have
Created a Task
successfully, let's update the task details.
Edit the Task
Click on the
"Edit"
button to edit the task.
You will see the pop-up modal with form to edit the task. Edit the necessary fields according to your need.
Click on
Update Task
Button.
Now, You will recieve a transaction request on your portkey wallet to
Sign
the transaction.
Click on
Sign
the transaction.
After the transaction is successfully processed, your task details will be Updated✅.
As we have
Edited a Task
successfully. Let's move that task to completed state.
Complete the Task
Click on the
"Complete"
button to move the task to
Completed
status.
Now, You will recieve a transaction request on your portkey wallet to
Sign
the transaction.
Click on
Sign
the transaction.
After the transaction is successfully processed, your task will be moved to the completed tab✅.
As we have performed
Complete Task
successfully. Let's remove the completed task.
Remove the Task
Click on
"Remove"
button to remove the task.
Now, You will recieve a transaction request on your portkey wallet to
Sign
the transaction.
Click on
Sign
the transaction.
After the transaction is successfully processed, your task will be moved to the removed tab✅.
success
🎉 Congratulations Learners! You have successfully built your ToDo dApp.
🎯 Conclusion
🎉 Congratulations on successfully completing the
ToDo dApp
tutorial! 🎉 You've taken important steps in setting up your development environment, developing and deploying a smart contract on ToDo dApp, and building a fully functional ToDo decentralized application on the aelf blockchain. 🌟
📚 What You've Learned
Throughout this tutorial, you've mastered:
🛠️ Setting Up Your Development Environment:
You prepared your workspace by installing and configuring all the necessary tools to kickstart your smart contract project.
💻 Developing Your Smart Contract:
You created the foundation of your ToDo dApp by writing and building the smart contract that manages tasks, from creation to deletion.
🚀 Deploying the Smart Contract:
You deployed your smart contract to the aelf blockchain, enabling its functionalities to be used in a live environment.
🔧 Interacting with Your Deployed Smart Contract:
You connected your frontend to the blockchain, integrated Portkey for wallet connectivity, and implemented functions to manage tasks such as creating, updating, and deleting directly through the dApp.
🔍 Final Output
By now, you should have:
📜 A deployed smart contract that powers your ToDo dApp, managing tasks with functionalities for creation, updating, status management, and deletion.
💻 A fully operational ToDo dApp, allowing users to interact with the smart contract to efficiently manage their tasks.
➡️ What's Next?
With the basics under your belt, consider exploring more advanced topics:
📈 Enhancing Smart Contract Logic:
Introduce more complex features to your ToDo dApp, such as prioritization, deadlines, or collaboration tools.
🔒 Improving Security:
Ensure your dApp and smart contract are secure by implementing best practices and security measures.
🌍 Exploring Cross-Chain Features:
Expand your dApp’s capabilities by exploring aelf’s cross-chain interoperability, enabling interaction with other blockchains.
The possibilities with blockchain technology and decentralized applications are endless. You're now well-equipped to take your ToDo dApp to the next level. Keep building, innovating, and exploring with aelf. 🚀
Happy coding and expanding your
ToDo dApp! 😊
Step 1 - Setting up your development environment
Step 2 - Develop Smart Contract
Start Your Smart Contract Project
Adding Your Smart Contract Code
Building Smart Contract
Step 3 - Deploy Smart Contract
Step 4 - Interact with Your Deployed Smart Contract through dApp
Project Setup
Configure Portkey Provider & Write Connect Wallet Function
Configure Connect Wallet Function
Configure Create Task Form
Check Contract Initialization
Initialize Contract
Create a New Task
Update an Existing Task
Update the Task Status
Delete the Task
Configure Submit Form
Fetch All Tasks
Run Application
🎯 Conclusion
## /quick-start/developers/tic-tac-toe-dapp
On this page
Description
: The Tic-Tac-Toe dApp is a decentralized gamify application that allows users to play the classic game of Tic-Tac-Toe on the aelf blockchain. It offers a simple and interactive interface where two players can compete against each other, with game data securely stored and verified on the aelf blockchain.
Purpose
: The purpose of the Tic-Tac-Toe gamify dApp is to demonstrate how traditional games can be implemented on the aelf blockchain, ensuring transparency and immutability of game outcomes. It serves as an educational tool for learning smart contract development and the basics of decentralized application functionality.
Difficulty Level
: Moderate
Step 1 - Setting up your development environment
Local
Codespaces
Basic knowledge of terminal commands
IDE
- Install
VS Code
Note for Apple Silicon users:
Ensure that Rosetta is installed, if it is not, use the following command:
Terminal
softwareupdate --install-rosetta
Install Required Packages
Install dotnet 8.0.x SDK
Install aelf contract templates
Linux and macOs
Windows
Terminal
dotnet new
--install
AElf.ContractTemplates
Command Prompt
dotnet new
install
AElf.ContractTemplates
AELF.ContractTemplates contains various predefined templates for the ease of developing smart contracts on the aelf blockchain.
Install aelf deploy tool
Terminal
dotnet tool
install
--global
aelf.deploy
aelf.deploy is a utility tool for deploying smart contracts on the aelf blockchain.
Please remember to export PATH after installing aelf.deploy.
info
ℹ️ Note: If you have installed aelf.deploy and your terminal says that there is no such command available, please uninstall and install aelf.deploy.
Install Node.js and Yarn
Install Node.js
Install Yarn
Install aelf-command
Linux and macOs
Windows
Terminal
sudo
npm
i
-g
aelf-command
Command Prompt
npm
i
-g
aelf-command
aelf-command is a CLI tool for interacting with the aelf blockchain, enabling tasks like creating wallets and managing transactions.
Provide required permissions while installing aelf-command globally.
Visit
aelf-devcontainer-template
.
Click the
Use this template
button. Choose
Create a new repository
.
Enter a suitable repository name. Click
Create repository
.
Within the GitHub interface of your new repository, click on
Code
.
Select
Codespaces
.
Click on the
+
sign to create a new Codespace.
After some time, your workspace will load with the contents of the repository.
You can now continue your development using GitHub Codespaces.
Step 2 - Develop Smart Contract
Start Your Smart Contract Project
Open your
Terminal
.
Enter the following command to generate a new project:
Terminal
mkdir
tic-tac-toe-dapp
cd
tic-tac-toe-dapp
dotnet new aelf
-n
TicTacToe
Adding Your Smart Contract Code
Now that we have a template tic-tac-toe project, we can customise the template to incorporate our own contract logic. Let's start by implementing methods to handle the basic functionality for starting the Tic-Tac-Toe game, allowing players to make moves, retrieving the game board data and current status, and checking if the game has been initialized. Tic-Tac-Toe dApp includes the below functionalities:
Start a new game
Make a move in the ongoing game
Get the board details
Get the current status of the board
Get the initial status of the board
Enter this command in your
Terminal
.
Terminal
cd
src
Defining Methods and Messages
Rename the proto file name
hello_world_contract.proto
inside folder
Protobuf/contract/
to
tic_tac_toe.proto
:
Terminal
mv
Protobuf/contract/hello_world_contract.proto Protobuf/contract/tic_tac_toe.proto
The
.proto
file defines the structure and serialization of data, ensuring consistent communication and data exchange between the contract and external systems.
Open the project with your IDE.
The implementation of
tic_tac_toe.proto
file inside folder
src/Protobuf/contract/
is as follows:
tic_tac_toe.proto
syntax
=
"proto3"
;
import
"aelf/options.proto"
;
import
"google/protobuf/empty.proto"
;
import
"google/protobuf/wrappers.proto"
;
import
"Protobuf/reference/acs12.proto"
;
// The namespace of this class
option
csharp_namespace
=
"AElf.Contracts.TicTacToe"
;
service
TicTacToe
{
// The name of the state class the smart contract is going to use to access blockchain state
option
(
aelf
.
csharp_state
)
=
"AElf.Contracts.TicTacToe.TicTacToeState"
;
option
(
aelf
.
base
)
=
"Protobuf/reference/acs12.proto"
;
rpc
Initialize
(
google
.
protobuf
.
Empty
)
returns
(
google
.
protobuf
.
Empty
)
{
}
rpc
StartGame
(
google
.
protobuf
.
Empty
)
returns
(
google
.
protobuf
.
StringValue
)
{
}
rpc
MakeMove
(
MoveInput
)
returns
(
google
.
protobuf
.
StringValue
)
{
}
rpc
GetBoard
(
google
.
protobuf
.
Empty
)
returns
(
Board
)
{
option
(
aelf
.
is_view
)
=
true
;
}
rpc
GetGameStatus
(
google
.
protobuf
.
Empty
)
returns
(
GameStatus
)
{
option
(
aelf
.
is_view
)
=
true
;
}
rpc
GetInitialStatus
(
google
.
protobuf
.
Empty
)
returns
(
google
.
protobuf
.
BoolValue
)
{
option
(
aelf
.
is_view
)
=
true
;
}
}
// Input for making a move
message
MoveInput
{
int32
x
=
1
;
int32
y
=
2
;
}
// A message to represent the game board
message
Board
{
repeated
string
rows
=
1
;
}
// A message to represent the game status
message
GameStatus
{
string
status
=
1
;
string
winner
=
2
;
}
rpc
methods define the callable functions within the contract, allowing external systems to interact with the contract's logic.
message
represent the structured data exchanged between the contract and external systems.
Define Contract States
The implementation of the Tic-Tac-Toe dApp state inside file
src/TicTacToeState.cs
is as follows:
src/TicTacToeState.cs
using
AElf
.
Sdk
.
CSharp
.
State
;
using
AElf
.
Types
;
namespace
AElf
.
Contracts
.
TicTacToe
{
// The state class is access the blockchain state
public
partial
class
TicTacToeState
:
ContractState
{
// A state to check if contract is initialized
public
BoolState
Initialized
{
get
;
set
;
}
public
SingletonState
<
Address
>
Owner
{
get
;
set
;
}
public
StringState
Board
{
get
;
set
;
}
// Board state as a concatenated string
public
StringState
CurrentPlayer
{
get
;
set
;
}
// X or O
public
StringState
GameStatus
{
get
;
set
;
}
// ongoing, finished, draw
public
StringState
Winner
{
get
;
set
;
}
// X or O
}
}
The
State.cs
file in an aelf blockchain smart contract holds the variables that store the contract's data, making sure this data is saved and accessible whenever the contract needs it.
Implement Tic-Tac-Toe Smart Contract
The implementation of the Tic-Tac-Toe dApp smart contract inside file
src/TicTacToe.cs
is as follows:
src/TicTacToe.cs
using
Google
.
Protobuf
.
WellKnownTypes
;
using
System
.
Collections
.
Generic
;
namespace
AElf
.
Contracts
.
TicTacToe
{
// Contract class must inherit the base class generated from the proto file
public
class
TicTacToe
:
TicTacToeContainer
.
TicTacToeBase
{
private
const
int
BoardSize
=
3
;
public
override
Empty
Initialize
(
Empty
input
)
{
if
(
State
.
Initialized
.
Value
)
{
return
new
Empty
(
)
;
}
State
.
Initialized
.
Value
=
true
;
State
.
Owner
.
Value
=
Context
.
Sender
;
ResetBoard
(
)
;
return
new
Empty
(
)
;
}
public
override
StringValue
StartGame
(
Empty
input
)
{
if
(
!
State
.
Initialized
.
Value
)
{
return
new
StringValue
{
Value
=
"Contract프로젝트로 돌아가기