https://github.com/carlosalegreur/buddyfighters-fullstackweb3nftgame
Fullstack EVM compatible NFT web3 project where you can buy NFTs and then use them to play on the project's web. The game consists on betting money in fights to the pokemon style against other players' NFTs.
https://github.com/carlosalegreur/buddyfighters-fullstackweb3nftgame
chainlink hardhat ipfs moralis nextjs nft react smart-contracts solidity web3
Last synced: 6 months ago
JSON representation
Fullstack EVM compatible NFT web3 project where you can buy NFTs and then use them to play on the project's web. The game consists on betting money in fights to the pokemon style against other players' NFTs.
- Host: GitHub
- URL: https://github.com/carlosalegreur/buddyfighters-fullstackweb3nftgame
- Owner: CarlosAlegreUr
- License: mit
- Created: 2022-07-17T15:57:43.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2023-08-07T11:13:34.000Z (about 2 years ago)
- Last Synced: 2025-03-28T14:21:39.623Z (6 months ago)
- Topics: chainlink, hardhat, ipfs, moralis, nextjs, nft, react, smart-contracts, solidity, web3
- Language: JavaScript
- Homepage:
- Size: 19.6 MB
- Stars: 3
- Watchers: 1
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# What is this repo? đ¤
Please read [**Purpose of this Repository đ¤**](#purpose-of-this-repository) (1 min read)
![]()
BuddyFighters (IN DEVELOPMENT)
PLAY IN WEB! (not deployed yet)
A fighting game on the browser using NFT technology that can be played in EVM compatible blockchains.
(completely decentralized version might come...)
# Index
- [**Purpose of this Repository đ¤**](#purpose-of-this-repository)
- [**App So Far Demo Video: đš**](#app-so-far-demo-video)
- [**About the App âšī¸**](#about-the-app)
- Potential Misuse of Power đĸ
- A Trustless Fully Decentralized Scenario đŧ
- [**Self-Audit state đĨ**](#self-audit-state)
- [**Packages & Technologies Utilized đ§°**](#packages--technologies-utilized)
- [**Brief System Overview âī¸**](#brief-system-overview)
- [**Project Structure đ**](#project-structure)
- [**Capabilities Of Deployed App đ**](#capabilities-of-deployed-app)
- [**Instructions for Local Usage âšī¸đ **](#instructions-for-local-usage)
- [**Special Thanks đ**](#special-thanks)
- [**TODO đ§**](#todo)
- [**License đ**](#license)
# **Purpose of this Repository đ¤**Learn and **gain experience in developing a robust full-stack web application** that combines traditional **`client-server-database`** mechanics and cutting-edge interactions with **`EVM-compatible blockchains and`** decentralized networks like **`IPFS`**.
## **What I Learned đ:**
- **General Insights đ**
- _**`Systems Design`**_ : Divide and Conquer, Separation of Responsibilities, Don't Repeat Yourself...
- _**`Client-Server communication`**_ : request-response, SSE...
- **`Database state management`** : CRUD operations, clean-up functions...
- **`Blockchain and IPFS interaction`** : with server and client.
- _**`Smart Contracts' System Design`**_- **Backend Development đģ:**
- Client-Server **`API development`**: routing, controllers, and services.
- **`User auth methods`** in Web2 and Web3 : signature-based-auth and token auth.
- **`Error handling, logging and job scheduling`**.
- **`MongoDB`**.
- **`System testing`** using frameworks like Mocha, Chai, and Supertest.- **Frontend Development đ¨:**
- **`Next.js`** for building **`React`** apps.
- **`UI/UX design`** for web3.At this stage, I am content to leave the project in its current state. I've achieved significant learning through practical experience and don't foresee additional learning benefits from further development. However, in the future, I might develop this project for fun. đ
Essentially, this application is a fighting game where players can battle against each other using NFTs and bet their cryptocurrencies on these fights. It includes a "change stats" feature, allowing you to adjust your NFT's stats in a fully trustless, decentralized manner.
# **App So Far Demo Video: đš**Click on the image to watch the video on **`Youtube`**.
---
The fighting and betting system isn't completely trustless, as it requires a trusted backend to execute off-chain computations when battles occur. However, it's designed in a way that makes any backend misbehavior easy to detect, enhancing the overall trustworthiness of the app's betting system.
## **Potential Misuse of Power đĸ**
One point of concern is the declaration of the winner. The backend could potentially declare any winner it prefers, regardless of the actual battle outcome. As the system stands, it's impossible to fully verify via computations alone if the backend is being dishonest. A more resource-intensive system on-chain that resolves this issue could be implemented, as explained below.
So the backend can potentially steal your current bet in an active fight if desired.
The second point of concern is in the `startFight()` function, specifically in the `_bets` variable. You have to trust that the backend will give input permissions with the correct bets and not with higher ones. The backend can potentially cooperate with a party player to give permissions, saying your bet was higher than the one you deposited, which will result in you losing your tickets.
## **A Trustless Fully Decentralized Scenario đŧ**
Basically, the decentralized scenario consists of contracts that implement:
- **Decentralized matchmaking**.
- **Decentralized activation of events on the blockchain**.
- **Decentralized fight state management**.All this is already possible; I just haven't programmed it yet. The disadvantage is that it results in a more expensive game to play due to the need for more transactions and on-chain computations. The following solution just focuses on making it truly decentralized and as cheap as possible, but always prioritizing fair play and trustless decentralized gameplay.
This is how it would be done though:
### **Decentralized Matchmaking**
You could even decentralize this app more without even requiring a backend to execute the matchmaking by doing the following:
Using the `InputControl` contract, you can allow players to give each other permissions to call `startFight()` with a previously agreed value, so now no bets would be faked.
If you mix this with the fight's states management on-chain described above, there would not even be a need for a trusted backend or a backend at all.
### **Decentralized Activation of Events on Blockchain**
This feature would be needed in order for fights, turns, or matchmaking not to potentially last forever.
This feature idea has already been explored and implemented by the Chainlink team with their [Time Based Automation](https://docs.chain.link/chainlink-automation/job-scheduler).
### **Decentralized Fight State Management**
To facilitate trustless fights, we'd need to introduce additional variables and functions to the `FightsManager` contract.
These would include:
- Mapping of the player's address to the last move executed. This variable should only be alterable by the same player, with moves potentially represented by integers.
- Mapping of the `fightId` to the last fight state. This would be a unique hashed representation of the fight state after each turn.Once the next move is updated, the next fight's state should be predictable by both clients. For the clients to agree on the next state, the game logic must be open-source.
There must also be a function that validates the next fight states. If different fight states are calculated by clients, this function could be called to figure out the right one and punish only the players who actually didn't behave correctly.
> **đ Note âšī¸**: For game mechanics with **luck-based moves**, **VRF Chainlink** contracts should be used to determine the **random luck-based result**. So users can validate the next fight state, even if the process is deterministic. Now they can **use a verified random value for the deterministically computed next state.**
Hardhat localhost network đĄ :
- Manual testing đĸ
- High Manual Tests' Coverage đĸ
- Slither syntax analysis đĸ
- Contracts Fuzz & Invariant testing âđĩī¸Any testnet or mainnet đ´ ââââ
# **Packages & Technologies Utilized đ§°**For the complete list of dependencies, please check the `package.json` file in the respective front-end and back-end directories.
Back-end dependencies đģ
- `ethers`: Ethereum blockchain and smart contracts JavaScript API.
- `@chainlink/contracts`: VRF (Verifiable Random Function) Chainlink.
- `@openzeppelin/contracts`: Secure open source smart contracts.
- `agenda`: For lightweight job scheduling.
- `express`: Web server framework.
- `mongoose`: For MongoDB object modeling.
- `jsonwebtoken`: For JSON Web Token sign and verify.
- `express-sse`: Server-side events management in express framework.
- `cors`: For enabling CORS in Express.
- `dotenv`: Management of environment variables.
- `express-winston`: Server-side logging.Front-end dependencies đ¨
- `@web3uikit/core`: UI components for DApps.
- `ethers`: Ethereum blockchain and smart contracts JavaScript API.
- `moralis`: For fast blockchain development.
- `react`: For the UI.
# **Brief System Overview âī¸**The **front end** handles API calls to the **backend** and also contains blockchain interaction code executed through a **MetaMask** provider.
The **backend** contains all the services, controllers, and route structures necessary for the **request-response communication** cycle. Additionally, it uses **Server-Side Events (SSE)** to manage matchmaking and fight mechanics services. Moreover, it can interact with the blockchain via **Alchemy** as a provider.
And don't forget to mention the front end and backend are designed to be hosted on different servers, therefore utilizing **CORS**.
Here is the **overall structure** of the project. It's divided into **two main parts**: `game` (back-end) and `website-game` (front-end).
Each directory is **further structured** to organize files based on their functionality. Not all files are listed here, only the **most relevant ones** for a high-level overview. For more detailed information, please navigate to the respective directories.
This structure allows for **modular development**, **easy maintainability**, and **scalability** of the project.
```
.
âââ game (Contains the server-side logic, blockchain scripts, contracts and tests)
â âââ README.md
â âââ src
â â âââ blockchainScripts (Scripts directly interacting with the blockchain)
â â âââ contracts (Smart Contracts written in Solidity)
â â âââ controllers (Controllers to manage route handling)
â â âââ database (Mongoose models and DB connection settings)
â â âââ logs (Different log files and the logger script)
â â âââ middleware (Middleware for Express.js, JWT AUTH and SSE management)
â â âââ routes (Routes for Express.js)
â â âââ serverConfig (Server configuration file)
â â âââ services (Services to handle business logic)
â â âââ tasks (Background tasks setup)
â â âââ tests (Unit and integration tests for the blockchain scripts and services)
â â âââ utils (Utility scripts used across the project)
â âââ hardhat.config.js
â âââ helper-hardhat-config.js
â âââ nodemon.json
â âââ package.json
â âââ yarn.lock
âââ LICENSE
âââ package.json
âââ printChildrenDirectories.sh
âââ readme-images (images used in the readmes)
âââ README.md
âââ TODO.md
âââ website-game (Contains the client-side logic, UI components, and styles)
â âââ components (React components for UI)
â âââ constants (JSON and index files with constant values)
â âââ next.config.js
â âââ package.json
â âââ pages (React pages)
â âââ public (Static files served by Next.js)
â âââ README.md
â âââ styles (CSS and SCSS style files)
â âââ utils (Utility scripts used across the project)
â âââ yarn.lock
âââ yarn.lock
```
# **Capabilities of the Deployed App đ**As a personal portfolio project, the public website and backend are limited to supporting only **4 authenticated users** playing or using backend services simultaneously. This restriction allows me to host the project for free. (:D)
---
# **Instructions for Local Usage âšī¸đ **To run the application locally, follow these steps:
1. Download the code.
1. Create an `.env` file and make sure you have all the API keys and variables set. Check them here [.env.example]()
1. Start a Hardhat node.
1. Mint some NFTs using the provided minting script. (blockchainScripts/00-useScript.js)
1. Launch the website on two different browsers or in sessions that don't share cookies. Recommended `Brave`, `Chrome`, `Firefox`.
1. Connect MetaMask to the local Hardhat network using the first two default addresses, one for each browser.
1. Run the server file.
1. Start the MongoDB database.---
## **Special thanks đ**Thanks to @aonsager for allowing me to use his images as long as I don't create a commercial product out of them.
Creator of => https://pokemon.alexonsager.net/
Source of the pokemon fusions images used in this project.
![]()
![]()
![]()
![]()
![]()
---
## someday...
1. Apply fuzz testing and symbolic analysis in smart contracts.
2. Try to improve manual smart contract tests.
3. Improve routes security type checking in backend.
4. Finish and test frontend, API and backend services.
5. Improve READMEs: intructions for local usage.
6. Try to improve tests' readability.
7. Create the completely decentralized trustless version of BuddyFighters!MIT
---
> GitHub [@CarlosAlegreUr](https://github.com/CarlosAlegreUr)