refactor: clean up code formatting and improve readability across multiple components

- Standardized the use of quotes and spacing in various files.
- Removed unnecessary line breaks and trailing spaces in components.
- Improved the structure of computed properties and methods for better clarity.
- Enhanced the consistency of prop definitions and emit events in Vue components.
- Updated the GraphQL composable to streamline error handling and data processing.
- Refactored network configuration files for better organization and readability.
- Cleaned up model files by removing redundant lines and ensuring consistent formatting.
- Adjusted router configuration for improved readability.
- Enhanced utility functions for better maintainability and clarity.
This commit is contained in:
2026-05-04 20:04:19 -03:00
committed by hueso
parent c481d9d0a5
commit d63cb8c6d3
52 changed files with 1645 additions and 1606 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +1,11 @@
import { getContract } from "./provider";
import { ChainContract } from "viem";
import {
parseEther,
type Address,
type TransactionReceipt,
} from "viem";
import { parseEther, type Address, type TransactionReceipt } from "viem";
export const addLock = async (
sellerAddress: Address,
tokenAddress: Address,
amount: number
amount: number,
): Promise<bigint> => {
const { address, abi, wallet, client, account } = await getContract();
const parsedAmount = parseEther(amount.toString());
@@ -36,7 +32,7 @@ export const addLock = async (
export const withdrawDeposit = async (
amount: string,
token: Address
token: Address,
): Promise<boolean> => {
const { address, abi, wallet, client, account } = await getContract();
@@ -49,7 +45,7 @@ export const withdrawDeposit = async (
abi,
functionName: "withdraw",
args: [token, parseEther(amount), []],
account
account,
});
const hash = await wallet.writeContract(request);
@@ -60,8 +56,8 @@ export const withdrawDeposit = async (
export const releaseLock = async (
lockID: bigint,
pixTimestamp: `0x${string}`&{lenght:34},
signature: `0x${string}`
pixTimestamp: `0x${string}` & { lenght: 34 },
signature: `0x${string}`,
): Promise<TransactionReceipt> => {
const { address, abi, wallet, client, account } = await getContract();
@@ -74,7 +70,7 @@ export const releaseLock = async (
abi,
functionName: "release",
args: [BigInt(lockID), pixTimestamp, signature],
account
account,
});
const hash = await wallet.writeContract(request);

View File

@@ -3,7 +3,7 @@ import { formatEther, toHex, stringToHex } from "viem";
import type { PublicClient, Address } from "viem";
import { Networks } from "@/config/networks";
import { getContract } from "./provider";
import { p2PixAbi } from "./abi"
import { p2PixAbi } from "./abi";
import type { ValidDeposit } from "@/model/ValidDeposit";
import type { NetworkConfig } from "@/model/NetworkEnum";
import type { UnreleasedLock } from "@/model/UnreleasedLock";
@@ -18,7 +18,7 @@ const getNetworksLiquidity = async (): Promise<void> => {
for (const network of Object.values(Networks)) {
const deposits = await getValidDeposits(
user.network.value.tokens[user.selectedToken.value].address,
network
network,
);
if (deposits) depositLists.push(deposits);
}
@@ -30,7 +30,7 @@ const getNetworksLiquidity = async (): Promise<void> => {
const getParticipantID = async (
seller: Address,
token: Address
token: Address,
): Promise<string> => {
const { address, abi, client } = await getContract();
@@ -51,7 +51,7 @@ const getParticipantID = async (
hexString
.slice(2)
.match(/.{1,2}/g)!
.map((byte: string) => parseInt(byte, 16))
.map((byte: string) => parseInt(byte, 16)),
);
// Remove null bytes from the end of the string
return new TextDecoder().decode(bytes).replace(/\0/g, "");
@@ -60,7 +60,7 @@ const getParticipantID = async (
const getValidDeposits = async (
token: Address,
network: NetworkConfig,
contractInfo?: { client: PublicClient; address: Address }
contractInfo?: { client: PublicClient; address: Address },
): Promise<ValidDeposit[]> => {
let client: PublicClient, abi;
@@ -84,7 +84,7 @@ const getValidDeposits = async (
`,
};
const depositLogs = await fetch( network.subgraphUrls[0], {
const depositLogs = await fetch(network.subgraphUrls[0], {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -104,7 +104,7 @@ const getValidDeposits = async (
acc[deposit.seller] = true;
return acc;
},
{} as Record<Address, boolean>
{} as Record<Address, boolean>,
);
if (!contractInfo) {
@@ -147,11 +147,11 @@ const getValidDeposits = async (
};
const getUnreleasedLockById = async (
lockID: bigint
lockID: bigint,
): Promise<UnreleasedLock> => {
const { address, abi, client } = await getContract();
const [ , , , amount, token, seller ] = await client.readContract({
const [, , , amount, token, seller] = await client.readContract({
address,
abi,
functionName: "mapLocks",

View File

@@ -15,14 +15,14 @@ import type { ChainContract } from "viem";
let walletClient: WalletClient | null = null;
const getPublicClient = (): PublicClient => {
const user = useUser();
const rpcUrl = (user.network.value as NetworkConfig).rpcUrls.default.http[0];
const chain = user.network.value;
const user = useUser();
const rpcUrl = (user.network.value as NetworkConfig).rpcUrls.default.http[0];
const chain = user.network.value;
return createPublicClient({
chain,
transport: http(rpcUrl),
});
return createPublicClient({
chain,
transport: http(rpcUrl),
});
};
const getWalletClient = (): WalletClient | null => {
@@ -32,7 +32,8 @@ const getWalletClient = (): WalletClient | null => {
const getContract = async (onlyRpcProvider = false) => {
const client = getPublicClient();
const user = useUser();
const address = (user.network.value.contracts?.p2pix as ChainContract).address;
const address = (user.network.value.contracts?.p2pix as ChainContract)
.address;
const abi = p2PixAbi;
const wallet = onlyRpcProvider ? null : getWalletClient();

View File

@@ -24,7 +24,8 @@ const approveTokens = async (participant: Participant): Promise<any> => {
const [account] = await walletClient.getAddresses();
// Get token address
const tokenAddress = user.network.value.tokens[user.selectedToken.value].address;
const tokenAddress =
user.network.value.tokens[user.selectedToken.value].address;
// Check if the token is already approved
const allowance = await publicClient.readContract({
@@ -34,7 +35,7 @@ const approveTokens = async (participant: Participant): Promise<any> => {
args: [account, getP2PixAddress()],
});
if ( allowance < parseEther(participant.offer.toString()) ) {
if (allowance < parseEther(participant.offer.toString())) {
// Approve tokens
const chain = user.network.value;
const hash = await walletClient.writeContract({

View File

@@ -30,12 +30,12 @@ export const updateWalletStatus = async (): Promise<void> => {
};
export const listValidDepositTransactionsByWalletAddress = async (
walletAddress: Address
walletAddress: Address,
): Promise<ValidDeposit[]> => {
const user = useUser();
const walletDeposits = await getValidDeposits(
user.network.value.tokens[user.selectedToken.value].address,
user.network.value
user.network.value,
);
if (walletDeposits) {
return walletDeposits
@@ -50,7 +50,7 @@ export const listValidDepositTransactionsByWalletAddress = async (
const getLockStatus = async (id: bigint): Promise<LockStatus> => {
const { address, abi, client } = await getContract();
const [ sortedIDs , status ] = await client.readContract({
const [sortedIDs, status] = await client.readContract({
address,
abi,
functionName: "getLocksStatus",
@@ -60,7 +60,7 @@ const getLockStatus = async (id: bigint): Promise<LockStatus> => {
};
export const listAllTransactionByWalletAddress = async (
walletAddress: Address
walletAddress: Address,
): Promise<WalletTransaction[]> => {
const user = useUser();
@@ -199,7 +199,7 @@ export const listAllTransactionByWalletAddress = async (
// get wallet's release transactions
export const listReleaseTransactionByWalletAddress = async (
walletAddress: Address
walletAddress: Address,
) => {
const user = useUser();
const network = user.network.value;
@@ -403,7 +403,7 @@ const listLockTransactionBySellerAddress = async (sellerAddress: Address) => {
};
export const checkUnreleasedLock = async (
walletAddress: Address
walletAddress: Address,
): Promise<UnreleasedLock | undefined> => {
const { address, abi, client } = await getContract();
const addedLocks = await listLockTransactionByWalletAddress(walletAddress);
@@ -412,7 +412,7 @@ export const checkUnreleasedLock = async (
const lockIds = addedLocks.map((lock: any) => lock.args.lockID);
const [ sortedIDs, status ] = await client.readContract({
const [sortedIDs, status] = await client.readContract({
address,
abi,
functionName: "getLocksStatus",
@@ -420,7 +420,7 @@ export const checkUnreleasedLock = async (
});
const unreleasedLockId = status.findIndex(
(status: LockStatus) => status == LockStatus.Active
(status: LockStatus) => status == LockStatus.Active,
);
if (unreleasedLockId !== -1)
@@ -428,7 +428,7 @@ export const checkUnreleasedLock = async (
};
export const getActiveLockAmount = async (
walletAddress: Address
walletAddress: Address,
): Promise<number> => {
const { address, abi, client } = await getContract(true);
const lockSeller = await listLockTransactionBySellerAddress(walletAddress);
@@ -437,7 +437,7 @@ export const getActiveLockAmount = async (
const lockIds = lockSeller.map((lock: any) => lock.args.lockID);
const [ sortedIDs, status ] = await client.readContract({
const [sortedIDs, status] = await client.readContract({
address,
abi,
functionName: "getLocksStatus",
@@ -450,7 +450,7 @@ export const getActiveLockAmount = async (
abi,
functionName: "mapLocks",
args: [BigInt(id)],
})
}),
);
const mapLocksResults = await client.multicall({

View File

@@ -31,11 +31,11 @@ const getWalletTransactions = async () => {
user.setLoadingWalletTransactions(true);
if (walletAddress.value) {
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
walletAddress.value
walletAddress.value,
);
const allUserTransactions = await listAllTransactionByWalletAddress(
walletAddress.value
walletAddress.value,
);
activeLockAmount.value = await getActiveLockAmount(walletAddress.value);
@@ -53,7 +53,10 @@ const getWalletTransactions = async () => {
const callWithdraw = async (amount: string) => {
if (amount) {
user.setLoadingWalletTransactions(true);
const withdraw = await withdrawDeposit(amount, user.network.value.tokens[user.selectedToken.value].address);
const withdraw = await withdrawDeposit(
amount,
user.network.value.tokens[user.selectedToken.value].address,
);
if (withdraw) {
console.log("Saque realizado!");
await getWalletTransactions();

View File

@@ -129,7 +129,6 @@ const checkReputationLimit = async (inputValue: number): Promise<void> => {
exceedsReputationLimit.value = spendLimitNumber < inputValue;
enableConfirmButton.value = !exceedsReputationLimit.value;
} catch (error) {
console.error("Error checking reputation limit:", error);
reputationLimit.value = null;
@@ -145,7 +144,7 @@ const connectAccount = async (): Promise<void> => {
const emitConfirmButton = async (): Promise<void> => {
const deposit = selectedDeposits.value?.find(
(d) => d.network === network.value
(d) => d.network === network.value,
);
if (!deposit) return;
deposit.participantID = await getParticipantID(deposit.seller, deposit.token);
@@ -185,17 +184,14 @@ const handleSelectedToken = (token: TokenEnum): void => {
// Verify if there is a valid deposit to buy
const verifyLiquidity = (): void => {
enableConfirmButton.value = false;
if (!walletAddress.value)
return;
if (!walletAddress.value) return;
const selDeposits = verifyNetworkLiquidity(
tokenValue.value,
walletAddress.value,
depositsValidList.value
depositsValidList.value,
);
selectedDeposits.value = selDeposits;
hasLiquidity.value = !!selDeposits.find(
(d) => d.network === network.value
);
hasLiquidity.value = !!selDeposits.find((d) => d.network === network.value);
enableOrDisableConfirmButton();
};
@@ -225,7 +221,7 @@ watch(walletAddress, (): void => {
const availableNetworks = computed(() => {
if (!selectedDeposits.value) return [];
return Object.values(Networks).filter((network) =>
selectedDeposits.value?.some((d) => d.network.id === network.id)
selectedDeposits.value?.some((d) => d.network.id === network.id),
);
});
@@ -364,7 +360,10 @@ const handleSubmit = async (e: Event): Promise<void> => {
<div
class="flex justify-center"
v-else-if="
!hasLiquidity && !loadingNetworkLiquidity && tokenValue > 0 && !exceedsReputationLimit
!hasLiquidity &&
!loadingNetworkLiquidity &&
tokenValue > 0 &&
!exceedsReputationLimit
"
>
<span class="text-red-500 font-normal text-sm"
@@ -375,11 +374,14 @@ const handleSubmit = async (e: Event): Promise<void> => {
<div
class="flex justify-center"
v-if="
exceedsReputationLimit && !loadingNetworkLiquidity && reputationLimit !== null
exceedsReputationLimit &&
!loadingNetworkLiquidity &&
reputationLimit !== null
"
>
<span class="text-red-500 font-normal text-sm"
>O valor excede o limite permitido pela sua reputação. Limite máximo: {{ reputationLimit }} {{ selectedToken }}</span
>O valor excede o limite permitido pela sua reputação. Limite
máximo: {{ reputationLimit }} {{ selectedToken }}</span
>
</div>
</div>

View File

@@ -54,7 +54,7 @@ const checkSolicitationStatus = async () => {
try {
const response = await getSolicitation(
solicitationData.value.numeroSolicitacao
solicitationData.value.numeroSolicitacao,
);
if (response.signature) {
@@ -82,7 +82,6 @@ const startPolling = () => {
pollingInterval.value = setInterval(checkSolicitationStatus, 10000);
};
const copyToClipboard = async () => {
if (!qrCode.value) {
return;
@@ -108,13 +107,10 @@ const copyToClipboard = async () => {
onMounted(async () => {
try {
const { tokenAddress, sellerAddress, amount } = await getUnreleasedLockById(
BigInt(props.lockID)
BigInt(props.lockID),
);
const participantId = await getParticipantID(
sellerAddress,
tokenAddress
);
const participantId = await getParticipantID(sellerAddress, tokenAddress);
const offer: Offer = {
amount,

View File

@@ -3,14 +3,14 @@ interface Props {
title: string;
value: string;
change?: string;
changeType?: 'positive' | 'negative' | 'neutral';
changeType?: "positive" | "negative" | "neutral";
icon?: string;
loading?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
changeType: 'neutral',
loading: false
changeType: "neutral",
loading: false,
});
</script>
@@ -22,7 +22,11 @@ const props = withDefaults(defineProps<Props>(), {
</div>
<div v-else class="analytics-value">{{ value }}</div>
<div class="analytics-title">{{ title }}</div>
<div v-if="change && !loading" class="analytics-change" :class="`change-${changeType}`">
<div
v-if="change && !loading"
class="analytics-change"
:class="`change-${changeType}`"
>
{{ change }}
</div>
</div>

View File

@@ -1,9 +1,9 @@
<script setup lang="ts">
import { ref } from 'vue';
import { ref } from "vue";
interface Transaction {
id: string;
type: 'deposit' | 'lock' | 'release' | 'return';
type: "deposit" | "lock" | "release" | "return";
timestamp: string;
seller?: string;
buyer?: string | null;
@@ -25,22 +25,27 @@ const copyFeedbackTimeout = ref<{ [key: string]: NodeJS.Timeout | null }>({});
const getTransactionTypeInfo = (type: string) => {
const typeMap = {
deposit: { label: 'Depósito', status: 'completed' as const },
lock: { label: 'Bloqueio', status: 'open' as const },
release: { label: 'Liberação', status: 'completed' as const },
return: { label: 'Retorno', status: 'expired' as const }
deposit: { label: "Depósito", status: "completed" as const },
lock: { label: "Bloqueio", status: "open" as const },
release: { label: "Liberação", status: "completed" as const },
return: { label: "Retorno", status: "expired" as const },
};
return typeMap[type as keyof typeof typeMap] || { label: type, status: 'pending' as const };
return (
typeMap[type as keyof typeof typeMap] || {
label: type,
status: "pending" as const,
}
);
};
const getTransactionTypeColor = (type: string) => {
const colorMap = {
deposit: 'text-emerald-600',
lock: 'text-amber-600',
release: 'text-emerald-600',
return: 'text-gray-600'
deposit: "text-emerald-600",
lock: "text-amber-600",
release: "text-emerald-600",
return: "text-gray-600",
};
return colorMap[type as keyof typeof colorMap] || 'text-gray-600';
return colorMap[type as keyof typeof colorMap] || "text-gray-600";
};
const formatAddress = (address: string) => {
@@ -74,7 +79,7 @@ const copyToClipboard = async (address: string, key: string) => {
copyFeedback.value[key] = false;
}, 2000);
} catch (error) {
console.error('Error copying to clipboard:', error);
console.error("Error copying to clipboard:", error);
}
};
</script>
@@ -85,9 +90,13 @@ const copyToClipboard = async (address: string, key: string) => {
<table class="w-full">
<thead>
<tr class="border-b border-gray-200">
<th class="text-left py-3 px-4 text-gray-700 font-medium">Horário</th>
<th class="text-left py-3 px-4 text-gray-700 font-medium">
Horário
</th>
<th class="text-left py-3 px-4 text-gray-700 font-medium">Tipo</th>
<th class="text-left py-3 px-4 text-gray-700 font-medium">Participantes</th>
<th class="text-left py-3 px-4 text-gray-700 font-medium">
Participantes
</th>
<th class="text-left py-3 px-4 text-gray-700 font-medium">Valor</th>
<th class="text-left py-3 px-4 text-gray-700 font-medium">Bloco</th>
<th class="text-left py-3 px-4 text-gray-700 font-medium">Ações</th>
@@ -100,7 +109,9 @@ const copyToClipboard = async (address: string, key: string) => {
class="border-b border-gray-100 hover:bg-gray-50 transition-colors"
>
<td class="py-4 px-4">
<div class="text-sm text-gray-600">{{ transaction.timestamp }}</div>
<div class="text-sm text-gray-600">
{{ transaction.timestamp }}
</div>
</td>
<td class="py-4 px-4">
<span
@@ -117,7 +128,12 @@ const copyToClipboard = async (address: string, key: string) => {
<div class="relative inline-block">
<span
class="text-gray-900 font-mono cursor-pointer hover:text-amber-500 transition-colors"
@click="copyToClipboard(transaction.seller, `seller-${transaction.id}`)"
@click="
copyToClipboard(
transaction.seller,
`seller-${transaction.id}`,
)
"
title="Copiar"
>
{{ formatAddress(transaction.seller) }}
@@ -137,7 +153,12 @@ const copyToClipboard = async (address: string, key: string) => {
<div class="relative inline-block">
<span
class="text-gray-900 font-mono cursor-pointer hover:text-amber-500 transition-colors"
@click="copyToClipboard(transaction.buyer, `buyer-${transaction.id}`)"
@click="
copyToClipboard(
transaction.buyer,
`buyer-${transaction.id}`,
)
"
title="Copiar"
>
{{ formatAddress(transaction.buyer) }}
@@ -202,7 +223,12 @@ const copyToClipboard = async (address: string, key: string) => {
<div class="relative inline-block">
<span
class="text-gray-900 font-mono cursor-pointer hover:text-amber-500 transition-colors"
@click="copyToClipboard(transaction.seller, `seller-${transaction.id}`)"
@click="
copyToClipboard(
transaction.seller,
`seller-${transaction.id}`,
)
"
title="Copiar"
>
{{ formatAddress(transaction.seller) }}
@@ -222,7 +248,9 @@ const copyToClipboard = async (address: string, key: string) => {
<div class="relative inline-block">
<span
class="text-gray-900 font-mono cursor-pointer hover:text-amber-500 transition-colors"
@click="copyToClipboard(transaction.buyer, `buyer-${transaction.id}`)"
@click="
copyToClipboard(transaction.buyer, `buyer-${transaction.id}`)
"
title="Copiar"
>
{{ formatAddress(transaction.buyer) }}
@@ -239,11 +267,15 @@ const copyToClipboard = async (address: string, key: string) => {
</div>
<div class="text-sm">
<span class="text-gray-600">Valor: </span>
<span class="font-semibold text-emerald-600">{{ formatAmount(transaction.amount, 18) }} BRZ</span>
</div>
<span class="font-semibold text-emerald-600"
>{{ formatAmount(transaction.amount, 18) }} BRZ</span
>
</div>
<div class="text-sm">
<span class="text-gray-600">Bloco: </span>
<span class="text-gray-900 font-mono">#{{ transaction.blockNumber }}</span>
<span class="text-gray-900 font-mono"
>#{{ transaction.blockNumber }}</span
>
</div>
</div>

View File

@@ -162,10 +162,7 @@ onMounted(() => {
</span>
</div>
<hr v-show="isCollapsibleOpen" class="pb-3" />
<div
v-show="isCollapsibleOpen"
class="flex justify-between items-center"
>
<div v-show="isCollapsibleOpen" class="flex justify-between items-center">
<h1
@click="cancelWithdraw"
class="text-black font-medium cursor-pointer hover:text-gray-600 transition-colors"
@@ -212,4 +209,3 @@ input[type="number"]::-webkit-outer-spin-button {
}
}
</style>

View File

@@ -39,7 +39,7 @@ const openEtherscanUrl = (transactionHash: string): void => {
const loadMore = (): void => {
const itemsShowing = itemsToShow.value.length;
itemsToShow.value?.push(
...props.walletTransactions.slice(itemsShowing, itemsShowing + 3)
...props.walletTransactions.slice(itemsShowing, itemsShowing + 3),
);
};

View File

@@ -29,7 +29,8 @@ const eventName = computed(() => {
});
const explorerName = computed(() => {
return Networks[(props.networkName as string).toLowerCase()].blockExplorers?.default.name;
return Networks[(props.networkName as string).toLowerCase()].blockExplorers
?.default.name;
});
const statusType = computed((): StatusType => {
@@ -142,4 +143,3 @@ const handleExplorerClick = () => {
@apply rounded-lg border-amber-300 border-2 px-3 py-2 text-gray-900 font-semibold sm:text-base text-xs hover:bg-transparent w-full text-center;
}
</style>

View File

@@ -44,7 +44,7 @@ const filteredBanks = computed(() => {
if (!bankSearchQuery.value) return [];
return bankList
.filter((bank) =>
bank.longName.toLowerCase().includes(bankSearchQuery.value.toLowerCase())
bank.longName.toLowerCase().includes(bankSearchQuery.value.toLowerCase()),
)
.slice(0, 5);
});

View File

@@ -55,12 +55,10 @@ watch(connectedChain, (newVal: any) => {
// Check if connected chain is valid, otherwise default to Sepolia
if (
!newVal ||
!Object.values(Networks).some(
(network) => network.id === Number(newVal.id)
)
!Object.values(Networks).some((network) => network.id === Number(newVal.id))
) {
console.log(
"Invalid or unsupported network detected, defaulting to Sepolia"
"Invalid or unsupported network detected, defaulting to Sepolia",
);
user.setNetwork(DEFAULT_NETWORK);
return;
@@ -69,13 +67,12 @@ watch(connectedChain, (newVal: any) => {
});
const formatWalletAddress = (): string => {
if (!walletAddress.value)
throw new Error("Wallet not connected");
if (!walletAddress.value) throw new Error("Wallet not connected");
const walletAddressLength = walletAddress.value.length;
const initialText = walletAddress.value.substring(0, 5);
const finalText = walletAddress.value.substring(
walletAddressLength - 4,
walletAddressLength
walletAddressLength,
);
return `${initialText}...${finalText}`;
};
@@ -95,7 +92,7 @@ const networkChange = async (network: NetworkConfig): Promise<void> => {
// If wallet is connected, try to change chain in wallet
if (connectedWallet.value) {
const chainId = network.id.toString(16)
const chainId = network.id.toString(16);
try {
await setChain({
chainId: `0x${chainId}`,
@@ -195,7 +192,10 @@ const handleMenuOptionClick = (option: MenuOption): void => {
<template>
<header class="z-20">
<RouterLink :to="'/'" class="default-button flex items-center md:h-auto md:py-2 h-10 py-0">
<RouterLink
:to="'/'"
class="default-button flex items-center md:h-auto md:py-2 h-10 py-0"
>
<img
alt="P2Pix logo"
class="logo hidden md:inline-block"
@@ -217,13 +217,11 @@ const handleMenuOptionClick = (option: MenuOption): void => {
<button
ref="infoMenuRef"
class="default-button hidden md:inline-block cursor-pointer"
@click="
[
(infoMenuOpenToggle = !infoMenuOpenToggle),
(menuOpenToggle = false),
(currencyMenuOpenToggle = false),
]
"
@click="[
(infoMenuOpenToggle = !infoMenuOpenToggle),
(menuOpenToggle = false),
(currencyMenuOpenToggle = false),
]"
>
<h1
class="topbar-text topbar-link"
@@ -245,7 +243,7 @@ const handleMenuOptionClick = (option: MenuOption): void => {
<div class="bg-white rounded-md z-10 -left-36 w-52">
<template
v-for="(option, index) in infoMenuOptions.filter(
(opt) => opt.showInDesktop
(opt) => opt.showInDesktop,
)"
:key="index"
>
@@ -273,7 +271,8 @@ const handleMenuOptionClick = (option: MenuOption): void => {
<div
v-if="
index <
infoMenuOptions.filter((opt) => opt.showInDesktop).length -
infoMenuOptions.filter((opt) => opt.showInDesktop)
.length -
1
"
class="w-full flex justify-center"
@@ -339,13 +338,11 @@ const handleMenuOptionClick = (option: MenuOption): void => {
ref="currencyRef"
class="top-bar-info cursor-pointer h-10 group hover:bg-gray-50 transition-all duration-500 ease-in-out"
:class="{ 'bg-gray-50': currencyMenuOpenToggle }"
@click="
[
(currencyMenuOpenToggle = !currencyMenuOpenToggle),
(menuOpenToggle = false),
(infoMenuOpenToggle = false),
]
"
@click="[
(currencyMenuOpenToggle = !currencyMenuOpenToggle),
(menuOpenToggle = false),
(infoMenuOpenToggle = false),
]"
>
<img
alt="Choosed network image"
@@ -357,9 +354,7 @@ const handleMenuOptionClick = (option: MenuOption): void => {
class="default-text hidden sm:inline-block text-gray-50 group-hover:text-gray-900 transition-all duration-500 ease-in-out whitespace-nowrap text-ellipsis overflow-hidden"
:class="{ '!text-gray-900': currencyMenuOpenToggle }"
>
{{
user.network.value.name || "Invalid Chain"
}}
{{ user.network.value.name || "Invalid Chain" }}
</span>
<div
class="transition-all duration-500 ease-in-out mt-1"
@@ -426,13 +421,11 @@ const handleMenuOptionClick = (option: MenuOption): void => {
ref="walletAddressRef"
class="top-bar-info cursor-pointer h-10 group hover:bg-gray-50 transition-all duration-500 ease-in-out"
:class="{ 'bg-gray-50': menuOpenToggle }"
@click="
[
(menuOpenToggle = !menuOpenToggle),
(currencyMenuOpenToggle = false),
(infoMenuOpenToggle = false),
]
"
@click="[
(menuOpenToggle = !menuOpenToggle),
(currencyMenuOpenToggle = false),
(infoMenuOpenToggle = false),
]"
>
<img alt="Account image" src="@/assets/account.svg?url" />
<span
@@ -463,7 +456,7 @@ const handleMenuOptionClick = (option: MenuOption): void => {
>
<template
v-for="(option, index) in walletMenuOptions.filter(
(opt) => opt.showInDesktop
(opt) => opt.showInDesktop,
)"
:key="index"
>
@@ -510,7 +503,7 @@ const handleMenuOptionClick = (option: MenuOption): void => {
<div class="bg-white rounded-md z-10 h-full">
<template
v-for="(option, index) in walletMenuOptions.filter(
(opt) => opt.showInMobile
(opt) => opt.showInMobile,
)"
:key="index"
>
@@ -653,6 +646,8 @@ a:hover {
max-height: calc(100vh - 60px);
overflow-y: auto;
border-radius: 8px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
box-shadow:
0 4px 6px -1px rgba(0, 0, 0, 0.1),
0 2px 4px -1px rgba(0, 0, 0, 0.06);
}
</style>

View File

@@ -27,7 +27,7 @@ const props = withDefaults(
minValue: 0,
disabled: false,
required: false,
}
},
);
const emit = defineEmits<{
@@ -106,11 +106,14 @@ const handleTokenChange = (token: TokenEnum) => {
emit("update:selectedToken", token);
};
watch(() => props.modelValue, (newVal) => {
if (newVal !== Number(inputValue.value)) {
inputValue.value = String(newVal || "");
}
});
watch(
() => props.modelValue,
(newVal) => {
if (newVal !== Number(inputValue.value)) {
inputValue.value = String(newVal || "");
}
},
);
</script>
<template>
@@ -153,11 +156,7 @@ watch(() => props.modelValue, (newVal) => {
<slot name="extra-info"></slot>
</div>
<ErrorMessage
v-if="errorMessage"
:message="errorMessage"
type="error"
/>
<ErrorMessage v-if="errorMessage" :message="errorMessage" type="error" />
</div>
</template>
@@ -205,4 +204,3 @@ watch(() => props.modelValue, (newVal) => {
@apply text-gray-500 font-normal text-sm;
}
</style>

View File

@@ -16,7 +16,7 @@ const props = withDefaults(
{
disabled: false,
placeholder: "Busque e selecione seu banco",
}
},
);
const emit = defineEmits<{
@@ -134,4 +134,3 @@ const selectBank = (bank: Bank) => {
@apply opacity-0 -translate-y-2;
}
</style>

View File

@@ -20,7 +20,7 @@ const props = withDefaults(
iconPosition: "left",
fullWidth: true,
loading: false,
}
},
);
const emit = defineEmits(["buttonClicked"]);

View File

@@ -3,6 +3,8 @@ import { ref, computed } from "vue";
import { onClickOutside } from "@vueuse/core";
import ChevronDown from "@/assets/chevronDown.svg";
defineOptions({ name: "UiDropdown" });
export interface DropdownItem<T = any> {
value: T;
label: string;
@@ -26,7 +28,7 @@ const props = withDefaults(
disabled: false,
size: "md",
showIcon: true,
}
},
);
const emit = defineEmits<{
@@ -48,9 +50,7 @@ const filteredItems = computed(() => {
}
const query = searchQuery.value.toLowerCase();
return props.items.filter((item) =>
item.label.toLowerCase().includes(query)
);
return props.items.filter((item) => item.label.toLowerCase().includes(query));
});
const toggleDropdown = () => {
@@ -97,10 +97,7 @@ onClickOutside(dropdownRef, () => {
<span class="selected-text">
{{ selectedItem?.label || placeholder }}
</span>
<ChevronDown
class="chevron"
:class="{ rotated: isOpen }"
/>
<ChevronDown class="chevron" :class="{ rotated: isOpen }" />
</button>
<transition name="dropdown-fade">
@@ -245,4 +242,3 @@ onClickOutside(dropdownRef, () => {
@apply opacity-0 -translate-y-2;
}
</style>

View File

@@ -12,7 +12,7 @@ const props = withDefaults(
type: "error",
centered: true,
icon: false,
}
},
);
const colorClasses = {
@@ -52,4 +52,3 @@ const colorClasses = {
@apply leading-tight;
}
</style>

View File

@@ -11,7 +11,7 @@ const props = withDefaults(
padding: "md",
fullWidth: true,
noBorder: false,
}
},
);
</script>
@@ -52,4 +52,3 @@ const props = withDefaults(
@apply px-12 py-8;
}
</style>

View File

@@ -19,7 +19,7 @@ const props = withDefaults(
iconPosition: "left",
disabled: false,
fullWidth: false,
}
},
);
const emit = defineEmits<{
@@ -144,4 +144,3 @@ const handleClick = () => {
@apply flex-shrink-0;
}
</style>

View File

@@ -13,7 +13,7 @@ const props = withDefaults(
placement: "right",
iconSrc: "",
showOnHover: true,
}
},
);
const showTooltip = ref<boolean>(false);
@@ -24,7 +24,12 @@ const floatingArrow = ref(null);
onMounted(() => {
useFloating(reference, floating, {
placement: props.placement,
middleware: [offset(10), flip(), shift(), arrow({ element: floatingArrow })],
middleware: [
offset(10),
flip(),
shift(),
arrow({ element: floatingArrow }),
],
});
});
@@ -88,4 +93,3 @@ const toggleTooltip = () => {
}
}
</style>

View File

@@ -13,7 +13,7 @@ const props = withDefaults(
size: "md",
centered: true,
inline: false,
}
},
);
const sizeMap = {
@@ -24,12 +24,7 @@ const sizeMap = {
</script>
<template>
<div
:class="[
'loading-state',
{ centered: centered, inline: inline },
]"
>
<div :class="['loading-state', { centered: centered, inline: inline }]">
<span v-if="message" :class="['loading-message', sizeMap[size].text]">
{{ message }}
</span>
@@ -57,4 +52,3 @@ const sizeMap = {
@apply text-gray-900 font-normal;
}
</style>

View File

@@ -12,7 +12,7 @@ const props = withDefaults(
{
size: "md",
showLabel: false,
}
},
);
const sizeMap = {
@@ -69,4 +69,3 @@ const networkData = computed(() => {
@apply text-sm font-medium text-gray-900;
}
</style>

View File

@@ -15,7 +15,7 @@ const props = withDefaults(
{
disabled: false,
size: "md",
}
},
);
const emit = defineEmits<{
@@ -47,4 +47,3 @@ const handleChange = (value: NetworkConfig) => {
@update:model-value="handleChange"
/>
</template>

View File

@@ -11,14 +11,12 @@ const props = withDefaults(
{
size: "lg",
centered: true,
}
},
);
</script>
<template>
<div
:class="['page-header', `size-${size}`, { centered: centered }]"
>
<div :class="['page-header', `size-${size}`, { centered: centered }]">
<h1 class="title text-white font-extrabold">
{{ title }}
</h1>
@@ -63,4 +61,3 @@ const props = withDefaults(
@apply sm:text-base text-sm sm:max-w-[28rem] max-w-[30rem] sm:tracking-normal tracking-wide;
}
</style>

View File

@@ -47,4 +47,3 @@ const displayText = computed(() => {
@apply text-xs sm:text-base font-medium text-gray-900 rounded-lg text-center px-2 py-1;
}
</style>

View File

@@ -23,7 +23,7 @@ const checkNetwork = () => {
const switchNetwork = async () => {
try {
if (connectedWallet.value && connectedWallet.value.provider) {
let chainId = network.value.id.toString(16);
const chainId = network.value.id.toString(16);
await connectedWallet.value.provider.request({
method: "wallet_switchEthereumChain",
params: [
@@ -66,7 +66,9 @@ watch(network, checkNetwork, { immediate: true });
<style scoped>
.slide-up-enter-active,
.slide-up-leave-active {
transition: transform 0.3s ease, opacity 0.3s ease;
transition:
transform 0.3s ease,
opacity 0.3s ease;
}
.slide-up-enter-from,

View File

@@ -13,7 +13,7 @@ const props = withDefaults(
{
disabled: false,
size: "md",
}
},
);
const emit = defineEmits<{
@@ -45,4 +45,3 @@ const handleChange = (value: TokenEnum) => {
@update:model-value="handleChange"
/>
</template>

View File

@@ -12,7 +12,7 @@ const props = withDefaults(
{
variant: "primary",
showMenu: true,
}
},
);
const emit = defineEmits<{
@@ -74,11 +74,7 @@ onClickOutside(menuRef, () => {
/>
<div v-else ref="menuRef" class="wallet-connected">
<button
type="button"
class="wallet-button"
@click="toggleMenu"
>
<button type="button" class="wallet-button" @click="toggleMenu">
<span class="wallet-address">{{ formattedAddress }}</span>
<div class="wallet-indicator"></div>
</button>
@@ -149,4 +145,3 @@ onClickOutside(menuRef, () => {
@apply opacity-0 -translate-y-2;
}
</style>

View File

@@ -1,11 +1,11 @@
import { NetworkConfig } from '@/model/NetworkEnum';
import { ref, computed, type Ref } from 'vue';
import { isTestnetEnvironment } from '@/config/networks';
import { NetworkConfig } from "@/model/NetworkEnum";
import { ref, computed, type Ref } from "vue";
import { isTestnetEnvironment } from "@/config/networks";
import { sepolia, rootstock, rootstockTestnet } from "viem/chains";
export interface Transaction {
id: string;
type: 'deposit' | 'lock' | 'release' | 'return';
type: "deposit" | "lock" | "release" | "return";
timestamp: string;
blockTimestamp: string;
seller?: string;
@@ -25,19 +25,19 @@ export interface AnalyticsData {
}
export function useGraphQL(network: Ref<NetworkConfig>) {
const searchAddress = ref('');
const selectedType = ref('all');
const searchAddress = ref("");
const selectedType = ref("all");
const loading = ref(false);
const error = ref<string | null>(null);
const analyticsLoading = ref(false);
const transactionsData = ref<Transaction[]>([]);
const analyticsData = ref<AnalyticsData>({
totalVolume: '0',
totalTransactions: '0',
totalLocks: '0',
totalDeposits: '0',
totalReleases: '0'
totalVolume: "0",
totalTransactions: "0",
totalLocks: "0",
totalDeposits: "0",
totalReleases: "0",
});
const executeQuery = async (query: string, variables: any = {}) => {
@@ -45,9 +45,9 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
try {
const response = await fetch(url, {
method: 'POST',
method: "POST",
headers: {
'Content-Type': 'application/json',
"Content-Type": "application/json",
},
body: JSON.stringify({
query,
@@ -62,12 +62,12 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
const data = await response.json();
if (data.errors) {
throw new Error(data.errors[0]?.message || 'GraphQL error');
throw new Error(data.errors[0]?.message || "GraphQL error");
}
return data.data;
} catch (err) {
console.error('GraphQL query error:', err);
console.error("GraphQL query error:", err);
throw err;
}
};
@@ -130,7 +130,8 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
const data = await executeQuery(query, { first: 50 });
transactionsData.value = processActivityData(data);
} catch (err) {
error.value = err instanceof Error ? err.message : 'Failed to fetch transactions';
error.value =
err instanceof Error ? err.message : "Failed to fetch transactions";
} finally {
loading.value = false;
}
@@ -194,7 +195,10 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
const data = await executeQuery(query, { userAddress, first: 50 });
transactionsData.value = processActivityData(data);
} catch (err) {
error.value = err instanceof Error ? err.message : 'Failed to fetch user transactions';
error.value =
err instanceof Error
? err.message
: "Failed to fetch user transactions";
} finally {
loading.value = false;
}
@@ -203,11 +207,11 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
const clearData = () => {
transactionsData.value = [];
analyticsData.value = {
totalVolume: '0',
totalTransactions: '0',
totalLocks: '0',
totalDeposits: '0',
totalReleases: '0'
totalVolume: "0",
totalTransactions: "0",
totalLocks: "0",
totalDeposits: "0",
totalReleases: "0",
};
};
@@ -242,7 +246,7 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
const data = await executeQuery(query);
analyticsData.value = processAnalyticsData(data);
} catch (err) {
console.error('Failed to fetch analytics:', err);
console.error("Failed to fetch analytics:", err);
} finally {
analyticsLoading.value = false;
}
@@ -260,12 +264,12 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
blockNumber: deposit.blockNumber,
blockTimestamp: deposit.blockTimestamp,
transactionHash: deposit.transactionHash,
type: 'deposit',
type: "deposit",
seller: deposit.seller,
buyer: undefined,
amount: deposit.amount,
token: deposit.token,
timestamp: formatTimestamp(deposit.blockTimestamp)
timestamp: formatTimestamp(deposit.blockTimestamp),
});
});
}
@@ -277,12 +281,12 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
blockNumber: withdrawal.blockNumber,
blockTimestamp: withdrawal.blockTimestamp,
transactionHash: withdrawal.transactionHash,
type: 'deposit', // Treat as deposit withdrawal
type: "deposit", // Treat as deposit withdrawal
seller: withdrawal.seller,
buyer: undefined,
amount: withdrawal.amount,
token: withdrawal.token,
timestamp: formatTimestamp(withdrawal.blockTimestamp)
timestamp: formatTimestamp(withdrawal.blockTimestamp),
});
});
}
@@ -294,12 +298,12 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
blockNumber: lock.blockNumber,
blockTimestamp: lock.blockTimestamp,
transactionHash: lock.transactionHash,
type: 'lock',
type: "lock",
seller: lock.seller,
buyer: lock.buyer,
amount: lock.amount,
token: lock.token,
timestamp: formatTimestamp(lock.blockTimestamp)
timestamp: formatTimestamp(lock.blockTimestamp),
});
});
}
@@ -311,12 +315,12 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
blockNumber: release.blockNumber,
blockTimestamp: release.blockTimestamp,
transactionHash: release.transactionHash,
type: 'release',
type: "release",
seller: undefined, // Release doesn't have seller info
buyer: release.buyer,
amount: release.amount,
token: 'BRZ', // Default token
timestamp: formatTimestamp(release.blockTimestamp)
token: "BRZ", // Default token
timestamp: formatTimestamp(release.blockTimestamp),
});
});
}
@@ -328,24 +332,26 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
blockNumber: returnTx.blockNumber,
blockTimestamp: returnTx.blockTimestamp,
transactionHash: returnTx.transactionHash,
type: 'return',
type: "return",
seller: undefined, // Return doesn't have seller info
buyer: returnTx.buyer,
amount: '0', // Return doesn't have amount
token: 'BRZ', // Default token
timestamp: formatTimestamp(returnTx.blockTimestamp)
amount: "0", // Return doesn't have amount
token: "BRZ", // Default token
timestamp: formatTimestamp(returnTx.blockTimestamp),
});
});
}
return activities.sort((a, b) => parseInt(b.blockTimestamp) - parseInt(a.blockTimestamp));
return activities.sort(
(a, b) => parseInt(b.blockTimestamp) - parseInt(a.blockTimestamp),
);
};
const formatTimestamp = (timestamp: string): string => {
const now = Date.now() / 1000;
const diff = now - parseInt(timestamp);
if (diff < 60) return 'Just now';
if (diff < 60) return "Just now";
if (diff < 3600) return `${Math.floor(diff / 60)} minutes ago`;
if (diff < 86400) return `${Math.floor(diff / 3600)} hours ago`;
return `${Math.floor(diff / 86400)} days ago`;
@@ -353,7 +359,8 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
const formatAmount = (amount: string): string => {
const num = parseFloat(amount);
if (num >= 1000000000000000) return `${(num / 1000000000000000).toFixed(1)}Q`;
if (num >= 1000000000000000)
return `${(num / 1000000000000000).toFixed(1)}Q`;
if (num >= 1000000000000) return `${(num / 1000000000000).toFixed(1)}T`;
if (num >= 1000000000) return `${(num / 1000000000).toFixed(1)}B`;
if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`;
@@ -365,11 +372,11 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
const processAnalyticsData = (data: any): AnalyticsData => {
if (!data) {
return {
totalVolume: '0',
totalTransactions: '0',
totalLocks: '0',
totalDeposits: '0',
totalReleases: '0'
totalVolume: "0",
totalTransactions: "0",
totalLocks: "0",
totalDeposits: "0",
totalReleases: "0",
};
}
@@ -381,7 +388,7 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
if (data.depositAddeds) {
data.depositAddeds.forEach((deposit: any) => {
totalVolume += parseFloat(deposit.amount || '0');
totalVolume += parseFloat(deposit.amount || "0");
totalTransactions++;
totalDeposits++;
});
@@ -389,14 +396,14 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
if (data.depositWithdrawns) {
data.depositWithdrawns.forEach((withdrawal: any) => {
totalVolume += parseFloat(withdrawal.amount || '0');
totalVolume += parseFloat(withdrawal.amount || "0");
totalTransactions++;
});
}
if (data.lockAddeds) {
data.lockAddeds.forEach((lock: any) => {
totalVolume += parseFloat(lock.amount || '0');
totalVolume += parseFloat(lock.amount || "0");
totalTransactions++;
totalLocks++;
});
@@ -404,13 +411,12 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
if (data.lockReleaseds) {
data.lockReleaseds.forEach((release: any) => {
totalVolume += parseFloat(release.amount || '0');
totalVolume += parseFloat(release.amount || "0");
totalTransactions++;
totalReleases++;
});
}
if (data.lockReturneds) {
data.lockReturneds.forEach((returnTx: any) => {
totalTransactions++;
@@ -422,7 +428,7 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
totalTransactions: totalTransactions.toString(),
totalLocks: totalLocks.toString(),
totalDeposits: totalDeposits.toString(),
totalReleases: totalReleases.toString()
totalReleases: totalReleases.toString(),
};
return result;
@@ -431,15 +437,16 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
const filteredTransactions = computed(() => {
let filtered = transactionsData.value;
if (selectedType.value !== 'all') {
filtered = filtered.filter(tx => tx.type === selectedType.value);
if (selectedType.value !== "all") {
filtered = filtered.filter((tx) => tx.type === selectedType.value);
}
if (searchAddress.value) {
const searchLower = searchAddress.value.toLowerCase();
filtered = filtered.filter(tx =>
tx.seller?.toLowerCase().includes(searchLower) ||
tx.buyer?.toLowerCase().includes(searchLower)
filtered = filtered.filter(
(tx) =>
tx.seller?.toLowerCase().includes(searchLower) ||
tx.buyer?.toLowerCase().includes(searchLower),
);
}
@@ -457,6 +464,6 @@ export function useGraphQL(network: Ref<NetworkConfig>) {
fetchAllActivity,
fetchUserActivity,
fetchAnalytics,
clearData
clearData,
};
}

View File

@@ -1,9 +1,9 @@
import { ref } from "vue";
import type { ValidDeposit } from "@/model/ValidDeposit";
import type { Participant } from "../utils/bbPay";
import type { Address } from "viem"
import type { Address } from "viem";
import { DEFAULT_NETWORK, Networks } from "@/config/networks";
import { TokenEnum, NetworkConfig } from "@/model/NetworkEnum"
import { TokenEnum, NetworkConfig } from "@/model/NetworkEnum";
const walletAddress = ref<Address | null>(null);
const balance = ref("");
@@ -38,9 +38,9 @@ export function useUser() {
const setNetworkById = (id: string | number) => {
let chainId: number;
if (typeof id === 'string') {
if (typeof id === "string") {
// Parse hex string or number string to number
if (id.startsWith('0x')) {
if (id.startsWith("0x")) {
chainId = parseInt(id, 16);
} else {
chainId = parseInt(id, 10);
@@ -50,7 +50,7 @@ export function useUser() {
}
// Find network by chain ID
const chain = Object.values(Networks).find(n => n.id === chainId);
const chain = Object.values(Networks).find((n) => n.id === chainId);
if (chain) {
network.value = chain;
}

View File

@@ -1,42 +1,58 @@
import { mainnet, sepolia, rootstock, rootstockTestnet } from "viem/chains";
import { NetworkConfig } from "@/model/NetworkEnum"
import { NetworkConfig } from "@/model/NetworkEnum";
// TODO: import addresses from p2pix-smart-contracts deployments
export const Networks: {[key:string]: NetworkConfig} = {
mainnet: { ...mainnet,
rpcUrls: { default: { http: [import.meta.env.VITE_MAINNET_API_URL]}},
contracts: { ...mainnet.contracts,
p2pix: { address: import.meta.env.VITE_MAINNET_P2PIX_ADDRESS } },
export const Networks: { [key: string]: NetworkConfig } = {
mainnet: {
...mainnet,
rpcUrls: { default: { http: [import.meta.env.VITE_MAINNET_API_URL] } },
contracts: {
...mainnet.contracts,
p2pix: { address: import.meta.env.VITE_MAINNET_P2PIX_ADDRESS },
},
tokens: {
BRZ: { address: import.meta.env.VITE_MAINNET_TOKEN_ADDRESS } },
subgraphUrls: [import.meta.env.VITE_MAINNET_SUBGRAPH_URL]
BRZ: { address: import.meta.env.VITE_MAINNET_TOKEN_ADDRESS },
},
subgraphUrls: [import.meta.env.VITE_MAINNET_SUBGRAPH_URL],
},
rootstock: { ...rootstock,
rpcUrls: { default: { http: [import.meta.env.VITE_RSK_API_URL]}},
contracts: { ...rootstock.contracts,
p2pix: { address: import.meta.env.VITE_RSK_P2PIX_ADDRESS } },
rootstock: {
...rootstock,
rpcUrls: { default: { http: [import.meta.env.VITE_RSK_API_URL] } },
contracts: {
...rootstock.contracts,
p2pix: { address: import.meta.env.VITE_RSK_P2PIX_ADDRESS },
},
tokens: {
BRZ: { address: import.meta.env.VITE_RSK_TOKEN_ADDRESS } },
subgraphUrls: [import.meta.env.VITE_RSK_SUBGRAPH_URL]
BRZ: { address: import.meta.env.VITE_RSK_TOKEN_ADDRESS },
},
subgraphUrls: [import.meta.env.VITE_RSK_SUBGRAPH_URL],
},
};
export const NetworksTestnet: {[key:string]: NetworkConfig} = {
sepolia: { ...sepolia,
rpcUrls: { default: { http: [import.meta.env.VITE_SEPOLIA_API_URL]}},
contracts: { ...sepolia.contracts,
p2pix: { address: import.meta.env.VITE_SEPOLIA_P2PIX_ADDRESS } },
export const NetworksTestnet: { [key: string]: NetworkConfig } = {
sepolia: {
...sepolia,
rpcUrls: { default: { http: [import.meta.env.VITE_SEPOLIA_API_URL] } },
contracts: {
...sepolia.contracts,
p2pix: { address: import.meta.env.VITE_SEPOLIA_P2PIX_ADDRESS },
},
tokens: {
BRZ: { address: import.meta.env.VITE_SEPOLIA_TOKEN_ADDRESS } },
subgraphUrls: [import.meta.env.VITE_SEPOLIA_SUBGRAPH_URL]
BRZ: { address: import.meta.env.VITE_SEPOLIA_TOKEN_ADDRESS },
},
subgraphUrls: [import.meta.env.VITE_SEPOLIA_SUBGRAPH_URL],
},
rootstockTestnet: { ...rootstockTestnet,
rpcUrls: { default: { http: [import.meta.env.VITE_RSK_API_URL]}},
contracts: { ...rootstockTestnet.contracts,
p2pix: { address: import.meta.env.VITE_RSK_P2PIX_ADDRESS } },
rootstockTestnet: {
...rootstockTestnet,
rpcUrls: { default: { http: [import.meta.env.VITE_RSK_API_URL] } },
contracts: {
...rootstockTestnet.contracts,
p2pix: { address: import.meta.env.VITE_RSK_P2PIX_ADDRESS },
},
tokens: {
BRZ: { address: import.meta.env.VITE_RSK_TOKEN_ADDRESS } },
subgraphUrls: [import.meta.env.VITE_RSK_SUBGRAPH_URL]
BRZ: { address: import.meta.env.VITE_RSK_TOKEN_ADDRESS },
},
subgraphUrls: [import.meta.env.VITE_RSK_SUBGRAPH_URL],
},
};

View File

@@ -4,5 +4,3 @@ export interface AppVersion {
releaseDate: string;
description?: string;
}

View File

@@ -1,8 +1,9 @@
import type { Address } from "viem";
export enum LockStatus { // from DataTypes.sol
export enum LockStatus {
// from DataTypes.sol
Inexistent = 0, // Uninitialized Lock
Active = 1, // Valid Lock
Expired = 2, // Expired Lock
Released = 3 // Already released Lock
Active = 1, // Valid Lock
Expired = 2, // Expired Lock
Released = 3, // Already released Lock
}

View File

@@ -1,10 +1,10 @@
import type { Chain, ChainContract } from "viem";
export enum TokenEnum {
BRZ = 'BRZ',
BRZ = "BRZ",
// BRX = 'BRX'
}
export type NetworkConfig = Chain & {
tokens: Record<TokenEnum, ChainContract>,
subgraphUrls: string[]
tokens: Record<TokenEnum, ChainContract>;
subgraphUrls: string[];
};

View File

@@ -1,11 +1,11 @@
export type Pix = {
pixKey: string;
merchantCity?: string;
merchantName?: string;
value?: number;
transactionId?: string;
message?: string;
cep?: string;
currency?: number;
countryCode?: string;
pixKey: string;
merchantCity?: string;
merchantName?: string;
value?: number;
transactionId?: string;
message?: string;
cep?: string;
currency?: number;
countryCode?: string;
};

View File

@@ -1,5 +1,5 @@
import type { LockStatus } from "@/model/LockStatus"
import type { Address } from "viem"
import type { LockStatus } from "@/model/LockStatus";
import type { Address } from "viem";
export type WalletTransaction = {
token?: Address;

View File

@@ -1,4 +1,8 @@
import { createRouter, createWebHistory, createWebHashHistory } from "vue-router";
import {
createRouter,
createWebHistory,
createWebHashHistory,
} from "vue-router";
import HomeView from "@/views/HomeView.vue";
import FaqView from "@/views/FaqView.vue";
import ManageBidsView from "@/views/ManageBidsView.vue";
@@ -7,9 +11,10 @@ import ExploreView from "@/views/ExploreView.vue";
import VersionsView from "@/views/VersionsView.vue";
const router = createRouter({
history: import.meta.env.MODE === 'production' && import.meta.env.BASE_URL === './'
? createWebHashHistory()
: createWebHistory(import.meta.env.BASE_URL),
history:
import.meta.env.MODE === "production" && import.meta.env.BASE_URL === "./"
? createWebHashHistory()
: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: "/",

View File

@@ -61,9 +61,11 @@ export const createSolicitation = async (offer: Offer) => {
return response.json();
};
export const getSolicitation = async (id: bigint): Promise<{pixTimestamp: `0x${string}`, signature: `0x${string}`}> => {
export const getSolicitation = async (
id: bigint,
): Promise<{ pixTimestamp: `0x${string}`; signature: `0x${string}` }> => {
const response = await fetch(
`${import.meta.env.VITE_APP_API_URL}/release/${id}`
`${import.meta.env.VITE_APP_API_URL}/release/${id}`,
);
const obj = await response.json();

View File

@@ -2,10 +2,14 @@ import type { TokenEnum } from "@/model/NetworkEnum";
import { Networks } from "@/config/networks";
export const getNetworkImage = (networkName: string): string => {
const normalizedName = networkName.toLowerCase().replace(/[^a-z0-9]/g, '-');
return new URL(`../assets/networks/${normalizedName}.svg`, import.meta.url).href;
const normalizedName = networkName.toLowerCase().replace(/[^a-z0-9]/g, "-");
return new URL(`../assets/networks/${normalizedName}.svg`, import.meta.url)
.href;
};
export const getTokenImage = (tokenName: TokenEnum): string => {
return new URL(`../assets/tokens/${tokenName.toLowerCase()}.svg`, import.meta.url).href;
return new URL(
`../assets/tokens/${tokenName.toLowerCase()}.svg`,
import.meta.url,
).href;
};

View File

@@ -4,14 +4,14 @@ import type { Address } from "viem";
const verifyNetworkLiquidity = (
tokenValue: number,
walletAddress: Address,
validDepositList: ValidDeposit[]
validDepositList: ValidDeposit[],
): ValidDeposit[] => {
const filteredDepositList = validDepositList
.filter((element) => {
const remaining = element.remaining;
if (
tokenValue!! <= remaining &&
tokenValue!! != 0 &&
tokenValue! <= remaining &&
tokenValue! != 0 &&
element.seller !== walletAddress
) {
return true;
@@ -25,14 +25,14 @@ const verifyNetworkLiquidity = (
const uniqueNetworkDeposits = filteredDepositList.reduce(
(acc: ValidDeposit[], current) => {
const existingNetwork = acc.find(
(deposit) => deposit.network === current.network
(deposit) => deposit.network === current.network,
);
if (!existingNetwork) {
acc.push(current);
}
return acc;
},
[]
[],
);
return uniqueNetworkDeposits;
};

View File

@@ -5,13 +5,13 @@ export const appVersions: AppVersion[] = [
tag: "1.1.0",
ipfsHash: "bafybeiaffdxrxoex3qh7kirnkkufnvpafb4gmkt7mjxufnnpbrq6tmqoha",
releaseDate: "2025-11-06",
description: "Explorer and versioning features added"
description: "Explorer and versioning features added",
},
{
tag: "1.0.0",
ipfsHash: "bafybeiagfqnxnb5zdrks6dicfm7kxjdtzzzzm2ouluxgdseg2hrrotayzi",
releaseDate: "2023-01-28",
description: "Initial release"
description: "Initial release",
},
];
@@ -26,5 +26,3 @@ export function getVersionByTag(tag: string): AppVersion | null {
export function getIpfsUrl(ipfsHash: string): string {
return `https://${ipfsHash}.ipfs.dweb.link`;
}

View File

@@ -1,11 +1,11 @@
<script setup lang="ts">
import { onMounted, watch } from 'vue';
import { useUser } from '@/composables/useUser';
import { useGraphQL } from '@/composables/useGraphQL';
import FormCard from '@/components/ui/FormCard.vue';
import LoadingComponent from '@/components/ui/LoadingComponent.vue';
import AnalyticsCard from '@/components/Explorer/AnalyticsCard.vue';
import TransactionTable from '@/components/Explorer/TransactionTable.vue';
import { onMounted, watch } from "vue";
import { useUser } from "@/composables/useUser";
import { useGraphQL } from "@/composables/useGraphQL";
import FormCard from "@/components/ui/FormCard.vue";
import LoadingComponent from "@/components/ui/LoadingComponent.vue";
import AnalyticsCard from "@/components/Explorer/AnalyticsCard.vue";
import TransactionTable from "@/components/Explorer/TransactionTable.vue";
const user = useUser();
const { network } = user;
@@ -21,15 +21,15 @@ const {
fetchAllActivity,
fetchUserActivity,
fetchAnalytics,
clearData
clearData,
} = useGraphQL(network);
const transactionTypes = [
{ key: 'all', label: 'Todas' },
{ key: 'deposit', label: 'Depósitos' },
{ key: 'lock', label: 'Bloqueios' },
{ key: 'release', label: 'Liberações' },
{ key: 'return', label: 'Retornos' }
{ key: "all", label: "Todas" },
{ key: "deposit", label: "Depósitos" },
{ key: "lock", label: "Bloqueios" },
{ key: "release", label: "Liberações" },
{ key: "return", label: "Retornos" },
];
const handleTypeFilter = (type: string) => {
@@ -44,26 +44,23 @@ watch(searchAddress, async (newAddress) => {
}
});
watch(network, async () => {
clearData();
await Promise.all([
fetchAllActivity(),
fetchAnalytics()
]);
}, { deep: true });
watch(
network,
async () => {
clearData();
await Promise.all([fetchAllActivity(), fetchAnalytics()]);
},
{ deep: true },
);
onMounted(async () => {
await Promise.all([
fetchAllActivity(),
fetchAnalytics()
]);
await Promise.all([fetchAllActivity(), fetchAnalytics()]);
});
</script>
<template>
<div class="min-h-screen">
<div class="container mx-auto px-4 py-8">
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4 mb-8">
<AnalyticsCard
title="Volume Total"
@@ -119,7 +116,7 @@ onMounted(async () => {
'px-4 py-2 rounded-lg text-sm font-medium transition-colors',
selectedType === type.key
? 'bg-amber-400 text-gray-900'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200',
]"
>
{{ type.label }}
@@ -143,8 +140,12 @@ onMounted(async () => {
<!-- Transactions Table -->
<FormCard v-else padding="lg">
<div class="mb-6">
<h2 class="text-xl font-semibold text-gray-900 mb-2">Transações Recentes</h2>
<p class="text-gray-600">{{ transactions.length }} transações encontradas</p>
<h2 class="text-xl font-semibold text-gray-900 mb-2">
Transações Recentes
</h2>
<p class="text-gray-600">
{{ transactions.length }} transações encontradas
</p>
</div>
<TransactionTable

View File

@@ -22,7 +22,7 @@ const openItem = (index: number) => {
});
faq.value[selectedSection.value].items[index].content = marked(
faq.value[selectedSection.value].items[index].content
faq.value[selectedSection.value].items[index].content,
);
};
</script>
@@ -30,10 +30,12 @@ const openItem = (index: number) => {
<template>
<div class="page">
<div class="text-container">
<span class="text font-extrabold sm:text-5xl text-3xl sm:max-w-[50rem] max-w-[90%]"
<span
class="text font-extrabold sm:text-5xl text-3xl sm:max-w-[50rem] max-w-[90%]"
>Perguntas Frequentes
</span>
<span class="text font-medium sm:text-base text-sm sm:max-w-[40rem] max-w-[90%]"
<span
class="text font-medium sm:text-base text-sm sm:max-w-[40rem] max-w-[90%]"
>Não conseguiu uma resposta para sua dúvida? Acesse a comunidade do
Discord para falar diretamente conosco.</span
>

View File

@@ -37,7 +37,7 @@ const paramLockID = window.history.state?.lockID;
const confirmBuyClick = async (
selectedDeposit: ValidDeposit,
tokenValue: number
tokenValue: number,
) => {
participantID.value = selectedDeposit.participantID;
tokenAmount.value = tokenValue;
@@ -60,22 +60,25 @@ const confirmBuyClick = async (
};
const releaseTransaction = async (params: {
pixTimestamp: `0x${string}`&{lenght:34},
signature: `0x${string}`,
pixTimestamp: `0x${string}` & { lenght: 34 };
signature: `0x${string}`;
}) => {
flowStep.value = Step.List;
showBuyAlert.value = true;
loadingRelease.value = true;
const release = await releaseLock(BigInt(lockID.value), params.pixTimestamp, params.signature);
const release = await releaseLock(
BigInt(lockID.value),
params.pixTimestamp,
params.signature,
);
await updateWalletStatus();
loadingRelease.value = false;
};
const checkForUnreleasedLocks = async (): Promise<void> => {
if (!walletAddress.value)
throw new Error("Wallet not connected");
if (!walletAddress.value) throw new Error("Wallet not connected");
const lock = await checkUnreleasedLock(walletAddress.value);
if (lock) {
lockID.value = String(lock.lockID);

View File

@@ -30,8 +30,9 @@ const callWithdraw = async (amount: string) => {
let withdraw;
try {
withdraw = await withdrawDeposit(
amount,
network.value.tokens[selectedToken.value].address);
amount,
network.value.tokens[selectedToken.value].address,
);
} catch {
loadingWithdraw.value = false;
}
@@ -51,11 +52,11 @@ const getWalletTransactions = async () => {
user.setLoadingWalletTransactions(true);
if (walletAddress.value) {
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
walletAddress.value
walletAddress.value,
);
const allUserTransactions = await listAllTransactionByWalletAddress(
walletAddress.value
walletAddress.value,
);
activeLockAmount.value = await getActiveLockAmount(walletAddress.value);

View File

@@ -8,8 +8,9 @@ const latestVersion = ref<AppVersion | null>(null);
const currentVersion = __APP_VERSION__;
onMounted(() => {
versions.value = [...appVersions].sort((a, b) =>
new Date(b.releaseDate).getTime() - new Date(a.releaseDate).getTime()
versions.value = [...appVersions].sort(
(a, b) =>
new Date(b.releaseDate).getTime() - new Date(a.releaseDate).getTime(),
);
latestVersion.value = getLatestVersion();
});
@@ -36,28 +37,22 @@ const formatDate = (dateString: string): string => {
Versões do P2Pix
</span>
<span class="text font-medium text-base max-w-[40rem]">
Visualize todas as versões do P2Pix. Cada versão está
disponível no IPFS para acesso permanente e descentralizado.
Visualize todas as versões do P2Pix. Cada versão está disponível no IPFS
para acesso permanente e descentralizado.
</span>
<div v-if="currentVersion" class="mt-4">
<span class="text-gray-400 text-sm">
Versão atual: <span class="font-semibold text-white">{{ currentVersion }}</span>
Versão atual:
<span class="font-semibold text-white">{{ currentVersion }}</span>
</span>
</div>
</div>
<div class="versions-container">
<div
v-for="version in versions"
:key="version.tag"
class="version-card"
>
<div v-for="version in versions" :key="version.tag" class="version-card">
<div class="version-header">
<h3 class="version-tag">{{ version.tag }}</h3>
<span
v-if="version.tag === currentVersion"
class="current-badge"
>
<span v-if="version.tag === currentVersion" class="current-badge">
Atual
</span>
</div>
@@ -153,5 +148,3 @@ const formatDate = (dateString: string): string => {
@apply text-center py-12;
}
</style>

View File

@@ -8,7 +8,10 @@ import svgLoader from "vite-svg-loader";
function getGitTag(): string {
try {
const tags = execSync("git tag --sort=-version:refname").toString().trim().split("\n");
const tags = execSync("git tag --sort=-version:refname")
.toString()
.trim()
.split("\n");
return tags.length > 0 ? tags[0] : "unknown";
} catch (fallbackError) {
return "";
@@ -40,7 +43,7 @@ export default defineConfig({
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
"viem/errors": fileURLToPath(
new URL("./node_modules/viem/errors", import.meta.url)
new URL("./node_modules/viem/errors", import.meta.url),
),
},
},

View File

@@ -1,11 +1,12 @@
import { defineConfig } from '@wagmi/cli'
import { hardhat } from '@wagmi/cli/plugins'
import { defineConfig } from "@wagmi/cli";
import { hardhat } from "@wagmi/cli/plugins";
export default defineConfig({
out: 'src/blockchain/abi.ts',
out: "src/blockchain/abi.ts",
contracts: [],
plugins: [
hardhat({
project: 'p2pix-smart-contracts',
}),],
})
project: "p2pix-smart-contracts",
}),
],
});