Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Defend nfts #265

Merged
merged 8 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions backend/routes/nft.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package routes

import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
Expand All @@ -19,6 +21,7 @@ func InitNFTRoutes() {
http.HandleFunc("/get-new-nfts", getNewNFTs)
http.HandleFunc("/get-my-nfts", getMyNFTs)
http.HandleFunc("/get-nft-likes", getNftLikeCount)
http.HandleFunc("/get-nft-pixel-data", getNftPixelData)
// http.HandleFunc("/like-nft", LikeNFT)
// http.HandleFunc("/unlike-nft", UnLikeNFT)
http.HandleFunc("/get-top-nfts", getTopNFTs)
Expand Down Expand Up @@ -220,6 +223,65 @@ func getNewNFTs(w http.ResponseWriter, r *http.Request) {
routeutils.WriteDataJson(w, string(nfts))
}

func getNftPixelData(w http.ResponseWriter, r *http.Request) {
tokenId := r.URL.Query().Get("tokenId")
if tokenId == "" {
routeutils.WriteErrorJson(w, http.StatusBadRequest, "TokenId parameter is required")
return
}

// First get the NFT data to access the imageHash
nft, err := core.PostgresQueryOneJson[NFTData]("SELECT * FROM nfts WHERE token_id = $1", tokenId)
if err != nil {
routeutils.WriteErrorJson(w, http.StatusNotFound, "NFT not found")
return
}

var nftData NFTData
if err := json.Unmarshal([]byte(nft), &nftData); err != nil {
routeutils.WriteErrorJson(w, http.StatusInternalServerError, "Failed to parse NFT data")
return
}

// Try to read from file first
roundNumber := os.Getenv("ROUND_NUMBER")
if roundNumber == "" {
roundNumber = "1" // Default to round 1 if not set
}

filename := fmt.Sprintf("nfts/round-%s/images/nft-%s.png", roundNumber, tokenId)
fileBytes, err := os.ReadFile(filename)
if err != nil {
routeutils.WriteErrorJson(w, http.StatusInternalServerError, "Failed to read image file")
return
}

// If we have the file, process it using imageToPixelData
pixelData, err := imageToPixelData(fileBytes, 10)
if err != nil {
routeutils.WriteErrorJson(w, http.StatusInternalServerError, "Failed to process image")
return
}

response := struct {
Width int `json:"width"`
Height int `json:"height"`
PixelData []int `json:"pixelData"`
}{
Width: nftData.Width,
Height: nftData.Height,
PixelData: pixelData,
}

jsonResponse, err := json.Marshal(response)
if err != nil {
routeutils.WriteErrorJson(w, http.StatusInternalServerError, "Failed to create response")
return
}

routeutils.WriteDataJson(w, string(jsonResponse))
}

func mintNFTDevnet(w http.ResponseWriter, r *http.Request) {
// Disable this in production
if routeutils.NonProductionMiddleware(w, r) {
Expand Down
28 changes: 16 additions & 12 deletions backend/routes/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func hexToRGBA(colorBytes string) color.RGBA {
return color.RGBA{uint8(r), uint8(g), uint8(b), 255}
}

func imageToPixelData(imageData []byte) ([]int, error) {
func imageToPixelData(imageData []byte, scaleFactor int) ([]int, error) {
img, _, err := image.Decode(bytes.NewReader(imageData))
if err != nil {
return nil, err
Expand All @@ -96,16 +96,20 @@ func imageToPixelData(imageData []byte) ([]int, error) {

bounds := img.Bounds()
width, height := bounds.Max.X, bounds.Max.Y
pixelData := make([]int, width*height)

for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
scaledWidth := width / scaleFactor
scaledHeight := height / scaleFactor
pixelData := make([]int, scaledWidth*scaledHeight)

for y := 0; y < height; y += scaleFactor {
for x := 0; x < width; x += scaleFactor {
newX := x / scaleFactor
newY := y / scaleFactor
rgba := color.RGBAModel.Convert(img.At(x, y)).(color.RGBA)
if rgba.A < 128 { // Consider pixels with less than 50% opacity as transparent
pixelData[y*width+x] = 0xFF
pixelData[newY*scaledWidth+newX] = 0xFF
} else {
closestIndex := findClosestColor(rgba, palette)
pixelData[y*width+x] = closestIndex
pixelData[newY*scaledWidth+newX] = closestIndex
}
}
}
Expand Down Expand Up @@ -229,7 +233,7 @@ func buildTemplateImg(w http.ResponseWriter, r *http.Request) {
return
}

imageData, err := imageToPixelData(fileBytes)
imageData, err := imageToPixelData(fileBytes, 1)
if err != nil {
routeutils.WriteErrorJson(w, http.StatusInternalServerError, "Failed to convert image to pixel data")
return
Expand Down Expand Up @@ -298,7 +302,7 @@ func addTemplateImg(w http.ResponseWriter, r *http.Request) {
}
bounds := img.Bounds()
width, height := bounds.Max.X-bounds.Min.X, bounds.Max.Y-bounds.Min.Y
if width < 5 || width > 64 || height < 5 || height > 64 {
if width < 5 || width > 256 || height < 5 || height > 256 {
routeutils.WriteErrorJson(w, http.StatusBadRequest, "Invalid image dimensions")
return
}
Expand All @@ -314,7 +318,7 @@ func addTemplateImg(w http.ResponseWriter, r *http.Request) {

r.Body.Close()

imageData, err := imageToPixelData(fileBytes)
imageData, err := imageToPixelData(fileBytes, 1)
if err != nil {
routeutils.WriteErrorJson(w, http.StatusInternalServerError, "Failed to convert image to pixel data")
return
Expand Down Expand Up @@ -372,7 +376,7 @@ func addTemplateData(w http.ResponseWriter, r *http.Request) {
return
}

if width < 5 || width > 64 || height < 5 || height > 64 {
if width < 5 || width > 256 || height < 5 || height > 256 {
routeutils.WriteErrorJson(w, http.StatusBadRequest, "Invalid image dimensions")
return
}
Expand Down Expand Up @@ -473,7 +477,7 @@ func getTemplatePixelData(w http.ResponseWriter, r *http.Request) {
}

// Convert image to pixel data using existing function
pixelData, err := imageToPixelData(fileBytes)
pixelData, err := imageToPixelData(fileBytes, 1)
if err != nil {
routeutils.WriteErrorJson(w, http.StatusInternalServerError, "Failed to process image")
return
Expand Down
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ services:
- ART_PEACE_END_TIME=3000000000
- ART_PEACE_HOST=0328ced46664355fc4b885ae7011af202313056a7e3d44827fb24c9d3206aaa0
- ROUND_NUMBER=1
volumes:
- nfts:/app/nfts
consumer:
build:
dockerfile: backend/Dockerfile.consumer
Expand Down
2 changes: 1 addition & 1 deletion frontend/public/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
Expand Down
53 changes: 42 additions & 11 deletions frontend/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -1009,18 +1009,49 @@ function App() {
return [];
};

// Only call getTemplatePixelData if overlayTemplate exists and has a hash
if (overlayTemplate && overlayTemplate.hash) {
// Need to handle the Promise properly
getTemplatePixelData(overlayTemplate.hash)
.then((data) => setTemplatePixels(data))
.catch((error) => {
console.error('Error fetching template pixels:', error);
const getNftPixelData = async (tokenId) => {
if (tokenId !== null) {
const response = await fetchWrapper(
`get-nft-pixel-data?tokenId=${tokenId}`
);
if (!response.data) {
console.error('NFT pixel data not found');
return [];
}
return response.data;
}
return [];
};

const fetchPixelData = async () => {
try {
if (!overlayTemplate) {
setTemplatePixels([]);
});
} else {
setTemplatePixels([]);
}
return;
}

// Handle NFT overlay case
if (overlayTemplate.isNft && overlayTemplate.tokenId !== undefined) {
const data = await getNftPixelData(overlayTemplate.tokenId);
setTemplatePixels(data);
return;
}

// Handle template overlay case
if (overlayTemplate.hash) {
const data = await getTemplatePixelData(overlayTemplate.hash);
setTemplatePixels(data);
return;
}

setTemplatePixels([]);
} catch (error) {
console.error('Error fetching pixel data:', error);
setTemplatePixels([]);
}
};

fetchPixelData();
}, [overlayTemplate]);

return (
Expand Down
16 changes: 8 additions & 8 deletions frontend/src/canvas/NFTSelector.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,14 @@ const NFTSelector = (props) => {
let width = endX - startX;
let height = endY - startY;
// Max NFT sizes
if (width > 64) {
width = 64;
if (width > 256) {
width = 256;
if (x < initX) {
startX = endX - width;
}
}
if (height > 64) {
height = 64;
if (height > 256) {
height = 256;
if (y < initY) {
startY = endY - height;
}
Expand Down Expand Up @@ -190,14 +190,14 @@ const NFTSelector = (props) => {
let width = endX - startX;
let height = endY - startY;
// Max NFT sizes
if (width > 64) {
width = 64;
if (width > 256) {
width = 256;
if (x < initX) {
startX = endX - width;
}
}
if (height > 64) {
height = 64;
if (height > 256) {
height = 256;
if (y < initY) {
startY = endY - height;
}
Expand Down
1 change: 1 addition & 0 deletions frontend/src/configs/backend.config.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"host": "api.art-peace.net",
"port": 8080,
"consumer_port": 8081,
"scripts": {
"place_pixel_devnet": "../tests/integration/local/place_pixel.sh",
"place_extra_pixels_devnet": "../tests/integration/local/place_extra_pixels.sh",
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/index.css
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
@font-face {
font-family: 'Public-Pixel';
src: local('Public-Pixel'),
src:
local('Public-Pixel'),
url('./fonts/PublicPixel-z84yD.ttf') format('truetype');
}

Expand Down
4 changes: 4 additions & 0 deletions frontend/src/tabs/TabPanel.js
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,8 @@ const TabPanel = (props) => {
setTemplateImage={props.setTemplateImage}
setTemplateColorIds={props.setTemplateColorIds}
setActiveTab={props.setActiveTab}
setTemplateOverlayMode={props.setTemplateOverlayMode}
setOverlayTemplate={props.setOverlayTemplate}
/>
</div>
)}
Expand All @@ -265,6 +267,8 @@ const TabPanel = (props) => {
queryAddress={props.queryAddress}
isMobile={props.isMobile}
gameEnded={props.gameEnded}
setTemplateOverlayMode={props.setTemplateOverlayMode}
setOverlayTemplate={props.setOverlayTemplate}
/>
</div>
)}
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/tabs/factions/FactionItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,9 @@ const FactionItem = (props) => {
);
return;
}
if (height > 64 || width > 64) {
if (height > 256 || width > 256) {
alert(
'Image is too large, maximum size is 64x64. Given size is ' +
'Image is too large, maximum size is 256x256. Given size is ' +
width +
'x' +
height
Expand Down
26 changes: 26 additions & 0 deletions frontend/src/tabs/nfts/NFTItem.css
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,32 @@
margin: 0;
padding: 0;
image-rendering: pixelated;
cursor: pointer;

transition: all 0.2s;
}

/* pulse animation */
@keyframes pulse {
0% {
transform: scale(1);
}
50% {
transform: scale(1.05);
}
100% {
transform: scale(1);
}
}

.NFTItem__image:hover {
animation: pulse 1s infinite;
transform: scale(1.03);
box-shadow: 0 0 10px rgba(0, 0, 0, 0.6);
}

.NFTItem__image:active {
transform: scale(1);
}

.NFTItem__buttons {
Expand Down
22 changes: 22 additions & 0 deletions frontend/src/tabs/nfts/NFTItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,27 @@ const NFTItem = (props) => {
}, [props.minter]);

const [showInfo, setShowInfo] = React.useState(false);
const handleNftClick = (e) => {
if (
e.target.classList.contains('NFTItem__button') ||
e.target.classList.contains('Like__icon') ||
e.target.classList.contains('Share__icon')
) {
return;
}
// Format NFT data to match template structure
const nftTemplate = {
position: props.position,
width: props.width,
height: props.height,
image: props.image,
isNft: true,
tokenId: props.tokenId
};
props.setTemplateOverlayMode(true);
props.setOverlayTemplate(nftTemplate);
props.setActiveTab('Canvas');
};
return (
<div className='NFTItem'>
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
Expand All @@ -153,6 +174,7 @@ const NFTItem = (props) => {
src={props.image}
alt={`nft-image-${props.tokenId}`}
className='NFTItem__image'
onClick={handleNftClick}
/>
<p className='Text__xsmall NFTItem__name'>{props.name}</p>
<div className='NFTItem__overlay'>
Expand Down
Loading