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

merge develop into main #143

Merged
merged 21 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
1299477
[feat] :truck: move transfer-all endpoint to user root endpoint (#65)
dappsar Oct 31, 2024
5510169
[feat] :necktie: add form business logic (#65)
dappsar Oct 31, 2024
c3ed6dd
[feat] :globe_with_meridians: add i18n text (#65)
dappsar Oct 31, 2024
6a58bf5
[feat] :alien: update backend params to transfer all (#65)
dappsar Oct 31, 2024
19f50dd
[feat] :building_construction: upgrade control to allow wallet type (…
dappsar Oct 31, 2024
2ba303b
[feat] :sparkles: update user-account path
dappsar Oct 31, 2024
9f507a1
Merge pull request #137 from P4-Games/feature/transfer-all
dappsar Oct 31, 2024
2e3663e
[feat] added share page for NFTs
TomasDmArg Nov 1, 2024
d75a4fb
[feat] :label: add new fields in balance type (#140)
dappsar Nov 1, 2024
4329c92
[feat] :label: add default balances response (#140)
dappsar Nov 1, 2024
54c554c
[feat] :alien: update balance-api to new backend structure (#140)
dappsar Nov 1, 2024
256dc9c
[feat] :alien: add call to backend endpoint to transfer-all (#65)
dappsar Nov 1, 2024
7c70014
[feat] :alien: avoid transfer-all backend error (#65)
dappsar Nov 1, 2024
b5d9b8b
Merge pull request #141 from P4-Games/feature/20241101
dappsar Nov 1, 2024
7543341
[fix] :bug: fix backend balance responde (#140)
dappsar Nov 1, 2024
1d0d512
Merge pull request #142 from P4-Games/fix/balance-response-data
dappsar Nov 1, 2024
423b7cc
[feat] :sparkles: added msg after copy clipboard (#139)
dappsar Nov 1, 2024
50b136f
[feat] :sparkles: improve close button (#139)
dappsar Nov 1, 2024
45b020c
[feat] :globe_with_meridians: update i18n for nfts-share (#139)
dappsar Nov 1, 2024
0792e87
[feat] :lipstick: prettier & linter (#139)
dappsar Nov 1, 2024
c4102c3
Merge pull request #138 from P4-Games/feat/share-nfts
dappsar Nov 1, 2024
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: 19 additions & 14 deletions src/app/api/_data/blk-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
API3_ENABLED,
defaultBalance,
BACKEND_API_URL,
defaultBalances,
tokensByNetwork,
BACKEND_API_TOKEN,
nodeProviderUrlSepolia
Expand All @@ -17,19 +18,17 @@ import TokenPriceFeedsAbi from './_abis/TokenPriceFeedsAbi.json'

// ---------------------------------------------------------------------------------------------

export async function transferAll(walletTo: string): Promise<boolean> {
export async function transferAll(channelUserId: string, walletTo: string): Promise<boolean> {
try {
// TODO:
// const data = { wallet: walletTo }
// const response = await axios.post(`${BACKEND_API_URL}/transferall`, data)
const data = { channel_user_id: channelUserId, dst_address: walletTo }
await axios.post(`${BACKEND_API_URL}/withdraw_funds`, data)
return true
} catch (error) {
console.error('Error transfering all funds:', error)
throw error
return true // avoid transfer-all error
}
}
export async function getBalancesWithTotalsFromBackend(walletAddress: string): Promise<IBalances> {
let balances: IBalances
const cacheKey = `getBalancesWithTotalsFromBackend.${walletAddress}`
const fromCache = cache.get(cacheKey) as IBalances

Expand All @@ -38,36 +37,42 @@ export async function getBalancesWithTotalsFromBackend(walletAddress: string): P
return fromCache
}

let responseBalances: IBalances
try {
const response = await axios.get(`${BACKEND_API_URL}/balance/${walletAddress}`, {
headers: {
Authorization: `Bearer ${BACKEND_API_TOKEN}`
}
})
const data = response.data as IBalances
responseBalances = response.data.data
} catch (error) {
console.error('Error fetching balance from backend:', error)
responseBalances = defaultBalances
}

// Convert keys to lowercase
const normalizedTotals = Object.keys(data.totals).reduce(
// Convert keys to lowercase
try {
const normalizedTotals = Object.keys(responseBalances.totals).reduce(
(acc, key) => {
const lowerKey = key.toLowerCase() as CurrencyKey
if (['usd', 'ars', 'brl', 'uyu'].includes(lowerKey)) {
acc[lowerKey] = data.totals[key as CurrencyKey]
acc[lowerKey] = responseBalances.totals[key as CurrencyKey]
}
return acc
},
{} as Record<CurrencyKey, number>
)

balances = {
...data,
const balances: IBalances = {
...responseBalances,
totals: normalizedTotals
}

cache.set(cacheKey, balances, 60) // 1 minute
return balances
} catch (error) {
console.error('Error fetching balance from backend:', error)
throw error
console.error('Error formatting balances totals:', error)
return defaultBalances
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/app/api/_hooks/api-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,12 @@ export const endpoints = {
id: (id: string) => getFullUIEndpoint(`user/${id}`),
update: (id: string) => getFullUIEndpoint(`user/${id}`),
code: (id: string) => getFullUIEndpoint(`user/${id}/code`),
updateEmail: (id: string) => getFullUIEndpoint(`user/${id}/email`)
updateEmail: (id: string) => getFullUIEndpoint(`user/${id}/email`),
transferAll: (id: string) => getFullUIEndpoint(`user/${id}/transfer-all`)
},
wallet: {
balance: (id: string) => getFullUIEndpoint(`wallet/${id}/balance`),
transactions: (id: string) => getFullUIEndpoint(`wallet/${id}/transactions`),
transferAll: (id: string) => getFullUIEndpoint(`wallet/${id}/transferAll`),
nfts: {
root: (id: string) => getFullUIEndpoint(`wallet/${id}/nfts`),
id: (walletId: string, nftId: string) =>
Expand Down
6 changes: 4 additions & 2 deletions src/app/api/_hooks/use-wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ export function useGetWalletNft(walletId: string, nftId: string) {

// ----------------------------------------------------------------------

export async function transferAll(walletId: string, data: { walletTo: string }) {
const res = await post(endpoints.dashboard.wallet.transferAll(walletId), data, {})
export async function transferAll(userId: string, data: { walletTo: string }) {
console.log('trasnfer all', userId, data)
const res = await post(endpoints.dashboard.user.transferAll(userId), data, {})
console.log('x', res)
return res
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { NextRequest, NextResponse } from 'next/server'

import { transferAll } from 'src/app/api/_data/blk-service'
import { getUserById } from 'src/app/api/_data/data-service'

import { IAccount } from 'src/types/account'

// ----------------------------------------------------------------------

Expand Down Expand Up @@ -42,7 +45,18 @@ export async function POST(req: NextRequest, { params }: { params: IParams }) {
)
}

const result: boolean = await transferAll(walletTo)
const user: IAccount | undefined = await getUserById(id)
if (!user) {
return new NextResponse(
JSON.stringify({ code: 'USER_NOT_FOUND', error: 'user not found with that id' }),
{
status: 404,
headers: { 'Content-Type': 'application/json' }
}
)
}

const result: boolean = await transferAll(user.id, walletTo)
if (!result) {
return new NextResponse(
JSON.stringify({
Expand Down
13 changes: 13 additions & 0 deletions src/app/nfts/share/[id]/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use client'

import MainLayout from 'src/layouts/main'

// ----------------------------------------------------------------------

type Props = {
children: React.ReactNode
}

export default function Layout({ children }: Props) {
return <MainLayout>{children}</MainLayout>
}
11 changes: 11 additions & 0 deletions src/app/nfts/share/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import NftShareView from 'src/sections/nfts/view/nft-share-view'

// ----------------------------------------------------------------------

export const metadata = {
title: 'NFT Share'
}

export default function NftMintPage({ params }: { params: { id: string } }) {
return <NftShareView nftId={params.id} />
}
7 changes: 7 additions & 0 deletions src/app/nfts/share/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { redirect } from 'next/navigation'

// ----------------------------------------------------------------------

export default function Share() {
return redirect('/')
}
8 changes: 6 additions & 2 deletions src/components/hook-form/rhf-text-field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,15 @@ export default function RHFTextField({ name, helperText, type, ...other }: Props
<TextField
{...field}
fullWidth
type={type}
type={type === 'wallet' ? 'text' : type}
value={type === 'number' && field.value === 0 ? '' : field.value}
onChange={(event) => {
let inputValue = event.target.value
if (type === 'number') {
field.onChange(Number(event.target.value))
field.onChange(Number(inputValue))
} else if (type === 'wallet') {
inputValue = inputValue.replace(/[^a-zA-Z0-9]/g, '')
field.onChange(inputValue.startsWith('0x') ? inputValue : `0x${inputValue}`)
} else {
field.onChange(event.target.value)
}
Expand Down
16 changes: 15 additions & 1 deletion src/config-global.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Network } from './types/networks'
import { IBalance, IBalances } from './types/wallet'

// ----------------------------------------------------------------------

Expand Down Expand Up @@ -56,7 +57,7 @@ export const STORAGE_KEY_SETTINGS = 'settings'
export const CONTACT_EMAIL = 'contacto@chatterpay.com.ar'
export const GET_BALANCES_FROM_BACKEND = true

export const defaultBalance = {
export const defaultBalance: IBalance = {
network: '',
token: '',
balance: 0,
Expand All @@ -68,6 +69,19 @@ export const defaultBalance = {
}
}

export const defaultBalances: IBalances = {
balances: [defaultBalance],
totals: {
usd: 0,
ars: 0,
brl: 0,
uyu: 0
},
certificates: [],
wallet: '',
message: ''
}

export const tokensByNetwork: { [networkKey: string]: Network } = {
scroll_testnet: {
config: {
Expand Down
2 changes: 1 addition & 1 deletion src/layouts/common/account-popover.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export default function AccountPopover() {
const OPTIONS = [
{
label: t('menu.account'),
linkTo: paths.dashboard.user.account
linkTo: paths.dashboard.user.root
}
]

Expand Down
2 changes: 1 addition & 1 deletion src/layouts/dashboard/config-navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export function useNavData() {
title: t('menu.user'),
path: paths.dashboard.user.root,
icon: ICONS.user,
children: [{ title: t('menu.account'), path: paths.dashboard.user.account }]
children: [{ title: t('menu.account'), path: paths.dashboard.user.root }]
}
]
}
Expand Down
24 changes: 20 additions & 4 deletions src/locales/langs/br.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"required": "obrigatório",
"must-be-numeric": "Deve ser numérico",
"must-be-max": "Deve ter no máximo {MAX_DIGITS} dígitos",
"must-be-valid-email": "O email deve ser um endereço de email válido",
"must-be-valid-email": "O email deve ser um endereço de email válido",
"must-be-min": "Deve ter no mínimo {MIN_CHARS} caracteres",
"nodata": "Sem Dados",
"save": "Salvar Alterações",
Expand All @@ -33,7 +33,8 @@
"user": "Usuário",
"account": "Conta",
"logout": "Sair",
"email": "Alterar Email"
"email": "Alterar Email",
"transfer-all": "Transfer Tudo"
},
"terms": {
"title": "Termos e Condições",
Expand Down Expand Up @@ -249,7 +250,7 @@
"answer": "Digite seu número de telefone registrado. Um código de 6 dígitos será enviado para o seu telefone por segurança; depois de inseri-lo, você poderá acessar o site."
}
}
},
},
"get-started": {
"title": "Comece com",
"description": "Todo o poder do Web3 sem complicações.",
Expand Down Expand Up @@ -290,6 +291,7 @@
"title": "Saldo Estimado",
"deposit": "Depositar",
"send": "Enviar",
"transfer-all": "Transferir Tudo",
"wapp-msg": "Olá!"
},
"transactions": {
Expand All @@ -305,6 +307,16 @@
"receive-from": "Recebido dinheiro de",
"sent-to": "Enviado dinheiro para"
},
"transfer-all": {
"info": "Indica um endereço de carteira para onde serão enviados todos os fundos que você possui no Chatterpay.",
"msgs": {
"ok": "Os fundos foram transferidos. Você os verá na carteira indicada em breve.",
"error": "Houve um erro ao tentar transferir os fundos."
},
"actions": {
"transfer": "Transferir Tudo"
}
},
"nfts": {
"view-trx": "Ver detalhes da transação",
"mint": "Ei, dá uma olhada no meu NFT:",
Expand All @@ -323,6 +335,10 @@
"cta-msg": "Reivindique seu certificado na blockchain gratuitamente!",
"opensea-alt": "logo open sea",
"wapp-msg": "Gostaria de mintar o NFT"
},
"share": {
"cta": "Compartilhar certificado",
"clipboard": "Link copiado!"
}
},
"account": {
Expand All @@ -340,4 +356,4 @@
"code-bot": "Insira este código {2FA_CODE} para validar a alteração do seu e-mail no Chatterpay. É muito importante que você não compartilhe esta informação com ninguém. Se você não solicitou o código, desconsidere esta mensagem e entre em contato conosco para que possamos ajudá-lo!"
}
}
}
}
26 changes: 21 additions & 5 deletions src/locales/langs/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@
"user": "User",
"account": "Account",
"logout": "Logout",
"email": "Email Change"
"email": "Email Change",
"transfer-all": "Transfer All"
},
"home": {
"header": {
"sign-up": "Create your account",
"sign-in": "Sign in"
"sign-up": "Create your account",
"sign-in": "Sign in"
},
"help": {
"need-help": "Need help?"
Expand Down Expand Up @@ -290,13 +291,14 @@
"title": "Estimated Balance",
"deposit": "Deposit",
"send": "Send",
"transfer-all": "Transfer All",
"wapp-msg": "Hi!"
},
},
"transactions": {
"title": "Recent Transactions",
"table-transaction": "Transaction",
"table-amount": "Amount",
"table-date": "Date",
"table-date": "Date",
"table-status": "Status",
"table-view-all": "View All",
"table-download": "Download",
Expand All @@ -305,6 +307,16 @@
"receive-from": "Received money from",
"sent-to": "Sent money to"
},
"transfer-all": {
"info": "Indicates a wallet address where all funds in Chatterpay will be sent.",
"msgs": {
"ok": "The funds were transferred. You will see them in the indicated wallet shortly.",
"error": "There was an error attempting to transfer the funds."
},
"actions": {
"transfer": "Transfer All"
}
},
"nfts": {
"view-trx": "View Transacton Details",
"mint": "Hey, check out my NFT:",
Expand All @@ -323,6 +335,10 @@
"cta-msg": "Claim your certificate on the blockchain for free!",
"opensea-alt": "open sea logo",
"wapp-msg": "I would like to mint the NFT"
},
"share": {
"cta": "Share",
"clipboard": "Link copied!"
}
},
"account": {
Expand Down
Loading