Skip to content

Commit

Permalink
Merge pull request #82 from BrainiacWizards/mmpotulo
Browse files Browse the repository at this point in the history
Update with Webpack bundling (not optimized)
  • Loading branch information
mmpotulo28 committed Jul 25, 2024
2 parents 72d05de + 2a2a733 commit f0c41f6
Show file tree
Hide file tree
Showing 63 changed files with 4,911 additions and 8,985 deletions.
20 changes: 19 additions & 1 deletion assets/img/site.webmanifest
Original file line number Diff line number Diff line change
@@ -1 +1,19 @@
{"name":"","short_name":"","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}
{
"name": "",
"short_name": "",
"icons": [
{
"src": "/assets/img/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/assets/img/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#1b1a55",
"background_color": "#1b1a55",
"display": "standalone"
}
4 changes: 2 additions & 2 deletions pages/auth/auth.js → assets/js/auth.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { navbar } from '../../assets/js/utils/setnavbar.js';
import { fbLogin, fbSignUp, githubLogin, googleLogin } from './fb.js';
import { navbar } from '/assets/js/utils/setnavbar.js';
import { fbLogin, fbSignUp, githubLogin, googleLogin } from '/assets/js/utils/fb.js';

const emailDOM = document.getElementById('email');
const userNameDOM = document.getElementById('username');
Expand Down
6 changes: 3 additions & 3 deletions pages/auth/gamepin/gamepin.js → assets/js/gamepin.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { checkLoginStatus } from '../../../assets/js/main.js';
import { navbar } from '../../../assets/js/utils/setnavbar.js';
import { createGamePinTable, queryGamePin } from '../fb.js';
import { checkLoginStatus } from '/assets/js/main.js';
import { navbar } from '/assets/js/utils/setnavbar.js';
import { createGamePinTable, queryGamePin } from './utils/fb.js';

const generateBtn = document.getElementById('generateBtn');
const topic = new URLSearchParams(window.location.search).get('topic');
Expand Down
2 changes: 1 addition & 1 deletion assets/js/host.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { endGame, fundGame, getPlayerNames, startGame } from '../../pages/auth/fb.js';
import { endGame, fundGame, getPlayerNames, startGame } from './utils/fb.js';
import { checkGameStatus } from './looby.js';
import { checkLoginStatus } from './main.js';
import { delay } from './utils/helpers.js';
Expand Down
2 changes: 1 addition & 1 deletion assets/js/looby.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createScoreBoard, getGameStatus } from '../../pages/auth/fb.js';
import { createScoreBoard, getGameStatus } from './utils/fb.js';
import { setPlayerNames } from './host.js';
import { delay } from './utils/helpers.js';
import { getState } from './utils/metamask.js';
Expand Down
70 changes: 51 additions & 19 deletions assets/js/postquiz.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { createScoreBoard, overallRanking } from '../../pages/auth/fb.js';
import { fundAccount } from './utils/metamask.js';
import {
checkRewardClaimed,
createScoreBoard,
overallRanking,
setRewardAsClaimed,
} from './utils/fb.js';
import { fundAccount, getState } from './utils/metamask.js';
import { topics } from './utils/questions.js';
import { checkLoginStatus } from './main.js';
import { navbar } from './utils/setnavbar.js';
import { delay } from './utils/helpers.js';
checkLoginStatus({ path: '../auth/' });

let login = null;
const searchParams = new URLSearchParams(window.location.search);
const topicID = searchParams.get('topic') || undefined;
const gamePin = searchParams.get('gamePin') || undefined;
Expand Down Expand Up @@ -51,7 +58,7 @@ let campaign = 'defaultCampaign';

async function setScoreBoard() {
// get username from login
const login = JSON.parse(sessionStorage.getItem('login'));
login = JSON.parse(sessionStorage.getItem('login'));
const username = login.username;
const myPin = gamePin;
campaign = login.campaign;
Expand Down Expand Up @@ -150,29 +157,54 @@ async function checkWin(scoreData, username, gamePin, score) {
navbar.errorDetection.consoleInfo(
'Congratulations! You are the winner! Token transfer in progress...',
);

try {
await fundAccount();
reload = false;
tokenTransferred = true;
navbar.errorDetection.consoleInfo('Token transfer successful');
return 'status: success';
} catch (error) {
reload = false;
if (error.code === 4001) {
error.reason = prompt('Please state the reason for cancelling the transaction?');
navbar.errorDetection.consoleWarn('Transaction cancelled', error.reason);
} else {
navbar.errorDetection.consoleError('Error funding account', error);
}
}
await checkState();
} else {
navbar.errorDetection.consoleInfo('You did not win, better luck next time!');
reload = false;
return;
}
}

async function checkState() {
let address = getState().account;
if (address) {
login.wallet = address;
navbar.errorDetection.consoleInfo('Account connected... minting');
const { gamePin, username, wallet } = login;
const response = await checkRewardClaimed({ gamePin, topicID });
if (!response.status) {
navbar.errorDetection.consoleError(response.message);
} else {
await transactNFT({ gamePin, topicID, username, wallet });
}

return;
}

window.requestAnimationFrame(checkState);
}

// transact
async function transactNFT({ gamePin, topicID, username, wallet }) {
try {
await fundAccount();
const response = await setRewardAsClaimed({ gamePin, topicID, username, wallet });
navbar.errorDetection.consoleInfo(response.message);
reload = false;
tokenTransferred = true;
navbar.errorDetection.consoleInfo('Token transfer successful');
return 'status: success';
} catch (error) {
reload = false;
if (error.code === 4001) {
error.reason = prompt('Please state the reason for cancelling the transaction?');
navbar.errorDetection.consoleWarn('Transaction cancelled', error.reason);
} else {
navbar.errorDetection.consoleError('Error funding account', error);
}
}
}

// set overall ranking
async function setOverallRanking({ username, score, retry, gamePin, campaign }) {
console.log('setting overall ranking for', username, score, retry, gamePin);
Expand Down
2 changes: 1 addition & 1 deletion assets/js/quiz.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createScoreBoard } from '../../pages/auth/fb.js';
import { createScoreBoard } from './utils/fb.js';
import { run } from './utils/openai.mjs';
import { topics } from './utils/questions.js';
import { checkLoginStatus } from './main.js';
Expand Down
2 changes: 1 addition & 1 deletion assets/js/ranking.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getOverallRanking } from '../../pages/auth/fb.js';
import { getOverallRanking } from './utils/fb.js';
const rankingTableBody = document.querySelector('#ranking-body');
import { checkLoginStatus } from './main.js';
checkLoginStatus();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ class ErrorDetection {
const timeDiff = currentDate - date;

const expirySpan = element.querySelector('.expiry-span');
let spanWidth = (timeDiff / 4000) * 100;
let spanWidth = (timeDiff / 6000) * 100;
expirySpan.style.width = `${100 - spanWidth}%`;

if (timeDiff > 4000) element.remove();
if (timeDiff > 6000) element.remove();
});

if (errorContainers.length === 0) this.errorBlock.style.display = 'none';
Expand Down
50 changes: 47 additions & 3 deletions pages/auth/fb.js → assets/js/utils/fb.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { delay } from '../../assets/js/utils/helpers.js';
import { navbar } from '../../assets/js/utils/setnavbar.js';
import * as fb from '../../fb_config.js';
import { delay } from '/assets/js/utils/helpers.js';
import { navbar } from '/assets/js/utils/setnavbar.js';
import * as fb from '/assets/js/utils/fb_config.js';

// Utility function to shorten usernames
function shortenUsername(username) {
Expand Down Expand Up @@ -663,6 +663,48 @@ function updateLogin(user) {
sessionStorage.setItem('login', JSON.stringify(login));
}

// set NFT-reward on game as claimed
async function setRewardAsClaimed({ gamePin, topicID, username, wallet }) {
let playerNames = await getPlayerNames({ gamePin, topicID });

try {
// change only dummy
if (playerNames) {
playerNames = playerNames.map((player) => {
if (player.username == 'dummy') {
player.nftClaim = true;
player.winner = { username, wallet };
}
return player;
});
}

await setPlayers({ gamePin, topicID, playerNames });
return { status: true, message: 'Reward Claimed!' };
} catch (error) {
throw new Error('Could not update game reward claim\\n', error);
}
}

// check if reward has been claimed
async function checkRewardClaimed({ gamePin, topicID }) {
let playerNames = await getPlayerNames({ gamePin, topicID });
let status = true,
message = `Reward hasn't been claimed`;

try {
// change only dummy
const dummy = playerNames.filter((player) => player.username == 'dummy');
if (dummy[0].nftClaim || dummy[0].winner) {
return { status: false, message: 'Reward Already Claimed!!' };
}

return { status: true, message: 'Not Claimed' };
} catch (error) {
throw new Error(`Could not check game reward claim\n${error}`);
}
}

export {
fbSignUp,
fbLogin,
Expand All @@ -680,4 +722,6 @@ export {
uploadImage,
fundGame,
getUsers,
setRewardAsClaimed,
checkRewardClaimed,
};
19 changes: 7 additions & 12 deletions fb_config.js → assets/js/utils/fb_config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js';
import { getStorage } from 'https://www.gstatic.com/firebasejs/9.6.1/firebase-storage.js';
import { initializeApp } from 'firebase/app';
import { getStorage, uploadBytes } from 'firebase/storage';
import { getDatabase, ref, set, update, get } from 'firebase/database';
import { getPerformance } from 'firebase/performance';
import { getAnalytics } from 'firebase/analytics';
import {
getAuth,
createUserWithEmailAndPassword,
Expand All @@ -9,16 +12,7 @@ import {
signInWithRedirect,
getRedirectResult,
GithubAuthProvider,
} from 'https://www.gstatic.com/firebasejs/9.6.1/firebase-auth.js';
import { getDatabase } from 'https://www.gstatic.com/firebasejs/9.6.1/firebase-database.js';
import {
ref,
set,
update,
get,
} from 'https://www.gstatic.com/firebasejs/9.6.1/firebase-database.js';
import { getPerformance } from 'https://www.gstatic.com/firebasejs/9.6.1/firebase-performance.js';
import { getAnalytics } from 'https://www.gstatic.com/firebasejs/9.6.1/firebase-analytics.js';
} from 'firebase/auth';

const firebaseConfig = {
apiKey: 'AIzaSyCeL875YW20dLfoeNxfR-EU4TeIPqkWc1Q',
Expand Down Expand Up @@ -62,4 +56,5 @@ export {
perf,
analytics,
storage,
uploadBytes,
};
9 changes: 8 additions & 1 deletion assets/js/utils/metamask.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,14 @@ async function loadContract(web3) {
return token;
}

async function metaConnection(walletAddress) {
async function metaConnection(walletAddress, n, caller) {
// const callerPath = new Error().stack.match(/(file:\/\/\/.*:\d+:\d+)/)[1];
// const callerFileName = callerPath.substring(callerPath.lastIndexOf('/') + 1);
// console.log('Caller Path:', callerPath);
// console.log('Caller File Name:', callerFileName);

console.log('testing', caller);

let web3;

if (window.ethereum) {
Expand Down
9 changes: 7 additions & 2 deletions assets/js/utils/openai.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { GoogleGenerativeAI } from 'https://cdn.skypack.dev/@google/generative-ai';
import { questions } from './questions.js';
// import { GoogleGenerativeAI } from 'https://cdn.skypack.dev/@google/generative-ai';
import { GoogleGenerativeAI } from '@google/generative-ai';

// Access your API key as an environment variable (see "Set up your API key" above)
const api_key = 'AIzaSyDgx9kucPZV4kAab55IzII0qFnxt2n26eY';
Expand Down Expand Up @@ -79,7 +80,11 @@ function validateResponse({ questionsAI, topicID }) {
errors.push('There should be 4 answers per question');
}

if (question.answers.includes('') || question.answers.includes(undefined) || !question.answers) {
if (
question.answers.includes('') ||
question.answers.includes(undefined) ||
!question.answers
) {
errors.push('Answers should not be empty');
}

Expand Down
8 changes: 4 additions & 4 deletions assets/js/utils/setnavbar.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import ErrorDetection from './error-detection.js';
import ErrorDetection from './error.js';
import { getTransfers } from './graph_query.js';
import { getState, metaConnection } from './metamask.js';

class Navbar {
constructor() {
const { origin } = window.location;
this.origin = origin;
this.origin = window.location.origin;
this.checkInternetConnection();
this.injectWalletContainer();
this.injectTrackingData();
Expand Down Expand Up @@ -117,7 +116,8 @@ class Navbar {
}

async setNavbar() {
await metaConnection(this.walletAddress, 1);
const caller = import.meta.url;
await metaConnection(this.walletAddress, 1, caller);
this.addEventListeners();
}

Expand Down
2 changes: 2 additions & 0 deletions dist/auth.bundle.js

Large diffs are not rendered by default.

Loading

0 comments on commit f0c41f6

Please sign in to comment.