Skip to content

Commit

Permalink
Merge pull request #228 from P4-Games/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
dappsar committed Dec 4, 2023
2 parents e543301 + 17e261d commit c3352a6
Show file tree
Hide file tree
Showing 16 changed files with 611 additions and 40 deletions.
12 changes: 11 additions & 1 deletion public/locales/br/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -133,5 +133,15 @@
"offer_card_number_empty": "Não há ofertas para esta carta.",
"offer_card_no_la_tienes": "Você não tem este cartão para trocá-lo.",
"offer_user_limit": "Você atingiu o limite de ofertas que pode fazer. Aguarde para confirmar uma troca ou remover uma publicação.",
"offer_game_limit": "No momento, nenhuma outra oferta pode ser feita. Tente em alguns dias."
"offer_game_limit": "No momento, nenhuma outra oferta pode ser feita. Tente em alguns dias.",

"account_connect": "Conectar",
"account_disconnect": "Desconectar",
"account_invalid_network": "Rede inválida",
"account_text_copied": "Copiado",
"account_balance_zero": "Você não tem saldo suficiente para enviar.",
"account_send_dai_title": "Transferência de token",
"account_send_dai_quantity": "Cantidad",
"account_send_dai_quantity_invalid": "Cantidad Inválida.",
"account_send_dai_error": "Ocorreu um erro ao tentar transferir tokens."
}
12 changes: 11 additions & 1 deletion public/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -133,5 +133,15 @@
"offer_card_number_empty": "There are no offers for this card.",
"offer_card_no_la_tienes": "You do not have this card to exchange it.",
"offer_user_limit": "You have reached the limit of offers you can make. Wait to confirm an exchange or remove a publication.",
"offer_game_limit": "At the moment, no more offers can be made. Please try in a few days."
"offer_game_limit": "At the moment, no more offers can be made. Please try in a few days.",

"account_connect": "Connect",
"account_disconnect": "Disconnect",
"account_invalid_network": "Invalid Network",
"account_text_copied": "Copied",
"account_balance_zero": "You do not have enough balance to send.",
"account_send_dai_title": "Token Transfer",
"account_send_dai_quantity": "Quantity",
"account_send_dai_quantity_invalid": "Invalid Quantity.",
"account_send_dai_error": "There was an error trying to transfer tokens."
}
15 changes: 12 additions & 3 deletions public/locales/es/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@
"transfer_pack_error": "Hubo un error al intentar transferir un pack",
"finish_album_error": "Ocurrió un error al intentar reclamar el premio",
"finish_album_success": "Felicitaciones! Completaste el álbum. Recibirás en tu wallet tu premio en DAIs.",
"finish_album_no_qtty": "Aún no tiene el album completo para poder reclamar el premio",
"finish_album_no_qtty": "Aún no tienes el album completo para poder reclamar el premio",
"finish_album_warning": "Aún no están dadas las condiciones para que se puedan completar los álbumnes y reclamas los premios. Intenta en unos días!",

"publish_offer_error": "Hubo un error al intentar realizar la publicación",
Expand Down Expand Up @@ -133,7 +133,16 @@
"offer_card_number_empty": "No hay ofertas para esta carta.",
"offer_card_no_la_tienes": "No tienes esta carta para poder intercambiarla.",
"offer_user_limit": "Alcanzaste el límite de ofertas que podes realizar. Espera a confirmar algún intercambio o quita alguna publicación.",
"offer_game_limit": "Por el momento, no se pueden realizar más ofertas. Intenta en unos días."

"offer_game_limit": "Por el momento, no se pueden realizar más ofertas. Intenta en unos días.",

"account_connect": "Conectar",
"account_disconnect": "Desconectar",
"account_invalid_network": "Red Inválida",
"account_text_copied": "Copiado",
"account_balance_zero": "No tienes saldo suficiente para enviar.",
"account_send_dai_title": "Transferencia de Tokens",
"account_send_dai_quantity": "Cantidad",
"account_send_dai_quantity_invalid": "Cantidad Inválida.",
"account_send_dai_error": "Hubo un error al intentar transferir tokens."

}
282 changes: 282 additions & 0 deletions src/components/Navbar/AccountInfo.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,282 @@
import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import Link from 'next/link'
import { useTranslation } from 'next-i18next'
import Swal from 'sweetalert2'
import { HiOutlineClipboardDocument } from 'react-icons/hi2'
import { FaExternalLinkAlt as FaExternalLinkSquareAlt } from 'react-icons/fa'
import { GoLinkExternal } from 'react-icons/go'
import { AiOutlineSend } from 'react-icons/ai'
import { MdOutlinePublishedWithChanges } from 'react-icons/md'
import { useWeb3Context, useLayoutContext } from '../../hooks'
import { NETWORK, CONTRACTS } from '../../config'
import { getBalance, getTokenName, transfer } from '../../services/dai'
import { emitError, emitInfo, emitSuccess } from '../../utils/alert'
import { checkInputAddress, checkValue1GTValue2 } from '../../utils/InputValidators'

const AccountInfo = ({ showAccountInfo, setShowAccountInfo }) => {
const { t } = useTranslation()
const {
walletAddress,
connectWallet,
disconnectWallet,
isValidNetwork,
daiContract,
switchOrCreateNetwork
} = useWeb3Context()
const { startLoading, stopLoading } = useLayoutContext()
const [copiedTextVisible, setCopiedTextVisible] = useState(false)
const [copiedTextPosition, setCopiedTextPosition] = useState(0)
const [walletBalance, setWalletBalance] = useState(0)
const [tokenName, setTokenName] = useState('')

const fetchTokenName = async () => {
if (!walletAddress || !daiContract) return
const token = await getTokenName(daiContract)
setTokenName(token)
}

useEffect(() => {
fetchTokenName()
}, [showAccountInfo, tokenName, walletAddress]) //eslint-disable-line react-hooks/exhaustive-deps

const fetchBalance = async () => {
if (!walletAddress || !daiContract) return
const balance = await getBalance(daiContract, walletAddress)
setWalletBalance(balance)
}

useEffect(() => {
fetchBalance()
}, [showAccountInfo, walletBalance, walletAddress]) //eslint-disable-line react-hooks/exhaustive-deps

const getAccountAddressText = () => {
if (walletAddress <= 15) {
return walletAddress
} else {
const firstPart = walletAddress.substring(0, 7)
const lastPart = walletAddress.substring(walletAddress.length - 5)
return `${firstPart}...${lastPart}`
}
}

function copyToClipboard(text) {
navigator.clipboard.writeText(text)
}

const handleCopy = () => {
copyToClipboard(walletAddress)
setCopiedTextPosition(window.scrollY + 80)
setCopiedTextVisible(true)
setTimeout(() => {
setCopiedTextVisible(false)
}, 1000)
}

const handleSendTokenClick = async () => {
try {
setShowAccountInfo(false)
if (walletBalance === 0) {
emitInfo(t('account_balance_zero', 2000))
return
}

// swal2-inputerror
const result = await Swal.fire({
title: `${t('account_send_dai_title')}`,
html: `
<input id="wallet" class="swal2-input" placeholder="${t('wallet_destinatario')}">
<input id="amount" type='number' class="swal2-input" placeholder="${t('account_send_dai_quantity')}">
`,
showDenyButton: false,
showCancelButton: true,
confirmButtonText: `${t('transferir')}`,
confirmButtonColor: '#005EA3',
color: 'black',
background: 'white',
customClass: {
image: 'cardalertimg',
input: 'alertinput'
},
preConfirm: () => {
const walletInput = Swal.getPopup().querySelector('#wallet')
const amountInput = Swal.getPopup().querySelector('#amount')
const wallet = walletInput.value
const amount = amountInput.value
// document.getElementById('Wwallet').remove('swal2-inputerror')
// amountInput.classList.remove('swal2-inputerror')

if (
!checkInputAddress(wallet, walletAddress) &&
!checkValue1GTValue2(amount, walletBalance)
) {
walletInput.classList.add('swal2-inputerror')
amountInput.classList.add('swal2-inputerror')
Swal.showValidationMessage(
`${t('direccion_destino_error')}<br />${t('account_send_dai_quantity_invalid')}`
)
} else {
if (!checkInputAddress(wallet, walletAddress)) {
walletInput.classList.add('swal2-inputerror')
Swal.showValidationMessage(`${t('direccion_destino_error')}`)
}
if (!checkValue1GTValue2(amount, walletBalance)) {
amountInput.classList.add('swal2-inputerror')
Swal.showValidationMessage(`${t('account_send_dai_quantity_invalid')}`)
}
}
return { wallet: wallet, amount: amount }
}
})

if (result.isConfirmed) {
startLoading()
await transfer(daiContract, result.value.wallet, result.value.amount)
emitSuccess(t('confirmado'), 2000)
stopLoading()
}
} catch (ex) {
stopLoading()
console.error({ ex })
emitError(t('account_send_dai_error'))
}
}

const ConnectButton = () => (
<button
onClick={() => {
connectWallet()
setShowAccountInfo(false)
}}
className='account__info__connect__btn'
>
{t('account_connect')}
</button>
)

const DisconnectButton = () => (
<button
onClick={() => {
disconnectWallet()
setShowAccountInfo(false)
}}
className='account__info__disconnect__btn'
>
{t('account_disconnect')}
</button>
)

const NetworkComponent = () => (
<div className='account__info__icon__and__link'>
<div>
<p
className={`account__info__account__network ${
!isValidNetwork() ? 'account__info__invalid__network' : ''
}`}
>
{isValidNetwork() ? NETWORK.chainName : t('account_invalid_network')}
</p>
</div>
{!isValidNetwork() && (
<div className='account__info__icon__container'>
<MdOutlinePublishedWithChanges
onClick={() => {
switchOrCreateNetwork(
NETWORK.chainId,
NETWORK.chainName,
NETWORK.ChainRpcUrl,
NETWORK.chainCurrency,
NETWORK.chainExplorerUrl
)
}}
className='account__info__icon'
/>
</div>
)}
</div>
)

const WalletComponent = () => (
<div className='account__info__icon__and__link'>
<div className='account__info__link__container'>
{copiedTextVisible && (
<span className='account__info__copied__text' style={{ top: copiedTextPosition }}>
{t('account_text_copied')}
</span>
)}
<p className='account__info__account__link' onClick={handleCopy}>
{getAccountAddressText()}
</p>
</div>
<div className='account__info__icon__container'>
<HiOutlineClipboardDocument onClick={handleCopy} className='account__info__icon' />
<Link
href={`${NETWORK.chainExplorerUrl}/address/${walletAddress}`}
target='_blank'
rel='noreferrer'
className='account__info__account__link'
>
<GoLinkExternal className='account__info__icon__link' />
</Link>
</div>
</div>
)

const BalanceComponent = () => (
<div className='account__info__icon__and__link'>
<div>
<p>{`${walletBalance} ${tokenName}`}</p>
</div>
<div className='account__info__icon__container'>
<AiOutlineSend
onClick={() => {
handleSendTokenClick()
}}
className='account__info__icon'
/>
<Link
href={`${NETWORK.chainExplorerUrl}/token/${CONTRACTS.daiAddress}?a=${walletAddress}`}
target='_blank'
rel='noreferrer'
className='account__info__account__link'
>
<GoLinkExternal className='account__info__icon__link' />
</Link>
</div>
</div>
)

return (
<div className={`account__info ${showAccountInfo ? 'active' : ''}`}>
{walletAddress ? (
<React.Fragment>
<div className='account__info__data'>
<NetworkComponent />
{isValidNetwork() && (
<React.Fragment>
<hr className='account__info__separator' />
<WalletComponent />
<BalanceComponent />
</React.Fragment>
)}
</div>
<hr className='account__info__separator' />
<div className='account__info__disconnect__btn__container'>
<DisconnectButton />
</div>
</React.Fragment>
) : (
<div className='account__info__disconnect__btn__container'>
<ConnectButton />
</div>
)}
</div>
)
}

AccountInfo.propTypes = {
showAccountInfo: PropTypes.bool,
setShowAccountInfo: PropTypes.func
}

export default AccountInfo
Loading

0 comments on commit c3352a6

Please sign in to comment.