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

feat(partnerConfig): redirect to upgrade view if needed #264

Merged
merged 1 commit into from
Oct 29, 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
33 changes: 30 additions & 3 deletions src/helpers/partnerConfigurationContext.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { ethers } from 'ethers'
import React, { createContext, useContext, useEffect, useReducer } from 'react'
import React, {
createContext,
useCallback,
useContext,
useEffect,
useReducer,
useState,
} from 'react'
import { useNavigate } from 'react-router'
import { usePartnerConfig } from './usePartnerConfig'
import { useSmartContract } from './useSmartContract'

Expand Down Expand Up @@ -374,9 +382,11 @@ const PartnerConfigContext = createContext()
// Context provider component
export const PartnerConfigurationProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState)
const [firstLoad, setFirstLoad] = useState(false)
const partnerConfig = usePartnerConfig()
const { accountReadContract } = useSmartContract()

const { accountReadContract, accountWriteContract, contractCMAccountAddress, needsUpgrade } =
useSmartContract()
const path = window.location.pathname
useEffect(() => {
if (partnerConfig.account) {
partnerConfig.getAllServices().then(result => {
Expand All @@ -390,6 +400,23 @@ export const PartnerConfigurationProvider = ({ children }) => {
}
}, [partnerConfig.account])

const navigate = useNavigate()

const checkIfCMAccountneedsUpgrade = useCallback(async () => {
let res = await needsUpgrade()
setFirstLoad(true)
if (res) navigate('/partners/upgrade')
}, [contractCMAccountAddress, accountWriteContract])

useEffect(() => {
if (
contractCMAccountAddress &&
path.includes('partners/messenger-configuration') &&
!firstLoad
) {
checkIfCMAccountneedsUpgrade()
}
}, [contractCMAccountAddress, accountWriteContract, path])
useEffect(() => {
if (accountReadContract) {
partnerConfig.getSupportedServices().then(res => {
Expand Down
2 changes: 0 additions & 2 deletions src/helpers/usePartnerConfig.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ export const usePartnerConfig = () => {
managerReadContract,
wallet,
CMAccountCreated,
contractCMAccountAddress,
accountReadContract,
provider,
} = useSmartContract()
const activeNetwork = useAppSelector(getActiveNetwork)
const auth = useAppSelector(state => state.appConfig.isAuth)
Expand Down
24 changes: 21 additions & 3 deletions src/helpers/useSmartContract.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ type SmartContractProviderProps = {

export const SmartContractProvider: React.FC<SmartContractProviderProps> = ({ children }) => {
const [provider, setProvider] = useState<ethers.JsonRpcProvider | null>(null)
const [needUpgrade, setNeedUpgrade] = useState(false)
const [managerReadContract, setManagerReadContract] = useState<ethers.Contract | null>(null)
const [managerWriteContract, setManagerWriteContract] = useState<ethers.Contract | null>(null)
const [accountReadContract, setAccountReadContract] = useState<ethers.Contract | null>(null)
Expand Down Expand Up @@ -84,7 +85,7 @@ export const SmartContractProvider: React.FC<SmartContractProviderProps> = ({ ch
}
}

const upgradeCMAccount = useCallback(async () => {
const needsUpgrade = useCallback(async () => {
try {
if (accountWriteContract) {
const implementation = await managerReadContract.getAccountImplementation()
Expand All @@ -94,10 +95,25 @@ export const SmartContractProvider: React.FC<SmartContractProviderProps> = ({ ch
IMPLEMENTATION_SLOT,
)
const implAddr = '0x' + implAddrPadded.slice(-40)
console.log({ implementation, implAddr })
if (ethers.getAddress(implementation) !== ethers.getAddress(implAddr)) {
setNeedUpgrade(true)
return true
}
return false
}
} catch (error) {
const decodedError = accountWriteContract.interface.parseError(error.data)
console.error('Message:', error.message)
console.error(`Reason: ${decodedError?.name} (${decodedError?.args})`)
}
}, [accountWriteContract])

const upgradeCMAccount = useCallback(async () => {
try {
if (accountWriteContract) {
const implementation = await managerReadContract.getAccountImplementation()
const tx = await accountWriteContract.upgradeToAndCall(implementation, '0x')
const receipt = await tx.wait()
console.log({ receipt })
return receipt
}
} catch (error) {
Expand Down Expand Up @@ -262,8 +278,10 @@ export const SmartContractProvider: React.FC<SmartContractProviderProps> = ({ ch
}

const value = {
needUpgrade,
getCMAccountMappings,
upgradeCMAccount,
needsUpgrade,
contractCMAccountAddress,
setContractCMAccountAddress,
wallet,
Expand Down
9 changes: 3 additions & 6 deletions src/layout/RoutesSuite.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import CreatedOffers from '../views/partners/CreatedOffers'
import Foundation from '../views/partners/Foundation'
import ManageBots, { BasicManageBots } from '../views/partners/ManageBots'
import Partner from '../views/partners/Partner'
import UpgradeCMAccount from '../views/partners/UpgradeCMAccount'
import MultisigWallet from '../views/settings/MultisigWallet'
import VerifyWallet from '../views/settings/VerifyWallet'
import Settings from '../views/settings/index'
Expand Down Expand Up @@ -113,15 +114,11 @@ export default function RoutesSuite() {
</Route>
<Route path="/partners" element={<PartnersLayout />}>
<Route index element={<Partners />} />
<Route path="upgrade" element={<UpgradeCMAccount />} />
<Route path=":partnerID/distribution" element={<BasicWantedServices />} />
<Route path=":partnerID/supplier" element={<BasicSupportedServices />} />
<Route path=":partnerID/bots" element={<BasicManageBots />} />
<Route path=":partnerID" element={<Partner />}>
<Route index element={<Partner />} />
{/* <Route path="distribution" element={<ConfigurDistrubitor />} /> */}
{/* <Route path="supplier" element={<ConfigurSupplier />} /> */}
{/* <Route path="bots" element={<ManageBots />} /> */}
</Route>
<Route path=":partnerID" element={<Partner />} />
<Route path="messenger-configuration">
<Route index element={<Partner />} />
<Route path="mymessenger" element={<Overreview />} />
Expand Down
80 changes: 80 additions & 0 deletions src/views/partners/UpgradeCMAccount.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Box, Link, Typography } from '@mui/material'
import React, { useState } from 'react'
import { Navigate, useNavigate } from 'react-router'
import MainButton from '../../components/MainButton'
import { useSmartContract } from '../../helpers/useSmartContract'
import { useAppDispatch, useAppSelector } from '../../hooks/reduxHooks'
import { updateNotificationStatus } from '../../redux/slices/app-config'

const UpgradeCMAccount = () => {
const navigate = useNavigate()
const [loading, setLoading] = useState(false)
const { contractCMAccountAddress, upgradeCMAccount } = useSmartContract()
const auth = useAppSelector(state => state.appConfig.isAuth)
const appDispatch = useAppDispatch()
if (!auth) return <Navigate to="/login" replace></Navigate>
async function upgrade() {
setLoading(true)
await upgradeCMAccount()
appDispatch(
updateNotificationStatus({
message: 'Camion Messenger account upgraded successfully.',
severity: 'success',
}),
)
setLoading(false)
navigate('/partners/messenger-configuration/mymessenger')
}
return (
<Box
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
gap: '8px',
height: '100%',
}}
>
<Typography variant="h5">Housekeeping needed</Typography>
<Typography variant="body2" textAlign={'center'}>
new implementation of the Camino Messenger Account smart contract is available.
While current functionality is not disrupted, we need your confirmation to upgrade
you to the new smart contrtact. This operation will incur a minimal cost (0.02 CAM).
</Typography>
<Typography variant="body2" textAlign={'center'}>
Upgrade Camino Messenger Account {contractCMAccountAddress},
<Link
component="a"
sx={{
color: theme => theme.palette.text.primary,
textDecorationColor: 'inherit',
cursor: 'pointer',
}}
onClick={() => navigate('/partners/messenger-configuration/mymessenger')}
>
{' '}
or Skip and go to My Account.
</Link>
</Typography>
<MainButton
loading={loading}
variant="contained"
onClick={upgrade}
style={{
padding: '10px 16px',
borderRadius: '8px',
background: 'linear-gradient(90deg, #0085FF 0%, #B440FC 100%)',
backgroundColor: theme =>
theme.palette.mode === 'dark' ? '#020617' : '#F1F5F9',
}}
>
<Typography fontSize={14} fontWeight={600} lineHeight={'20px'}>
Upgrade
</Typography>
</MainButton>
</Box>
)
}

export default UpgradeCMAccount
Loading