Skip to content

Commit

Permalink
Merge branch 'develop' into 523-implement-tanstack-to-prevent-reloads…
Browse files Browse the repository at this point in the history
…-between-search-page-and-prompt-of-the-month
  • Loading branch information
marclupanc committed Dec 5, 2024
2 parents 41c5ce4 + 91582a5 commit 76c9266
Show file tree
Hide file tree
Showing 9 changed files with 135 additions and 76 deletions.
6 changes: 4 additions & 2 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ VITE_TEST_PASSWORD=12345678

#BLOCKCHAIN
VITE_WALLET_CONNECT_PROJECT_ID='9dcf39cb8034882a971d5086066c7f17'
VITE_CURRENT_NETWORK_NAME="matic"

VITE_CURRENT_NETWORK_NAME="MATIC"

#sepolia
VITE_ALCHEMY_SEPOLIA_PROVIDER_URL="https://eth-sepolia.g.alchemy.com/v2/F_3kP4qK3m83Mzp0ZsxoBSNwXn9AWZfy"
Expand All @@ -41,12 +42,13 @@ VITE_INFURA_POLYGON_MAINET_NETWORK_NAME="Polygon Matic"
VITE_POLYGON_MAINET_CHAIN_ID=137
VITE_POLYGON_MAINET_CURRENCY="MATIC"

VITE_ADVERTISEMENT_CAMPAIGN_CONTRACT_ADDRESS="0x0d273b72B189745a2aF49706d62dAaD5f00f0aE4"
VITE_ADVERTISEMENT_CAMPAIGN_CONTRACT_ADDRESS="0x96354a0D4746E4B87d7640B2891bdb313Ad6Ac66"
VITE_ADVERTISEMENT_COMPAIGN_CONTRACT_OWNER= "0xdb0f8aACC19a779b9020a693c35014DaF9cF3796"

VITE_ADVERTISE_CLICK_RATE='0.001'
VITE_ADVERTISE_IMPRESSION_RATE='0.001'
VITE_ADVERTISE_VIEWS_RATE='0.001'

VITE_LAYER8_PROXY=https://layer8proxy.net
#DEV ENV FOR STATS API
VITE_STATS_API_URL=https://stats-api-dev.up.railway.app/v1
Expand Down
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,7 @@ package-lock.json

.lighthousec/

src/web3/alternatives
src/components/Admin/updatedTableEntry.vue

src/web3/#walletConnect.js#
13 changes: 9 additions & 4 deletions functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ async function calculateTotalVisits(advertiseDocRef) {
return totalVisits
}

async function calculateAmountSpent(totalClicks, totalImpressions, totalVisits) {
return (
import.meta.env.VITE_ADVERTISE_CLICK_RATE * totalClicks +
import.meta.env.VITE_ADVERTISE_IMPRESSION_RATE * totalImpressions +
import.meta.env.VITE_ADVERTISE_VIEWS_RATE * totalVisits
)
}

async function updateAdvertiseStatus(docId) {
const advertiseDocRef = db.collection('advertises').doc(docId)

Expand All @@ -55,11 +63,8 @@ async function updateAdvertiseStatus(docId) {
const totalImpressions = await calculateTotalImpressions(advertiseDocRef)
const totalClicks = await calculateTotalClicks(advertiseDocRef)
const totalVisits = await calculateTotalVisits(advertiseDocRef)
const impressionsMatic = totalImpressions * 0.001
const clicksMatic = totalClicks * 0.001
const viewsMatic = totalVisits * 0.001
const totalCost = viewsMatic + clicksMatic + impressionsMatic

const totalCost = calculateAmountSpent(totalClicks, totalImpressions, totalVisits)
const date1 = new Date()
const date2 = new Date(docData.endDate)
date1.setHours(0, 0, 0, 0)
Expand Down
3 changes: 2 additions & 1 deletion src/components/Admin/TableEntry.vue
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@
v-if="
_currentPrompt?.isTreated ? props.row.isWinner && !_currentPrompt?.isTreated : props.row.isWinner && !props.row.isTreated
"
color="green"
:disable="props.row.author.uid !== userStore.getUserId"
color="green"
icon="payment"
unelevated
size="sm"
Expand Down Expand Up @@ -308,6 +308,7 @@ async function onProceedPaymentDialog(props) {
} else {
//let's check if the entry already have valid payment..
const cryptoTransactionExist = await cryptoTransactions.getCryptoTransactionsByEntry(props.id)
if (cryptoTransactionExist.length > 0) {
const escrowEvents = await getEventsForEscrow({ escrowId: _currentPrompt.value.escrowId })
if (escrowEvents?.status?.includes('success')) {
Expand Down
4 changes: 2 additions & 2 deletions src/components/Advertiser/AdvertiseCard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ function isUrlValid(userInput = '') {
return res !== null
}
async function createAdCampain(payload) {
async function createAdCampaign(payload) {
return await contractCreateAdCampaign(payload)
}
function convertToMatic() {
Expand Down Expand Up @@ -359,7 +359,7 @@ async function onSubmit() {
.finally(() => $q.loading.hide())
} else {
//call contract create function
const result = await createAdCampain({ budgetInMatic: advertise.budget })
const result = await createAdCampaign({ budgetInMatic: advertise.budget })
if (result.status.includes('success')) {
advertise.campaignCode = result.events[0].args.campaignCode
//save advertisement to database
Expand Down
155 changes: 97 additions & 58 deletions src/components/Advertiser/AdvertiserTable.vue
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@
<template #body-cell-action="props">
<q-td :props="props">
<q-icon
v-if="userStore.getUser.role === 'Admin' && props.row.campaignCode?.length > 5 && props.row.status === 'Active'"
v-if="
userStore.getUser.role === 'Admin' &&
props.row.campaignCode?.length > 5 &&
props.row.status !== 'Inactive' &&
props.row.status !== 'Complete'
"
flat
color="green"
name="payment"
Expand All @@ -52,7 +57,10 @@
</q-icon>
<q-icon
v-if="
userStore.getUser.email === props.row.author.email && props.row.campaignCode?.length > 5 && props.row.status === 'Active'
userStore.getUser.uid === props.row.author.id &&
props.row.campaignCode?.length > 5 &&
props.row.status !== 'Inactive' &&
props.row.status !== 'Complete'
"
flat
color="primary"
Expand Down Expand Up @@ -187,7 +195,7 @@
<q-dialog v-model="withdrawAmountSpentDialog.show">
<q-card>
<q-card-section class="q-pb-none">
<h6 class="q-my-sm">Withdraw Amount Spent : {{ withdrawAmountSpentDialog.currentAmountSpent }}</h6>
<h6 class="q-my-sm">Available Amount to withdraw : {{ withdrawAmountSpentDialog.unclaimedAmount }}</h6>
</q-card-section>
<q-card-section>Are you sure you want to withdraw it ?</q-card-section>
<q-card-actions align="right">
Expand Down Expand Up @@ -243,6 +251,7 @@ import { useAdvertiseStore, useErrorStore, useUserStore } from 'src/stores'
import { useRouter } from 'vue-router'
import { getCurrentDate, calculateEndDate, computedDuration } from 'src/utils/date'
import { claimPayment, requestAndApproveWithdrawal, getEventsForCampaign } from 'app/src/web3/adCampaignManager'
import { customWeb3modal } from 'app/src/web3/walletConnect'
const props = defineProps({
advertises: {
Expand Down Expand Up @@ -301,41 +310,48 @@ async function calculateAmountSpent(advertise) {
async function _getEventsForCampaign(advertise) {
if (advertise?.campaignCode) {
$q.loading.show()
const result = await getEventsForCampaign(advertise.campaignCode)
if (result.status.includes('success')) {
// Combine events into a single array with eventType field
const adCampaignCreatedEvents = result.events.adCampaignCreatedEvents.map((event) => ({
...event,
eventType: 'Campaign Created'
}))
const paymentReleasedEvents = result.events.paymentReleasedEvents.map((event) => ({
...event,
eventType: 'Payment Released'
}))
const budgetWithdrawnEvents = result.events.budgetWithdrawnEvents.map((event) => ({
...event,
eventType: 'Remaining Budget Withdrawn'
}))
const paymentReleasedOnWithdrawApprovalEvents = result.events.paymentReleasedOnWithdrawApprovalEvents.map((event) => ({
...event,
eventType: 'Payment Released on Withdraw Approval'
}))
eventRows.value = [
...adCampaignCreatedEvents,
...paymentReleasedEvents,
...budgetWithdrawnEvents,
...paymentReleasedOnWithdrawApprovalEvents
]
//let's change the advertise status.
advertismentPaymentEventsDialog.value.show = true
if (!customWeb3modal.getAddress()) {
$q.notify({ type: 'negative', message: 'Please connect your wallet and try again' })
customWeb3modal.open()
$q.loading.hide()
} else {
$q.notify({ message: result?.error?.message, type: 'negative' })
const result = await getEventsForCampaign(advertise.campaignCode)
if (result.status.includes('success')) {
$q.notify({ message: 'Events retreived successfully ', type: 'positive' })
// Combine events into a single array with eventType field
const adCampaignCreatedEvents = result.events.adCampaignCreatedEvents.map((event) => ({
...event,
eventType: 'Campaign Created'
}))
const paymentReleasedEvents = result.events.paymentReleasedEvents.map((event) => ({
...event,
eventType: 'Payment Released'
}))
const budgetWithdrawnEvents = result.events.budgetWithdrawnEvents.map((event) => ({
...event,
eventType: 'Remaining Budget Withdrawn'
}))
const paymentReleasedOnWithdrawApprovalEvents = result.events.paymentReleasedOnWithdrawApprovalEvents.map((event) => ({
...event,
eventType: 'Payment Released on Withdraw Approval'
}))
eventRows.value = [
...adCampaignCreatedEvents,
...paymentReleasedEvents,
...budgetWithdrawnEvents,
...paymentReleasedOnWithdrawApprovalEvents
]
//let's change the advertise status.
advertismentPaymentEventsDialog.value.show = true
} else {
$q.notify({ message: result?.error?.message, type: 'negative' })
}
}
} else {
$q.notify({ message: 'No campaign code associated', type: 'negative' })
Expand All @@ -362,8 +378,21 @@ async function onwithdrawAmountSpentDialog(advertise) {
if (advertise?.campaignCode) {
$q.loading.show()
const currentAmountSpent = await calculateAmountSpent(advertise)
if (currentAmountSpent > 0) {
const adEvents = await getEventsForCampaign(advertise.campaignCode)
let releasedAmount = 0
let unclaimedAmount = 0
if (adEvents.status.includes('success')) {
if (adEvents.events.paymentReleasedEvents) {
adEvents.events.paymentReleasedEvents.forEach((paymentReleasedEvent) => {
releasedAmount += parseFloat(paymentReleasedEvent.amount)
})
}
}
unclaimedAmount = parseFloat(currentAmountSpent - releasedAmount).toFixed(3)
if (unclaimedAmount > 0) {
withdrawAmountSpentDialog.value.advertise = advertise
withdrawAmountSpentDialog.value.unclaimedAmount = unclaimedAmount
withdrawAmountSpentDialog.value.currentAmountSpent = currentAmountSpent
withdrawAmountSpentDialog.value.show = true
} else {
Expand All @@ -377,16 +406,23 @@ async function onwithdrawAmountSpentDialog(advertise) {
async function _claimPayment(advertise, currentAmountSpent) {
$q.loading.show()
const result = await claimPayment({ campaignCode: advertise.campaignCode, currentAmounSpentInMatic: currentAmountSpent })
if (result.status.includes('success')) {
$q.notify({ message: 'Campaign payment claimed successfully', type: 'positive' })
//let's change the advertise status.
if (currentAmountSpent >= advertise.budget) {
await _completeAdvertise(advertise)
}
if (!customWeb3modal.getAddress()) {
$q.notify({ type: 'negative', message: 'Please connect your wallet and try again' })
customWeb3modal.open()
$q.loading.hide()
} else {
$q.notify({ message: result?.error?.message, type: 'negative' })
const result = await claimPayment({ campaignCode: advertise.campaignCode, currentAmounSpentInMatic: currentAmountSpent.toString() })
if (result.status.includes('success')) {
$q.notify({ message: 'Campaign payment claimed successfully ', type: 'positive' })
//let's change the advertise status.
if (currentAmountSpent >= advertise.budget) {
await _completeAdvertise(advertise)
}
} else {
$q.notify({ message: result?.error?.message, type: 'negative' })
}
}
$q.loading.hide()
}
Expand All @@ -401,16 +437,19 @@ async function _completeAdvertise(advertise) {
}
async function _withdrawRemainingBudget(advertise, currentAmounSpent) {
$q.loading.show()
const result = await requestAndApproveWithdrawal({
campaignCode: advertise.campaignCode,
currentAmounSpentInMatic: currentAmounSpent
})
if (result.status.includes('success')) {
$q.notify({ message: 'Remaining budget withdrawn successfully ', type: 'positive' })
//let's change the advertise status
await _completeAdvertise(advertise)
if (!customWeb3modal.getAddress()) {
$q.notify({ type: 'negative', message: 'Please connect your wallet and try again' })
customWeb3modal.open()
$q.loading.hide()
} else {
$q.notify({ message: result?.error?.message, type: 'negative' })
const result = await requestAndApproveWithdrawal({ campaignCode: advertise.campaignCode, currentAmounSpentInMatic: currentAmounSpent })
if (result.status.includes('success')) {
$q.notify({ message: 'Remaing budget withdrawn successfully ', type: 'positive' })
//let's change the advertise status
await _completeAdvertise(advertise)
} else {
$q.notify({ message: result?.error?.message, type: 'negative' })
}
}
$q.loading.hide()
}
Expand Down Expand Up @@ -485,10 +524,10 @@ function onDeselect() {
function onApproveAdvertise() {
advertiseStore
.editAdvertise(selectedAdvertise.value)
.then(() => $q.notify({ type: 'info', message: 'Advertise approved successfully' }))
.then(() => $q.notify({ type: 'info', message: 'Advertise Approved successfully' }))
.catch((error) => {
console.log(error)
errorStore.throwError(error, 'Advertise approval failed')
errorStore.throwError(error, 'Advertise Approval failed')
})
.finally(() => {
selectedAdvertise.value = {}
Expand Down Expand Up @@ -637,7 +676,7 @@ function viewMatic(matic) {
function showStatus(data) {
const create = calculateStatus(data.publishDate)
const ended = calculateStatus(data.endDate)
const budgetCrossed = computeAdvertisementMatic(data.impressions, data.clicks, data.visits) > Number(data.budget)
const budgetCrossed = computeAdvertisementMatic(data.totalImpressions, data.totalClicks, data.totalVisits) > Number(data.budget)
if (!create) {
return 'Publish date pending'
} else if (budgetCrossed || data.status === 'Budget Crossed') {
Expand Down
7 changes: 6 additions & 1 deletion src/components/Advertiser/CampaignCard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,12 @@ function goToUrl() {
const loadStoredImpressions = () => {
const storedImpressions = localStorage.getItem('impressions')
return storedImpressions ? JSON.parse(storedImpressions) : {}
try {
return storedImpressions ? JSON.parse(storedImpressions) : {}
} catch (error) {
console.error('Failed to parse stored impressions:', error)
return {}
}
}
const saveImpressionsToStorage = () => {
Expand Down
11 changes: 9 additions & 2 deletions src/stores/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,18 @@ export const useWalletStore = defineStore('wallet', {
rpcUrl: import.meta.env.VITE_ALCHEMY_SEPOLIA_PROVIDER_URL
},
matic: {
chainId: import.meta.env.VITE_POLYGON_MAINET_CHAIN_ID,
chainId: 137,
name: import.meta.env.VITE_INFURA_POLYGON_MAINET_NETWORK_NAME,
currency: import.meta.env.VITE_POLYGON_MAINET_CURRENCY,
explorerUrl: import.meta.env.VITE_INFURA_POLYGON_MAINET_SCAN_URL,
rpcUrl: import.meta.env.VITE_INFURA_POLYGON_MAINET_PROVIDER_URL
rpcUrl: 'https://polygon-rpc.com',
blockExplorerUrls: ['https://polygonscan.com/'],

nativeCurrency: {
name: 'Polygon',
symbol: 'MATIC',
decimals: 18
}
}
}
}),
Expand Down
8 changes: 2 additions & 6 deletions src/web3/adCampaignManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const getProvider = async () => {
}
} catch (error) {
console.error('Error getting provider:', error)
error = 'please connect your wallet'
error = 'Please connect your wallet and try again'
// Rethrow the error to handle it where getProvider is called
throw error
}
Expand Down Expand Up @@ -73,10 +73,7 @@ export const claimPayment = async (payload = { campaignCode: '', currentAmounSpe
if (payload.campaignCode.length > 1 && payload.currentAmounSpentInMatic > 0) {
try {
const adCampaignManager = await getContractInstance()
if (
customWeb3modal.getAddress() &&
customWeb3modal.getAddress().toLowerCase() === import.meta.env.VITE_ADVERTISEMENT_COMPAIGN_CONTRACT_OWNER.toLowerCase()
) {
if (customWeb3modal.getAddress()) {
const tx = await adCampaignManager.claimPayment(
payload.campaignCode,
ethers.utils.parseEther(payload.currentAmounSpentInMatic.toString())
Expand Down Expand Up @@ -225,7 +222,6 @@ export const getEventsForCampaign = async (campaignCode) => {
adCampaignCreatedEvents: adCampaignCreatedData
}

//console.log('Events retrieved successfully')
return { status: 'success', events: result }
} catch (error) {
const errorMessage = error.error ? error.error.data : error
Expand Down

0 comments on commit 76c9266

Please sign in to comment.