-
-
Save Daltonic/a083fa992dde823f712d10b343a790d1 to your computer and use it in GitHub Desktop.
Dapp Lottery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import abi from '@/artifacts/contracts/DappLottery.sol/DappLottery.json' | |
import address from '@/artifacts/contractAddress.json' | |
import { globalActions } from '@/store/global_reducer' | |
import { store } from '@/store' | |
import { | |
getLottery, | |
getLotteryResult, | |
getLuckyNumbers, | |
getParticipants, | |
getPurchasedNumbers, | |
} from '@/services/blockchain.srr' | |
import { ethers } from 'ethers' | |
import { logOutWithCometChat } from './chat' | |
const { | |
updateWallet, | |
setLuckyNumbers, | |
setParticipants, | |
setPurchasedNumbers, | |
setJackpot, | |
setResult, | |
setCurrentUser, | |
} = globalActions | |
const contractAddress = address.address | |
const contractAbi = abi.abi | |
let tx, ethereum | |
if (typeof window !== 'undefined') { | |
ethereum = window.ethereum | |
} | |
const toWei = (num) => ethers.utils.parseEther(num.toString()) | |
const getEthereumContract = async () => { | |
const provider = new ethers.providers.Web3Provider(ethereum) | |
const signer = provider.getSigner() | |
const contract = new ethers.Contract(contractAddress, contractAbi, signer) | |
return contract | |
} | |
const isWallectConnected = async (CometChat) => { | |
try { | |
if (!ethereum) return notifyUser('Please install Metamask') | |
const accounts = await ethereum.request({ method: 'eth_accounts' }) | |
window.ethereum.on('chainChanged', (chainId) => { | |
window.location.reload() | |
}) | |
window.ethereum.on('accountsChanged', async () => { | |
store.dispatch(updateWallet(accounts[0])) | |
store.dispatch(setCurrentUser(null)) | |
logOutWithCometChat(CometChat).then(() => console.log('Logged out')) | |
await isWallectConnected(CometChat) | |
}) | |
if (accounts.length) { | |
store.dispatch(updateWallet(accounts[0])) | |
} else { | |
store.dispatch(updateWallet('')) | |
notifyUser('Please connect wallet.') | |
console.log('No accounts found.') | |
} | |
} catch (error) { | |
reportError(error) | |
} | |
} | |
const connectWallet = async () => { | |
try { | |
if (!ethereum) return notifyUser('Please install Metamask') | |
const accounts = await ethereum.request({ method: 'eth_requestAccounts' }) | |
store.dispatch(updateWallet(accounts[0])) | |
} catch (error) { | |
reportError(error) | |
} | |
} | |
const createJackpot = async ({ title, description, imageUrl, prize, ticketPrice, expiresAt }) => { | |
try { | |
if (!ethereum) return notifyUser('Please install Metamask') | |
const connectedAccount = store.getState().globalState.wallet | |
const contract = await getEthereumContract() | |
tx = await contract.createLottery( | |
title, | |
description, | |
imageUrl, | |
toWei(prize), | |
toWei(ticketPrice), | |
expiresAt, | |
{ | |
from: connectedAccount, | |
} | |
) | |
await tx.wait() | |
} catch (error) { | |
reportError(error) | |
} | |
} | |
const buyTicket = async (id, luckyNumberId, ticketPrice) => { | |
try { | |
if (!ethereum) return notifyUser('Please install Metamask') | |
const connectedAccount = store.getState().globalState.wallet | |
const contract = await getEthereumContract() | |
tx = await contract.buyTicket(id, luckyNumberId, { | |
from: connectedAccount, | |
value: toWei(ticketPrice), | |
}) | |
await tx.wait() | |
const purchasedNumbers = await getPurchasedNumbers(id) | |
const lotteryParticipants = await getParticipants(id) | |
const lottery = await getLottery(id) | |
store.dispatch(setPurchasedNumbers(purchasedNumbers)) | |
store.dispatch(setParticipants(lotteryParticipants)) | |
store.dispatch(setJackpot(lottery)) | |
} catch (error) { | |
reportError(error) | |
} | |
} | |
const performDraw = async (id, numOfWinners) => { | |
try { | |
if (!ethereum) return notifyUser('Please install Metamask') | |
const connectedAccount = store.getState().globalState.wallet | |
const contract = await getEthereumContract() | |
tx = await contract.randomlySelectWinners(id, numOfWinners, { | |
from: connectedAccount, | |
}) | |
await tx.wait() | |
const lotteryParticipants = await getParticipants(id) | |
const lottery = await getLottery(id) | |
const result = await getLotteryResult(id) | |
store.dispatch(setParticipants(lotteryParticipants)) | |
store.dispatch(setJackpot(lottery)) | |
store.dispatch(setResult(result)) | |
} catch (error) { | |
reportError(error) | |
} | |
} | |
const exportLuckyNumbers = async (id, luckyNumbers) => { | |
try { | |
if (!ethereum) return notifyUser('Please install Metamask') | |
const connectedAccount = store.getState().globalState.wallet | |
const contract = await getEthereumContract() | |
tx = await contract.importLuckyNumbers(id, luckyNumbers, { | |
from: connectedAccount, | |
}) | |
await tx.wait() | |
const lotteryNumbers = await getLuckyNumbers(id) | |
store.dispatch(setLuckyNumbers(lotteryNumbers)) | |
} catch (error) { | |
reportError(error) | |
} | |
} | |
const reportError = (error) => { | |
console.log(error.message) | |
} | |
const notifyUser = (msg) => { | |
console.log(msg) | |
} | |
const truncate = (text, startChars, endChars, maxLength) => { | |
if (text.length > maxLength) { | |
let start = text.substring(0, startChars) | |
let end = text.substring(text.length - endChars, text.length) | |
while (start.length + end.length < maxLength) { | |
start = start + '.' | |
} | |
return start + end | |
} | |
return text | |
} | |
export { | |
isWallectConnected, | |
connectWallet, | |
createJackpot, | |
exportLuckyNumbers, | |
buyTicket, | |
performDraw, | |
truncate, | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const abi = require('../artifacts/contracts/DappLottery.sol/DappLottery.json') | |
const address = require('../artifacts/contractAddress.json') | |
const { ethers } = require('ethers') | |
const contractAddress = address.address | |
const contractAbi = abi.abi | |
const fromWei = (num) => ethers.utils.formatEther(num) | |
const getEtheriumContract = async () => { | |
const provider = new ethers.providers.JsonRpcProvider('http://localhost:8545') | |
const wallet = ethers.Wallet.createRandom() | |
// Set the new account as the signer for the provider | |
const signer = provider.getSigner(wallet.address) | |
const contract = new ethers.Contract(contractAddress, contractAbi, signer) | |
return contract | |
} | |
const getLotteries = async () => { | |
const lotteries = await (await getEtheriumContract()).functions.getLotteries() | |
return structureLotteries(lotteries[0]) | |
} | |
const getLottery = async (id) => { | |
const lottery = await (await getEtheriumContract()).functions.getLottery(id) | |
return structureLotteries([lottery[0]])[0] | |
} | |
const getLuckyNumbers = async (id) => { | |
const luckyNumbers = await (await getEtheriumContract()).functions.getLotteryLuckyNumbers(id) | |
return luckyNumbers[0] | |
} | |
const getLotteryResult = async (id) => { | |
const lotterResult = await (await getEtheriumContract()).functions.getLotteryResult(id) | |
return structuredResult(lotterResult[0]) | |
} | |
const getParticipants = async (id) => { | |
const participants = await (await getEtheriumContract()).functions.getLotteryParticipants(id) | |
return structuredParticipants(participants[0]) | |
} | |
const getPurchasedNumbers = async (id) => { | |
const participants = await (await getEtheriumContract()).functions.getLotteryParticipants(id) | |
return structuredNumbers(participants[0]) | |
} | |
function formatDate(timestamp) { | |
const date = new Date(timestamp) | |
const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] | |
const monthsOfYear = [ | |
'Jan', | |
'Feb', | |
'Mar', | |
'Apr', | |
'May', | |
'Jun', | |
'Jul', | |
'Aug', | |
'Sep', | |
'Oct', | |
'Nov', | |
'Dec', | |
] | |
const dayOfWeek = daysOfWeek[date.getDay()] | |
const monthOfYear = monthsOfYear[date.getMonth()] | |
const dayOfMonth = date.getDate() | |
const year = date.getFullYear() | |
return `${dayOfWeek} ${monthOfYear} ${dayOfMonth}, ${year}` | |
} | |
const structureLotteries = (lotteries) => | |
lotteries.map((lottery) => ({ | |
id: Number(lottery.id), | |
title: lottery.title, | |
description: lottery.description, | |
owner: lottery.owner.toLowerCase(), | |
prize: fromWei(lottery.prize), | |
ticketPrice: fromWei(lottery.ticketPrice), | |
image: lottery.image, | |
createdAt: formatDate(Number(lottery.createdAt + '000')), | |
drawsAt: formatDate(Number(lottery.expiresAt)), | |
expiresAt: Number(lottery.expiresAt), | |
participants: Number(lottery.participants), | |
drawn: lottery.drawn, | |
})) | |
const structuredParticipants = (participants) => | |
participants.map((participant) => ({ | |
account: participant[0].toLowerCase(), | |
lotteryNumber: participant[1], | |
paid: participant[2], | |
})) | |
const structuredNumbers = (participants) => { | |
const purchasedNumbers = [] | |
for (let i = 0; i < participants.length; i++) { | |
const purchasedNumber = participants[i][1] | |
purchasedNumbers.push(purchasedNumber) | |
} | |
return purchasedNumbers | |
} | |
const structuredResult = (result) => { | |
const LotteryResult = { | |
id: Number(result[0]), | |
completed: result[1], | |
paidout: result[2], | |
timestamp: Number(result[3] + '000'), | |
sharePerWinner: fromWei(result[4]), | |
winners: [], | |
} | |
for (let i = 0; i < result[5].length; i++) { | |
const winner = result[5][i][1] | |
LotteryResult.winners.push(winner) | |
} | |
return LotteryResult | |
} | |
module.exports = { | |
getLotteries, | |
getLottery, | |
structureLotteries, | |
getLuckyNumbers, | |
getParticipants, | |
getPurchasedNumbers, | |
getLotteryResult, | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const CONSTANTS = { | |
APP_ID: process.env.NEXT_PUBLIC_APP_ID, | |
REGION: process.env.NEXT_PUBLIC_REGION, | |
Auth_Key: process.env.NEXT_PUBLIC_AUTH_KEY, | |
} | |
const initCometChat = async (CometChat) => { | |
const appID = CONSTANTS.APP_ID | |
const region = CONSTANTS.REGION | |
const appSetting = new CometChat.AppSettingsBuilder() | |
.subscribePresenceForAllUsers() | |
.setRegion(region) | |
.build() | |
await CometChat.init(appID, appSetting) | |
.then(() => console.log('Initialization completed successfully')) | |
.catch((error) => console.log(error)) | |
} | |
const loginWithCometChat = async (CometChat, UID) => { | |
const authKey = CONSTANTS.Auth_Key | |
return new Promise(async (resolve, reject) => { | |
await CometChat.login(UID, authKey) | |
.then((user) => resolve(user)) | |
.catch((error) => reject(error)) | |
}) | |
} | |
const signUpWithCometChat = async (CometChat, UID) => { | |
const authKey = CONSTANTS.Auth_Key | |
const user = new CometChat.User(UID) | |
user.setName(UID) | |
return new Promise(async (resolve, reject) => { | |
await CometChat.createUser(user, authKey) | |
.then((user) => resolve(user)) | |
.catch((error) => reject(error)) | |
}) | |
} | |
const logOutWithCometChat = async (CometChat) => { | |
return new Promise(async (resolve, reject) => { | |
await CometChat.logout() | |
.then(() => resolve()) | |
.catch(() => reject()) | |
}) | |
} | |
const checkAuthState = async (CometChat) => { | |
return new Promise(async (resolve, reject) => { | |
await CometChat.getLoggedinUser() | |
.then((user) => resolve(user)) | |
.catch((error) => reject(error)) | |
}) | |
} | |
const createNewGroup = async (CometChat, GUID, groupName) => { | |
const groupType = CometChat.GROUP_TYPE.PUBLIC | |
const password = '' | |
const group = new CometChat.Group(GUID, groupName, groupType, password) | |
return new Promise(async (resolve, reject) => { | |
await CometChat.createGroup(group) | |
.then((group) => resolve(group)) | |
.catch((error) => reject(error)) | |
}) | |
} | |
const getGroup = async (CometChat, GUID) => { | |
return new Promise(async (resolve, reject) => { | |
await CometChat.getGroup(GUID) | |
.then((group) => resolve(group)) | |
.catch((error) => reject(error)) | |
}) | |
} | |
const joinGroup = async (CometChat, GUID) => { | |
const groupType = CometChat.GROUP_TYPE.PUBLIC | |
const password = '' | |
return new Promise(async (resolve, reject) => { | |
await CometChat.joinGroup(GUID, groupType, password) | |
.then((group) => resolve(group)) | |
.catch((error) => reject(error)) | |
}) | |
} | |
const getMessages = async (CometChat, GUID) => { | |
const limit = 30 | |
const messagesRequest = new CometChat.MessagesRequestBuilder() | |
.setGUID(GUID) | |
.setLimit(limit) | |
.build() | |
return new Promise(async (resolve, reject) => { | |
await messagesRequest | |
.fetchPrevious() | |
.then((messages) => resolve(messages.filter((msg) => msg.type == 'text'))) | |
.catch((error) => reject(error)) | |
}) | |
} | |
const sendMessage = async (CometChat, receiverID, messageText) => { | |
const receiverType = CometChat.RECEIVER_TYPE.GROUP | |
const textMessage = new CometChat.TextMessage(receiverID, messageText, receiverType) | |
return new Promise(async (resolve, reject) => { | |
await CometChat.sendMessage(textMessage) | |
.then((message) => resolve(message)) | |
.catch((error) => reject(error)) | |
}) | |
} | |
const listenForMessage = async (CometChat, listenerID) => { | |
return new Promise(async (resolve, reject) => { | |
CometChat.addMessageListener( | |
listenerID, | |
new CometChat.MessageListener({ | |
onTextMessageReceived: (message) => resolve(message), | |
}) | |
) | |
}) | |
} | |
export { | |
initCometChat, | |
loginWithCometChat, | |
signUpWithCometChat, | |
logOutWithCometChat, | |
checkAuthState, | |
createNewGroup, | |
getGroup, | |
getMessages, | |
joinGroup, | |
sendMessage, | |
listenForMessage, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment