Skip to content

Commit

Permalink
prettier on FE
Browse files Browse the repository at this point in the history
  • Loading branch information
0age committed Dec 9, 2024
1 parent 14dffec commit 73aa616
Show file tree
Hide file tree
Showing 11 changed files with 310 additions and 227 deletions.
7 changes: 5 additions & 2 deletions frontend/src/components/BalanceDisplay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ const formatResetPeriod = (seconds: number): string => {
return `${Math.floor(seconds / 86400)} days`;
};

export function BalanceDisplay({ sessionToken }: BalanceDisplayProps): JSX.Element | null {
export function BalanceDisplay({
sessionToken,
}: BalanceDisplayProps): JSX.Element | null {
const { isConnected } = useAccount();
const { balances, error, isLoading } = useBalances();
const { data: resourceLocksData, isLoading: resourceLocksLoading } =
Expand Down Expand Up @@ -296,7 +298,8 @@ export function BalanceDisplay({ sessionToken }: BalanceDisplayProps): JSX.Eleme
decimals={resourceLock.resourceLock.token.decimals}
tokenName={{
resourceLockName: resourceLock.resourceLock.token.name,
resourceLockSymbol: resourceLock.resourceLock.token.symbol,
resourceLockSymbol:
resourceLock.resourceLock.token.symbol,
tokenName: balance.token?.name || '',
}}
tokenSymbol={balance.token?.symbol || ''}
Expand Down
22 changes: 12 additions & 10 deletions frontend/src/components/SessionManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ interface SessionManagerProps {
onSessionUpdate: (token: string | null) => void;
}

export function SessionManager({ sessionToken, onSessionUpdate }: SessionManagerProps) {
export function SessionManager({
sessionToken,
onSessionUpdate,
}: SessionManagerProps) {
const { address, isConnected } = useAccount();
const { signMessageAsync } = useSignMessage();
const chainId = useChainId();
Expand All @@ -26,9 +29,9 @@ export function SessionManager({ sessionToken, onSessionUpdate }: SessionManager
if (!payloadResponse.ok) {
throw new Error('Failed to get session payload');
}

const { session } = await payloadResponse.json();

// Format the message according to EIP-4361
const message = [
`${session.domain} wants you to sign in with your Ethereum account:`,
Expand Down Expand Up @@ -63,7 +66,7 @@ export function SessionManager({ sessionToken, onSessionUpdate }: SessionManager
},
}),
});

if (response.ok) {
const data = await response.json();
storeSession(data.session.id);
Expand All @@ -86,8 +89,8 @@ export function SessionManager({ sessionToken, onSessionUpdate }: SessionManager
const response = await fetch('/session', {
method: 'DELETE',
headers: {
'x-session-id': sessionToken
}
'x-session-id': sessionToken,
},
});

if (response.ok) {
Expand All @@ -105,8 +108,8 @@ export function SessionManager({ sessionToken, onSessionUpdate }: SessionManager
// Always render a container, even if not connected
return (
<div className="flex items-center">
{isConnected && (
sessionToken ? (
{isConnected &&
(sessionToken ? (
<button
onClick={signOut}
disabled={isLoading}
Expand All @@ -130,8 +133,7 @@ export function SessionManager({ sessionToken, onSessionUpdate }: SessionManager
>
{isLoading ? 'Signing in...' : 'Sign in'}
</button>
)
)}
))}
</div>
);
}
109 changes: 76 additions & 33 deletions frontend/src/components/Transfer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,25 @@ export function Transfer({
amount: '',
});

const { allocatedTransfer, isPending: isTransferLoading } = useAllocatedTransfer();
const { allocatedWithdrawal, isPending: isWithdrawalPending } = useAllocatedWithdrawal();
const { allocatedTransfer, isPending: isTransferLoading } =
useAllocatedTransfer();
const { allocatedWithdrawal, isPending: isWithdrawalPending } =
useAllocatedWithdrawal();
const { requestAllocation } = useRequestAllocation();
const { showNotification } = useNotification();
const [fieldErrors, setFieldErrors] = useState<{ [key: string]: string | undefined }>({});
const [fieldErrors, setFieldErrors] = useState<{
[key: string]: string | undefined;
}>({});

// Check if nonce has been consumed
const { data: isNonceConsumed } = useReadContract({
address: COMPACT_ADDRESS[parseInt(targetChainId)] as `0x${string}`,
abi: COMPACT_ABI,
functionName: 'hasConsumedAllocatorNonce',
args: formData.nonce && address ? [BigInt(formData.nonce), address as `0x${string}`] : undefined,
args:
formData.nonce && address
? [BigInt(formData.nonce), address as `0x${string}`]
: undefined,
});

// Validate amount
Expand All @@ -93,7 +100,10 @@ export function Transfer({
// Check decimal places
const decimalParts = formData.amount.split('.');
if (decimalParts.length > 1 && decimalParts[1].length > decimals) {
return { type: 'error', message: `Invalid amount (greater than ${decimals} decimals)` };
return {
type: 'error',
message: `Invalid amount (greater than ${decimals} decimals)`,
};
}

// Check against resource lock balance
Expand All @@ -120,7 +130,7 @@ export function Transfer({

// Update field errors when nonce error changes
useEffect(() => {
setFieldErrors(prev => ({
setFieldErrors((prev) => ({
...prev,
nonce: nonceError,
}));
Expand All @@ -129,25 +139,25 @@ export function Transfer({
// Validate expiry
const validateExpiry = (value: string) => {
if (!value) return { type: 'error', message: 'Expiry is required' };

const expiryTime = parseInt(value);
const now = Math.floor(Date.now() / 1000);

if (isNaN(expiryTime)) {
return { type: 'error', message: 'Invalid expiry time' };
}

if (expiryTime <= now) {
return { type: 'error', message: 'Expiry time must be in the future' };
}

return null;
};

// Update field errors when expiry changes
useEffect(() => {
const expiryValidation = validateExpiry(formData.expires);
setFieldErrors(prev => ({
setFieldErrors((prev) => ({
...prev,
expires: expiryValidation?.message,
}));
Expand All @@ -160,7 +170,7 @@ export function Transfer({
}

// Check for any field errors
if (Object.values(fieldErrors).some(error => error !== undefined)) {
if (Object.values(fieldErrors).some((error) => error !== undefined)) {
return false;
}

Expand All @@ -173,7 +183,9 @@ export function Transfer({
return true;
}, [formData, fieldErrors, validateAmount]);

const handleAction = async (action: 'transfer' | 'withdraw' | 'force' | 'disable') => {
const handleAction = async (
action: 'transfer' | 'withdraw' | 'force' | 'disable'
) => {
// Check if we need to switch networks
const targetChainIdNumber = parseInt(targetChainId);
if (targetChainIdNumber !== currentChainId) {
Expand Down Expand Up @@ -280,7 +292,7 @@ export function Transfer({

const response = await requestAllocation(params, sessionToken);

setFormData(prev => ({
setFormData((prev) => ({
...prev,
allocatorSignature: response.signature,
nonce: response.nonce,
Expand All @@ -290,14 +302,18 @@ export function Transfer({
showNotification({
type: 'success',
title: 'Allocation Requested',
message: 'Successfully received allocation. You can now submit the transfer.',
message:
'Successfully received allocation. You can now submit the transfer.',
});
} catch (error) {
console.error('Error requesting allocation:', error);
showNotification({
type: 'error',
title: 'Allocation Request Failed',
message: error instanceof Error ? error.message : 'Failed to request allocation',
message:
error instanceof Error
? error.message
: 'Failed to request allocation',
});
} finally {
setIsRequestingAllocation(false);
Expand All @@ -313,7 +329,7 @@ export function Transfer({
if (!formData.recipient?.startsWith('0x')) {
throw new Error('Recipient must be a valid address starting with 0x');
}

try {
// Convert values and prepare transfer struct
const transfer = {
Expand Down Expand Up @@ -350,14 +366,19 @@ export function Transfer({
setIsOpen(false);
} catch (conversionError) {
console.error('Error converting values:', conversionError);
throw new Error('Failed to convert input values. Please check all fields are valid.');
throw new Error(
'Failed to convert input values. Please check all fields are valid.'
);
}
} catch (error) {
console.error('Error submitting transfer:', error);
showNotification({
type: 'error',
title: isWithdrawal ? 'Withdrawal Failed' : 'Transfer Failed',
message: error instanceof Error ? error.message : `Failed to submit ${isWithdrawal ? 'withdrawal' : 'transfer'}`,
message:
error instanceof Error
? error.message
: `Failed to submit ${isWithdrawal ? 'withdrawal' : 'transfer'}`,
});
}
};
Expand All @@ -368,7 +389,7 @@ export function Transfer({
// Initialize default expiry on mount
useEffect(() => {
const now = Math.floor(Date.now() / 1000);
setFormData(prev => ({ ...prev, expires: (now + 600).toString() })); // 10 minutes default
setFormData((prev) => ({ ...prev, expires: (now + 600).toString() })); // 10 minutes default
}, []);

const handleExpiryChange = (value: string) => {
Expand All @@ -395,8 +416,8 @@ export function Transfer({
}

if (newExpiry) {
setFormData(prev => ({ ...prev, expires: newExpiry }));
setFieldErrors(prev => ({ ...prev, expires: undefined }));
setFormData((prev) => ({ ...prev, expires: newExpiry }));
setFieldErrors((prev) => ({ ...prev, expires: undefined }));
}
};

Expand Down Expand Up @@ -447,7 +468,8 @@ export function Transfer({
) : (
<>
Submit Transfer
{tokenName.resourceLockName && ` - ${tokenName.resourceLockName}`}
{tokenName.resourceLockName &&
` - ${tokenName.resourceLockName}`}
</>
)}
</h2>
Expand Down Expand Up @@ -485,17 +507,24 @@ export function Transfer({
...prev,
expires: validation?.message,
}));
setFormData((prev) => ({ ...prev, expires: e.target.value }));
setFormData((prev) => ({
...prev,
expires: e.target.value,
}));
}}
placeholder="Unix timestamp"
className={`w-full px-3 py-2 bg-gray-800 border ${
fieldErrors.expires ? 'border-red-500' : 'border-gray-700'
fieldErrors.expires
? 'border-red-500'
: 'border-gray-700'
} rounded-lg text-gray-300 focus:outline-none focus:border-[#00ff00] transition-colors`}
/>
)}
</div>
{fieldErrors.expires && (
<p className="mt-1 text-sm text-red-500">{fieldErrors.expires}</p>
<p className="mt-1 text-sm text-red-500">
{fieldErrors.expires}
</p>
)}
</div>

Expand All @@ -507,7 +536,10 @@ export function Transfer({
type="text"
value={formData.recipient}
onChange={(e) =>
setFormData((prev) => ({ ...prev, recipient: e.target.value }))
setFormData((prev) => ({
...prev,
recipient: e.target.value,
}))
}
placeholder="0x..."
className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-300 focus:outline-none focus:border-[#00ff00] transition-colors"
Expand All @@ -518,7 +550,8 @@ export function Transfer({
<label className="block text-sm font-medium text-gray-300 mb-2">
Amount
<span className="float-right text-gray-400">
Balance: {formatUnits(BigInt(resourceLockBalance), decimals)}{' '}
Balance:{' '}
{formatUnits(BigInt(resourceLockBalance), decimals)}{' '}
{isWithdrawal ? tokenSymbol : tokenName.resourceLockSymbol}
</span>
</label>
Expand All @@ -530,13 +563,17 @@ export function Transfer({
}
placeholder="0.0"
className={`w-full px-3 py-2 bg-gray-800 border ${
validateAmount()?.type === 'error' ? 'border-red-500' : 'border-gray-700'
validateAmount()?.type === 'error'
? 'border-red-500'
: 'border-gray-700'
} rounded-lg text-gray-300 focus:outline-none focus:border-[#00ff00] transition-colors`}
/>
{validateAmount() && (
<p
className={`mt-1 text-sm ${
validateAmount()?.type === 'error' ? 'text-red-500' : 'text-yellow-500'
validateAmount()?.type === 'error'
? 'text-red-500'
: 'text-yellow-500'
}`}
>
{validateAmount()?.message}
Expand Down Expand Up @@ -582,7 +619,9 @@ export function Transfer({
) : (
<button
type="submit"
disabled={!isFormValid || isTransferLoading || isWithdrawalPending}
disabled={
!isFormValid || isTransferLoading || isWithdrawalPending
}
className="w-full py-2 px-4 bg-[#00ff00] text-gray-900 rounded-lg font-medium hover:bg-[#00dd00] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{isTransferLoading || isWithdrawalPending ? (
Expand All @@ -607,10 +646,14 @@ export function Transfer({
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
{isWithdrawal ? 'Submitting Withdrawal...' : 'Submitting Transfer...'}
{isWithdrawal
? 'Submitting Withdrawal...'
: 'Submitting Transfer...'}
</span>
) : (
<>{isWithdrawal ? 'Submit Withdrawal' : 'Submit Transfer'}</>
<>
{isWithdrawal ? 'Submit Withdrawal' : 'Submit Transfer'}
</>
)}
</button>
)}
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/config/api.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// Default to production URL
const DEFAULT_GRAPHQL_URL = 'https://the-compact-indexer-2.ponder-dev.com/'
const DEFAULT_GRAPHQL_URL = 'https://the-compact-indexer-2.ponder-dev.com/';

interface Config {
graphqlUrl: string
graphqlUrl: string;
}

export const config: Config = {
graphqlUrl: import.meta.env.VITE_GRAPHQL_INDEXER_URL || DEFAULT_GRAPHQL_URL,
}
};
Loading

0 comments on commit 73aa616

Please sign in to comment.