Skip to content

Commit

Permalink
do not query subgraph if running as static app
Browse files Browse the repository at this point in the history
  • Loading branch information
yuetloo committed Apr 22, 2024
1 parent ae7a8e5 commit 179e0da
Show file tree
Hide file tree
Showing 15 changed files with 182 additions and 78 deletions.
34 changes: 22 additions & 12 deletions vue-app/src/api/clrFund.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { clrfundContractAddress, clrFundContract } from './core'
import { clrfundContractAddress, clrFundContract, isActiveApp, provider } from './core'
import sdk from '@/graphql/sdk'
import { ERC20 } from './abi'
import { Contract } from 'ethers'

export interface ClrFund {
nativeTokenAddress: string
Expand All @@ -19,19 +21,27 @@ export async function getClrFundInfo() {
let recipientRegistryAddress = ''

try {
const data = await sdk.GetClrFundInfo({
clrFundAddress: clrfundContractAddress.toLowerCase(),
})
if (isActiveApp) {
const data = await sdk.GetClrFundInfo({
clrFundAddress: clrfundContractAddress.toLowerCase(),
})
const nativeTokenInfo = data.clrFund?.nativeTokenInfo
if (nativeTokenInfo) {
nativeTokenAddress = nativeTokenInfo.tokenAddress || ''
nativeTokenSymbol = nativeTokenInfo.symbol || ''
nativeTokenDecimals = Number(nativeTokenInfo.decimals) || 0
}

const nativeTokenInfo = data.clrFund?.nativeTokenInfo
if (nativeTokenInfo) {
nativeTokenAddress = nativeTokenInfo.tokenAddress || ''
nativeTokenSymbol = nativeTokenInfo.symbol || ''
nativeTokenDecimals = Number(nativeTokenInfo.decimals) || 0
userRegistryAddress = data.clrFund?.contributorRegistryAddress || ''
recipientRegistryAddress = data.clrFund?.recipientRegistryAddress || ''
} else {
nativeTokenAddress = await clrFundContract.nativeToken()
const nativeTokenContract = new Contract(nativeTokenAddress, ERC20, provider)
nativeTokenSymbol = await nativeTokenContract.symbol()
nativeTokenDecimals = await nativeTokenContract.decimals()
userRegistryAddress = await clrFundContract.userRegistry()
recipientRegistryAddress = await clrFundContract.recipientRegistry()
}

userRegistryAddress = data.clrFund?.contributorRegistryAddress || ''
recipientRegistryAddress = data.clrFund?.recipientRegistryAddress || ''
} catch (err) {
/* eslint-disable-next-line no-console */
console.error('Failed GetClrFundInfo', err)
Expand Down
19 changes: 10 additions & 9 deletions vue-app/src/api/contributions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Contract, FixedNumber, parseUnits, id } from 'ethers'
import { Contract, FixedNumber, parseUnits, id, AbiCoder } from 'ethers'
import type { TransactionResponse, Signer } from 'ethers'
import { Keypair, PubKey, PrivKey, Message, Command } from '@clrfund/common'

Expand Down Expand Up @@ -81,16 +81,17 @@ export async function getContributionAmount(fundingRoundAddress: string, contrib
if (!fundingRoundAddress) {
return 0n
}
const data = await sdk.GetContributionsAmount({
fundingRoundAddress: fundingRoundAddress.toLowerCase(),
contributorAddress: contributorAddress.toLowerCase(),
})

if (!data.contributions.length) {
const fundingRound = new Contract(fundingRoundAddress, FundingRound, provider)
try {
const abiCoder = AbiCoder.defaultAbiCoder()
const userData = abiCoder.encode(['address'], [contributorAddress])
const voiceCredits = await fundingRound.getVoiceCredits(contributorAddress, userData)
const voiceCreditFactor = await fundingRound.voiceCreditFactor()
return BigInt(voiceCredits) * BigInt(voiceCreditFactor)
} catch {
// ignore error as older contract does not expose the contributors info
return 0n
}

return BigInt(data.contributions[0].amount)
}

export async function getTotalContributed(fundingRoundAddress: string): Promise<{ count: number; amount: bigint }> {
Expand Down
30 changes: 30 additions & 0 deletions vue-app/src/api/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,3 +261,33 @@ export function formToProjectInterface(data: RecipientApplicationData): Project
isLocked: true,
}
}

/**
* Format the project data from the static round data to project interface
* @param project project data from the static round file
* @returns formatted project data
*/
export function staticDataToProjectInterface(project: any): Project {
return {
id: project.id,
address: project.recipientAddress,
name: project.metadata.name,
tagline: project.metadata.tagline,
description: project.metadata.description,
category: project.metadata.category,
problemSpace: project.metadata.problemSpace,
plans: project.metadata.plans,
teamName: project.metadata.teamName,
teamDescription: project.metadata.teamDescription,
githubUrl: project.metadata.githubUrl,
radicleUrl: project.metadata.radicleUrl,
websiteUrl: project.metadata.websiteUrl,
twitterUrl: project.metadata.twitterUrl,
discordUrl: project.discordUrl,
bannerImageUrl: `${ipfsGatewayUrl}/ipfs/${project.metadata.bannerImageHash}`,
thumbnailImageUrl: `${ipfsGatewayUrl}/ipfs/${project.metadata.thumbnailImageHash}`,
index: project.recipientIndex,
isHidden: project.state !== 'Accepted',
isLocked: false,
}
}
7 changes: 6 additions & 1 deletion vue-app/src/api/round.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { DateTime } from 'luxon'
import { PubKey, type Tally } from '@clrfund/common'

import { FundingRound, Poll } from './abi'
import { provider, clrFundContract } from './core'
import { provider, clrFundContract, isActiveApp } from './core'
import { getTotalContributed } from './contributions'
import { isVoidedRound } from './rounds'
import sdk from '@/graphql/sdk'
Expand Down Expand Up @@ -151,6 +151,11 @@ export async function getRoundInfo(
return cachedRound
}

if (!isActiveApp) {
// static app should use the exported round information from rounds.json
return null
}

const fundingRound = new Contract(fundingRoundAddress, FundingRound, provider)
const data = await sdk.GetRoundInfo({
fundingRoundAddress: roundAddress.toLowerCase(),
Expand Down
9 changes: 4 additions & 5 deletions vue-app/src/api/rounds.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import sdk from '@/graphql/sdk'
import extraRounds from '@/rounds/rounds.json'
import { chain, voidedRounds } from './core'
import { chain, voidedRounds, isActiveApp, clrfundContractAddress } from './core'

export interface Round {
index: number
Expand All @@ -21,14 +21,13 @@ function toRoundId({ network, address }: { network: string; address: string }):

/**
* Get a list of funding rounds created by the clrFund contract
* @param clrFundAddress The ClrFund contract address
* @returns A list of funding rounds sorted by start time in descending order
*/
export async function getRounds(clrFundAddress?: string): Promise<Round[]> {
export async function getRounds(): Promise<Round[]> {
let data
if (clrFundAddress) {
if (isActiveApp) {
try {
data = await sdk.GetRounds({ clrFundAddress: clrFundAddress.toLowerCase() })
data = await sdk.GetRounds({ clrFundAddress: clrfundContractAddress.toLowerCase() })
} catch {
data = { fundingRounds: [] }
}
Expand Down
4 changes: 2 additions & 2 deletions vue-app/src/components/ActiveApp.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ interface Props {
showBreadCrumb: boolean
isSidebarShown: boolean
}
defineProps<Props>()
const props = defineProps<Props>()
const route = useRoute()
const wallet = useWalletStore()
Expand All @@ -45,7 +45,7 @@ const routeName = computed(() => route.name?.toString() || '')
const intervals: { [key: string]: any } = {}
const isUserAndRoundLoaded = computed(() => !!currentUser.value && !!currentRound.value)
const isSideCartShown = computed(() => isUserAndRoundLoaded.value && isSidebarShown.value && routeName.value !== 'cart')
const isSideCartShown = computed(() => isUserAndRoundLoaded.value && props.isSidebarShown && routeName.value !== 'cart')
const isVerifyStep = computed(() => routeName.value === 'verify-step')
const isCartPadding = computed(() => {
const routes = ['cart']
Expand Down
24 changes: 0 additions & 24 deletions vue-app/src/components/Cart.vue
Original file line number Diff line number Diff line change
Expand Up @@ -130,16 +130,6 @@
}}
</div>
</div>
<div class="submit-btn-wrapper" v-if="canWithdrawContribution && cart.length >= 1">
<button class="btn-action" @click="openWithdrawalModal()">
{{
$t('cart.button1', {
contribution: formatAmount(contribution),
tokenSymbol: tokenSymbol,
})
}}
</button>
</div>
<div
class="submit-btn-wrapper"
v-if="
Expand Down Expand Up @@ -232,7 +222,6 @@ import WalletModal from '@/components/WalletModal.vue'
import SignatureModal from '@/components/SignatureModal.vue'
import ContributionModal from '@/components/ContributionModal.vue'
import ReallocationModal from '@/components/ReallocationModal.vue'
import WithdrawalModal from '@/components/WithdrawalModal.vue'
import CartItems from '@/components/CartItems.vue'
import Links from '@/components/Links.vue'
import TimeLeft from '@/components/TimeLeft.vue'
Expand Down Expand Up @@ -562,15 +551,6 @@ const votes = computed(() => {
return formattedVotes
})
const { open: openWithdrawalModal, close: closeWithdrawalModal } = useModal({
component: WithdrawalModal,
attrs: {
onClose() {
closeWithdrawalModal()
},
},
})
function submitCart(event: any) {
event.preventDefault()
Expand Down Expand Up @@ -604,10 +584,6 @@ function submitCart(event: any) {
appStore.toggleEditSelection(false)
}
const canWithdrawContribution = computed(
() => currentRound.value?.status === RoundStatus.Cancelled && !contribution.value,
)
const showCollapseCart = computed(() => route.name !== 'cart')
function openDropdown() {
Expand Down
4 changes: 2 additions & 2 deletions vue-app/src/components/NavBar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
<p class="item-text">{{ $t('navBar.dropdown.rounds') }}</p>
</links>
</div>
<div v-if="isOptimisticRecipientRegistry" class="dropdown-item" @click="closeHelpDropdown">
<div v-if="isOptimisticRecipientRegistry && isActiveApp" class="dropdown-item" @click="closeHelpDropdown">
<links to="/recipients">
<div class="emoji-wrapper">💎</div>
<p class="item-text">{{ $t('navBar.dropdown.recipients') }}</p>
Expand Down Expand Up @@ -87,7 +87,7 @@
</template>

<script setup lang="ts">
import { chain, ThemeMode, isOptimisticRecipientRegistry } from '@/api/core'
import { chain, ThemeMode, isOptimisticRecipientRegistry, isActiveApp } from '@/api/core'
import { lsGet, lsSet } from '@/utils/localStorage'
import { isValidTheme, getDefaultColorScheme } from '@/utils/theme'
import { useAppStore } from '@/stores'
Expand Down
49 changes: 41 additions & 8 deletions vue-app/src/components/StaticApp.vue
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
<template>
<div
id="content"
class="mr-cart-closed"
:class="{
padded: isSidebarShown,
}"
>
<div id="content" class="app-margin">
<breadcrumbs v-if="showBreadCrumb" />
<router-view :key="route.path" />
</div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '@/stores'
import { useAppStore, useWalletStore, useUserStore, type WalletUser } from '@/stores'
import type { BrowserProvider } from 'ethers'
interface Props {
showBreadCrumb: boolean
Expand All @@ -26,6 +21,10 @@ const router = useRouter()
const appStore = useAppStore()
const { currentRound } = storeToRefs(appStore)
const userStore = useUserStore()
const wallet = useWalletStore()
const { user: walletUser } = storeToRefs(wallet)
onMounted(async () => {
await appStore.loadStaticClrFundInfo()
appStore.isAppReady = true
Expand All @@ -40,4 +39,38 @@ onMounted(async () => {
})
}
})
watch(walletUser, async () => {
try {
if (walletUser.value) {
const user: WalletUser = {
chainId: walletUser.value.chainId,
walletAddress: walletUser.value.walletAddress,
web3Provider: walletUser.value.web3Provider as BrowserProvider,
}
// make sure factory is loaded
await appStore.loadStaticClrFundInfo()
userStore.loginUser(user)
await userStore.loadUserInfo()
} else {
await userStore.logoutUser()
}
} catch (err) {
/* eslint-disable-next-line no-console */
console.log('error', err)
}
})
</script>

<style lang="scss">
@import '../styles/vars';
@import '../styles/fonts';
@import '../styles/theme';
.app-margin {
margin-right: 1.5rem;
@media (max-width: $breakpoint-m) {
margin-right: 0;
}
}
</style>
2 changes: 1 addition & 1 deletion vue-app/src/locales/cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,7 @@
"tooltip2": "{chain} 链上钱包余额",
"h2_3": "项目",
"div1": "正在审核",
"withdraw_button": "取回 {contribution} {tokenSymbol}",
"btn2_1": "预览",
"btn2_2": "查看",
"div2": "您尚未提交任何项目"
Expand Down Expand Up @@ -891,7 +892,6 @@
"div8": "匹配池",
"div9": "剩余的将会加入匹配池",
"div10": "平均分配 {contribution} {tokenSymbol}",
"button1": "取回 {contribution} {tokenSymbol}",
"div11": "不可以",
"div11_if2": "重新分配",
"div11_if3": "捐赠",
Expand Down
2 changes: 1 addition & 1 deletion vue-app/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,7 @@
"tooltip2": "Balance of wallet on {chain} chain",
"h2_3": "Projects",
"div1": "Under review",
"withdraw_button": "Withdraw {contribution} {tokenSymbol}",
"btn2_1": "Preview",
"btn2_2": "View",
"div2": "You haven't submitted any projects"
Expand Down Expand Up @@ -891,7 +892,6 @@
"div8": "Matching pool",
"div9": "Remaining funds go to matching pool",
"div10": "Split {contribution} {tokenSymbol} evenly",
"button1": "Withdraw {contribution} {tokenSymbol}",
"div11": "Can't",
"div11_if2": "reallocate",
"div11_if3": "contribute",
Expand Down
2 changes: 1 addition & 1 deletion vue-app/src/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,7 @@
"tooltip2": "Saldo de la billetera en la cadena {chain}",
"h2_3": "Proyectos",
"div1": "En revisión",
"withdraw_button": "Retirar {contribution} {tokenSymbol}",
"btn2_1": "Vista previa",
"btn2_2": "Ver",
"div2": "No has enviado ningún proyecto"
Expand Down Expand Up @@ -891,7 +892,6 @@
"div8": "Matching pool",
"div9": "Los fondos restantes se destinarán al matching pool",
"div10": "Distribuir {contribution} {tokenSymbol} de manera uniforme",
"button1": "Retirar {contribution} {tokenSymbol}",
"div11": "No puedes",
"div11_if2": "reasignar",
"div11_if3": "contribuir",
Expand Down
4 changes: 2 additions & 2 deletions vue-app/src/router/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { isUserRegistrationRequired, isOptimisticRecipientRegistry } from '@/api/core'
import { isUserRegistrationRequired, isOptimisticRecipientRegistry, isActiveApp } from '@/api/core'

const Landing = () => import('@/views/Landing.vue')
const JoinLanding = () => import('@/views/JoinLanding.vue')
Expand Down Expand Up @@ -262,7 +262,7 @@ if (isUserRegistrationRequired) {
)
}

if (isOptimisticRecipientRegistry) {
if (isOptimisticRecipientRegistry && isActiveApp) {
routes.push({
path: '/recipients',
name: 'recipients',
Expand Down
3 changes: 3 additions & 0 deletions vue-app/src/stores/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,9 @@ export const useAppStore = defineStore('app', {
maxRecipients = currentRoundInfo.maxRecipients
}
}
if (!this.clrFund) {
this.clrFund = await getClrFundInfo()
}
await this.loadMACIFactoryInfo(maxRecipients)
},
async loadClrFundInfo() {
Expand Down
Loading

0 comments on commit 179e0da

Please sign in to comment.