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

[PartnerConfig]: added tokens to accepted currencies #258

Merged
merged 2 commits into from
Oct 14, 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
39 changes: 39 additions & 0 deletions src/helpers/usePartnerConfig.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ export const usePartnerConfig = () => {
managerReadContract,
wallet,
CMAccountCreated,
contractCMAccountAddress,
accountReadContract,
provider,
} = useSmartContract()
const activeNetwork = useAppSelector(getActiveNetwork)
const auth = useAppSelector(state => state.appConfig.isAuth)
Expand Down Expand Up @@ -368,6 +370,42 @@ export const usePartnerConfig = () => {
[account, accountWriteContract],
)

const transferERC20 = useCallback(
async (address, value) => {
if (!account) {
console.error('Account is not initialized')
return
}
try {
const abi = [
{
constant: true,
inputs: [{ name: '_owner', type: 'address' }],
name: 'balanceOf',
outputs: [{ name: 'balance', type: 'uint256' }],
type: 'function',
},
]

// Create a contract instance
const contract = new ethers.Contract(address, abi, provider)

// Call the balanceOf function
const balance = await contract.balanceOf(contractCMAccountAddress)
const tx = await accountWriteContract.transferERC20(address, wallet.address, value)
await tx.wait()
const afterBalance = await contract.balanceOf(contractCMAccountAddress)
const afterFormattedBalance = ethers.formatUnits(afterBalance, 18)
return afterFormattedBalance
} catch (error) {
const decodedError = accountWriteContract.interface.parseError(error.data)
console.error('Message:', error.message)
console.error(`Reason: ${decodedError?.name} (${decodedError?.args})`)
}
},
[account, accountWriteContract],
)

const setOffChainPaymentSupported = useCallback(
async value => {
if (!account) {
Expand Down Expand Up @@ -454,6 +492,7 @@ export const usePartnerConfig = () => {
}, [account, readFromContract])

return {
transferERC20,
checkWithDrawRole,
grantWithDrawRole,
withDraw,
Expand Down
145 changes: 142 additions & 3 deletions src/views/partners/MyMessenger.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
import { ethers } from 'ethers'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router'
import store from 'wallet/store'
import Alert from '../../components/Alert'
import DialogAnimate from '../../components/Animate/DialogAnimate'
import MainButton from '../../components/MainButton'
Expand Down Expand Up @@ -323,6 +324,8 @@ const MyMessenger = () => {
const [isCAMSupported, setCAMSupported] = useState(false)
const [isEditMode, setIsEditMode] = useState(false)
const [tempOffChainPaymentSupported, setTempOffChainPaymentSupported] = useState(false)
const [tempSupportedTokens, setTempSupportedTokens] = useState([])
const [supportedTokens, setSupportedTokens] = useState([])
const [tempCAMSupported, setTempCAMSupported] = useState(false)
const { balanceOfAnAddress, getBalanceOfAnAddress } = useWalletBalance()
const [isLoading, setIsLoading] = useState(false)
Expand All @@ -335,6 +338,7 @@ const MyMessenger = () => {
addSupportedToken,
removeSupportedToken,
getListOfBots,
transferERC20,
} = usePartnerConfig()
const { data: partner, refetch } = useFetchPartnerDataQuery({
companyName: '',
Expand Down Expand Up @@ -380,6 +384,33 @@ const MyMessenger = () => {
if (tempCAMSupported) await addSupportedToken(ethers.ZeroAddress)
else await removeSupportedToken(ethers.ZeroAddress)
}
if (tempSupportedTokens) {
const result = []

for (const address of supportedTokens) {
const foundToken = tempSupportedTokens.find(
token =>
token.address.toLowerCase() === address.toLowerCase() &&
token.supported,
)

if (foundToken) {
result.push({
address: foundToken.address,
name: foundToken.name,
symbol: foundToken.symbol,
added: true,
})
} else {
result.push({
address: address,
added: false,
})
}
}

return result
}
appDispatch(
updateNotificationStatus({
message: 'Accepted currencies updated successfully',
Expand All @@ -399,6 +430,32 @@ const MyMessenger = () => {
const res = await getListOfBots()
setBots(res)
}
async function fetchSupportedTokens() {
const res = await getSupportedTokens()
setSupportedTokens(res)
}

const tokens = useMemo(() => {
if (
store.getters['Assets/networkErc20Tokens'] &&
store.getters['Assets/networkErc20Tokens'].length > 0
) {
let tokens = store.getters['Assets/networkErc20Tokens'].map(elem => {
return {
address: elem.contract._address,
balance: elem.balanceBig.toLocaleString(),
name: elem.data.name,
symbol: elem.data.symbol,
decimal: elem.data.decimal,
supported: supportedTokens.find(token => token === elem.contract._address),
}
})
setTempSupportedTokens([...tokens])
return tokens
}
return []
}, [supportedTokens])

useEffect(() => {
checkIfCamSupported()
checkIfOffChainPaymentSupported()
Expand All @@ -407,6 +464,7 @@ const MyMessenger = () => {

useEffect(() => {
fetchBots()
fetchSupportedTokens()
}, [])

function getServicesNames(services) {
Expand Down Expand Up @@ -489,7 +547,11 @@ const MyMessenger = () => {
<>
None. Visit the relevant{' '}
<Link
sx={{ cursor: 'pointer' }}
sx={{
cursor: 'pointer',
color: theme => theme.palette.text.primary,
textDecorationColor: 'inherit',
}}
onClick={() =>
navigate('/partners/messenger-configuration/supplier')
}
Expand All @@ -512,7 +574,11 @@ const MyMessenger = () => {
<>
None. Visit the relevant{' '}
<Link
sx={{ cursor: 'pointer' }}
sx={{
cursor: 'pointer',
color: theme => theme.palette.text.primary,
textDecorationColor: 'inherit',
}}
onClick={() =>
navigate(
'/partners/messenger-configuration/distribution',
Expand Down Expand Up @@ -544,7 +610,11 @@ const MyMessenger = () => {
<>
None. Visit the relevant{' '}
<Link
sx={{ cursor: 'pointer' }}
sx={{
cursor: 'pointer',
color: theme => theme.palette.text.primary,
textDecorationColor: 'inherit',
}}
onClick={() =>
navigate('/partners/messenger-configuration/bots')
}
Expand Down Expand Up @@ -669,6 +739,75 @@ const MyMessenger = () => {
</Button>
)}
</Box>
{tokens.length > 0 &&
tokens.map((elem, index) => {
return (
<Box
sx={{
display: 'flex',
alignItems: 'center',
gap: '8px',
justifyContent: 'space-between',
}}
key={index}
>
<FormControlLabel
disabled={!isEditMode}
label={
<Typography variant="body2">
{elem.name}: {elem.balance} {elem.symbol}
</Typography>
}
control={
<Checkbox
sx={{
m: '0 8px 0 0',
color: theme =>
!isEditMode
? theme.palette.action.disabled
: theme.palette.secondary.main,
'&.Mui-checked': {
color: theme =>
!isEditMode
? theme.palette.action.disabled
: theme.palette.secondary.main,
},
'&.MuiCheckbox-colorSecondary.Mui-checked':
{
color: theme =>
!isEditMode
? theme.palette.action
.disabled
: theme.palette.secondary
.main,
},
}}
checked={
isEditMode
? tempSupportedTokens[index].supported
: elem.supported
}
onChange={e => {
let newArray = [...tempSupportedTokens]
newArray[index].supported = e.target.checked
setTempSupportedTokens(newArray)
}}
/>
}
/>
{!isEditMode && (
<Button
variant="contained"
onClick={() => {
transferERC20()
}}
>
Withdraw
</Button>
)}
</Box>
)
})}
<Box
sx={{
display: 'flex',
Expand Down
Loading