Skip to content

Commit

Permalink
fix(MyMessenger): fixed withdraw tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
aeddaqqa committed Oct 17, 2024
1 parent d381063 commit fab8b8a
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 51 deletions.
9 changes: 9 additions & 0 deletions src/constants/apps-consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ export const ERC20_ABI = [
'function totalSupply() view returns (uint256)',
'function balanceOf(address) view returns (uint256)',
]
export const ERC20_BALANCE_ABI = [
{
constant: true,
inputs: [{ name: '_owner', type: 'address' }],
name: 'balanceOf',
outputs: [{ name: 'balance', type: 'uint256' }],
type: 'function',
},
]

export const CONTRACTCMACCOUNTMANAGERADDRESSCOLUMBUS = '0xE5B2f76C778D082b07BDd7D51FFe83E3E055B47F'

Expand Down
16 changes: 6 additions & 10 deletions src/helpers/usePartnerConfig.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ export const usePartnerConfig = () => {
)

const transferERC20 = useCallback(
async (address, value) => {
async (tokenAddress, to, value) => {
if (!account) {
console.error('Account is not initialized')
return
Expand All @@ -387,16 +387,12 @@ export const usePartnerConfig = () => {
},
]

// 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)
const tx = await accountWriteContract.transferERC20(
tokenAddress,
ethers.getAddress(to),
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)
Expand Down
26 changes: 17 additions & 9 deletions src/redux/services/partners.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ const BASE_URLS = {
}

function createPartnerContract(address: string, provider: ethers.Provider) {
return new ethers.Contract(address, CMAccount, provider)
try {
const contract = new ethers.Contract(address, CMAccount, provider)
return contract
} catch (e) {
return null
}
}

const getListOfBots = async contract => {
Expand Down Expand Up @@ -62,15 +67,18 @@ async function fetchContractServices(contractAddress: string, provider: ethers.P
const contract = createPartnerContract(contractAddress, provider)

try {
const [supportedServices, wantedServices, bots, supportedCurrencies] = await Promise.all([
contract.getSupportedServices(),
contract.getWantedServices(),
getListOfBots(contract),
getSupportedCurrencies(contract, provider),
])
return { supportedServices, wantedServices, bots, supportedCurrencies }
if (contract) {
const [supportedServices, wantedServices, bots, supportedCurrencies] =
await Promise.all([
contract.getSupportedServices(),
contract.getWantedServices(),
getListOfBots(contract),
getSupportedCurrencies(contract, provider),
])
return { supportedServices, wantedServices, bots, supportedCurrencies }
}
return { supportedServices: [], wantedServices: [] }
} catch (error) {
console.error(`Error fetching services for ${contractAddress}:`, error)
return { supportedServices: [], wantedServices: [] }
}
}
Expand Down
93 changes: 61 additions & 32 deletions src/views/partners/MyMessenger.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import store from 'wallet/store'
import Alert from '../../components/Alert'
import DialogAnimate from '../../components/Animate/DialogAnimate'
import MainButton from '../../components/MainButton'
import { ERC20_BALANCE_ABI } from '../../constants/apps-consts'
import { usePartnerConfigurationContext } from '../../helpers/partnerConfigurationContext'
import { usePartnerConfig } from '../../helpers/usePartnerConfig'
import { useSmartContract } from '../../helpers/useSmartContract'
Expand Down Expand Up @@ -163,24 +164,25 @@ const AddressInput = ({ address, onAddressChange, onMyAddressClick }) => {
)
}

const CamWithdraw = ({ setOpen }) => {
const CamWithdraw = ({ setOpen, token, fetchTokenBalances }) => {
const { wallet, contractCMAccountAddress } = useSmartContract()
const [address, setAddress] = useState('')
const [amount, setAmount] = useState('')
const [confirm, setConfirm] = useState(false)
const [isValidAddress, setIsValidAddress] = useState(false)
const [loading, setLoading] = useState(false)
const [amountError, setAmountError] = useState('')
const { withDraw } = usePartnerConfig()
const { withDraw, transferERC20 } = usePartnerConfig()
const { getBalanceOfAnAddress, balanceOfAnAddress: balance } = useWalletBalance()

const maxAmount = useMemo(() => {
if (token) return parseFloat(token.balance)
const balanceParsed = parseFloat(balance)
if (isNaN(balanceParsed)) {
return '0.00'
}
return Math.max(balanceParsed - 100, 0).toFixed(2)
}, [balance])
}, [balance, token])

const handleAddressChange = useCallback(newAddress => {
setAddress(newAddress)
Expand Down Expand Up @@ -225,8 +227,13 @@ const CamWithdraw = ({ setOpen }) => {

async function handleWithdraw() {
setLoading(true)
await withDraw(address, ethers.parseEther(amount))
getBalanceOfAnAddress(contractCMAccountAddress)
if (!token) {
await withDraw(address, ethers.parseEther(amount))
getBalanceOfAnAddress(contractCMAccountAddress)
} else {
await transferERC20(token.address, address, ethers.parseEther(amount))
await fetchTokenBalances()
}
setAmount('')
setConfirm(false)
setAddress('')
Expand Down Expand Up @@ -320,6 +327,7 @@ const CamWithdraw = ({ setOpen }) => {
const MyMessenger = () => {
const { state, dispatch } = usePartnerConfigurationContext()
const [open, setOpen] = useState(false)
const [selectedToken, setSelectedToken] = useState(null)
const [isOffChainPaymentSupported, setIsOffChainPaymentSupported] = useState(false)
const [isCAMSupported, setCAMSupported] = useState(false)
const [isEditMode, setIsEditMode] = useState(false)
Expand All @@ -330,15 +338,15 @@ const MyMessenger = () => {
const { balanceOfAnAddress, getBalanceOfAnAddress } = useWalletBalance()
const [isLoading, setIsLoading] = useState(false)
const [bots, setBots] = useState([])
const { contractCMAccountAddress, wallet } = useSmartContract()
const [tokens, setTokens] = useState([])
const { contractCMAccountAddress, wallet, provider } = useSmartContract()
const {
getSupportedTokens,
getOffChainPaymentSupported,
setOffChainPaymentSupported,
addSupportedToken,
removeSupportedToken,
getListOfBots,
transferERC20,
} = usePartnerConfig()
const { data: partner, refetch } = useFetchPartnerDataQuery({
companyName: '',
Expand All @@ -349,7 +357,7 @@ const MyMessenger = () => {
if (activeNetwork) refetch()
}, [activeNetwork])
const appDispatch = useAppDispatch()
const handleOpenModal = () => {
const handleOpenModal = token => {
setOpen(true)
}
async function checkIfOffChainPaymentSupported() {
Expand All @@ -358,6 +366,7 @@ const MyMessenger = () => {
}

const handleCloseModal = () => {
setSelectedToken(null)
setOpen(false)
}

Expand Down Expand Up @@ -423,26 +432,33 @@ const MyMessenger = () => {
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
const fetchTokenBalances = async () => {
const networkErc20Tokens = store.getters['Assets/networkErc20Tokens'] || []
if (networkErc20Tokens.length > 0) {
const fetchedTokens = await Promise.all(
networkErc20Tokens.map(async elem => {
const contract = new ethers.Contract(
elem.contract._address,
ERC20_BALANCE_ABI,
provider,
)
const balance = await contract.balanceOf(contractCMAccountAddress)
return {
address: elem.contract._address,
balance: ethers.formatUnits(balance, elem.data.decimal),
name: elem.data.name,
symbol: elem.data.symbol,
decimal: elem.data.decimal,
supported: supportedTokens.includes(elem.contract._address),
}
}),
)
setTokens(fetchedTokens)
}
return []
}, [supportedTokens])
}
useEffect(() => {
fetchTokenBalances()
}, [contractCMAccountAddress, supportedTokens])

useEffect(() => {
getBalanceOfAnAddress(contractCMAccountAddress)
Expand Down Expand Up @@ -637,7 +653,7 @@ const MyMessenger = () => {
<RefreshOutlined
onClick={() => {
getBalanceOfAnAddress(contractCMAccountAddress)
fetchSupportedTokens()
fetchTokenBalances()
}}
sx={{
cursor: 'pointer',
Expand Down Expand Up @@ -722,7 +738,15 @@ const MyMessenger = () => {
}
/>
{!isEditMode && (
<Button variant="contained" onClick={handleOpenModal}>
<Button
variant="contained"
onClick={() => {
setSelectedToken(null)
handleOpenModal({
symbol: 'CAM',
})
}}
>
Withdraw
</Button>
)}
Expand Down Expand Up @@ -787,7 +811,8 @@ const MyMessenger = () => {
<Button
variant="contained"
onClick={() => {
transferERC20()
setSelectedToken(elem)
handleOpenModal(elem)
}}
>
Withdraw
Expand Down Expand Up @@ -1021,7 +1046,7 @@ const MyMessenger = () => {
}}
>
<Typography variant="body1" component="span">
Withdraw CAM
Withdraw {selectedToken ? selectedToken.symbol : 'CAM'}
</Typography>
<IconButton
aria-label="close"
Expand All @@ -1045,7 +1070,11 @@ const MyMessenger = () => {
theme.palette.mode === 'dark' ? '#020617' : '#F1F5F9',
}}
>
<CamWithdraw setOpen={setOpen} />
<CamWithdraw
setOpen={setOpen}
token={selectedToken}
fetchTokenBalances={fetchTokenBalances}
/>
</DialogContent>
</DialogAnimate>
</>
Expand Down

0 comments on commit fab8b8a

Please sign in to comment.