Skip to content

Commit

Permalink
remove resources from 4361
Browse files Browse the repository at this point in the history
  • Loading branch information
0age committed Dec 5, 2024
1 parent af3c7ee commit cab2b94
Show file tree
Hide file tree
Showing 7 changed files with 87 additions and 61 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,8 @@ git clone [email protected]:Uniswap/smallocator.git && cd smallocator
# 2. Copy example environment file (modify as needed)
cp .env.example .env

# 3. Install dependencies
pnpm install
# 3. Install frontend and backend dependencies
pnpm install:all

# 4. Run tests
pnpm test
Expand Down
13 changes: 10 additions & 3 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { WagmiProvider } from 'wagmi';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { http } from 'wagmi';
import '@rainbow-me/rainbowkit/styles.css';
import { useState } from 'react';
import { useState, useMemo } from 'react';

import { WalletConnect } from './components/WalletConnect';
import { SessionManager } from './components/SessionManager';
Expand All @@ -19,10 +19,17 @@ const config = getDefaultConfig({
},
});

const queryClient = new QueryClient();

function App() {
const [hasSession, setHasSession] = useState(false);

const queryClient = useMemo(() => new QueryClient({
defaultOptions: {
queries: {
staleTime: Infinity,
refetchOnWindowFocus: false,
},
},
}), []);

return (
<WagmiProvider config={config}>
Expand Down
78 changes: 51 additions & 27 deletions frontend/src/components/SessionManager.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useAccount, useSignMessage, useChainId } from 'wagmi';
import { useState, useEffect } from 'react';
import { useState, useCallback } from 'react';

interface SessionManagerProps {
onSessionCreated: () => void;
Expand All @@ -10,32 +10,36 @@ export function SessionManager({ onSessionCreated }: SessionManagerProps) {
const { signMessageAsync } = useSignMessage();
const chainId = useChainId();
const [sessionToken, setSessionToken] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);

const createSession = async () => {
if (!address || !chainId) return;
const createSession = useCallback(async () => {
if (!address || !chainId || isLoading) {
return;
}

setIsLoading(true);
try {
// First, get the payload from server
const payloadResponse = await fetch(`/session/${address}`);
const payloadResponse = await fetch(`/session/${chainId}/${address}`);
if (!payloadResponse.ok) {
throw new Error('Failed to get session payload');
}

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

// Format the message according to EIP-4361
const message = [
`${payload.domain} wants you to sign in with your Ethereum account:`,
payload.address,
`${session.domain} wants you to sign in with your Ethereum account:`,
session.address,
'',
payload.statement,
session.statement,
'',
`URI: ${payload.uri}`,
`Version: ${payload.version}`,
`Chain ID: ${payload.chainId}`,
`Nonce: ${payload.nonce}`,
`Issued At: ${payload.issuedAt}`,
`Expiration Time: ${payload.expirationTime}`,
`URI: ${session.uri}`,
`Version: ${session.version}`,
`Chain ID: ${session.chainId}`,
`Nonce: ${session.nonce}`,
`Issued At: ${session.issuedAt}`,
`Expiration Time: ${session.expirationTime}`,
].join('\n');

// Get signature from wallet
Expand All @@ -51,35 +55,55 @@ export function SessionManager({ onSessionCreated }: SessionManagerProps) {
},
body: JSON.stringify({
signature,
payload,
payload: {
...session,
chainId: parseInt(session.chainId.toString(), 10), // Ensure chainId is a number
},
}),
});

if (response.ok) {
const data = await response.json();
setSessionToken(data.token);
setSessionToken(data.session.id);
onSessionCreated();
} else {
console.error('Failed to create session:', await response.text());
const errorText = await response.text();
console.error('Failed to create session:', errorText);
}
} catch (error) {
console.error('Failed to create session:', error);
} finally {
setIsLoading(false);
}
};

useEffect(() => {
if (isConnected && address && !sessionToken && chainId) {
createSession();
}
}, [isConnected, address, sessionToken, chainId]);
}, [address, chainId, signMessageAsync, onSessionCreated]);

if (!isConnected) {
return (
<div>
<p>Please connect your wallet to continue.</p>
<div className="text-center">
<p className="text-gray-600">Please connect your wallet to continue.</p>
</div>
);
}

return null;
if (sessionToken) {
return null;
}

const canLogin = isConnected && address && chainId && !isLoading;

return (
<div className="text-center">
<button
onClick={createSession}
disabled={!canLogin}
className={`px-4 py-2 rounded-lg font-medium ${
canLogin
? 'bg-blue-600 text-white hover:bg-blue-700'
: 'bg-gray-300 text-gray-500 cursor-not-allowed'
}`}
>
{isLoading ? 'Signing in...' : 'Sign in with Ethereum'}
</button>
</div>
);
}
23 changes: 21 additions & 2 deletions frontend/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,29 @@ export default defineConfig(({ mode }) => {
plugins: [react()],
server: {
proxy: {
'/api': {
'/session': {
target: baseUrl,
changeOrigin: true,
},
'/health': {
target: baseUrl,
changeOrigin: true,
},
'/compact': {
target: baseUrl,
changeOrigin: true,
},
'/compacts': {
target: baseUrl,
changeOrigin: true,
},
'/balance': {
target: baseUrl,
changeOrigin: true,
},
'/balances': {
target: baseUrl,
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"start": "node dist/index.js",
"dev": "tsx watch src/index.ts",
"dev:all": "concurrently \"pnpm dev\" \"cd frontend && pnpm dev\"",
"install:all": "pnpm install && cd frontend && pnpm install && cd -",
"prebuild": "rm -rf dist && cd frontend && pnpm build",
"build": "esbuild src/index.ts --bundle --platform=node --outdir=dist --format=esm --sourcemap --packages=external && cp .env dist/ 2>/dev/null || true && cp -r frontend/dist dist/frontend",
"build:all": "pnpm build",
Expand Down
3 changes: 0 additions & 3 deletions src/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,6 @@ export async function generateSignature(
`Nonce: ${payload.nonce}`,
`Issued At: ${payload.issuedAt}`,
`Expiration Time: ${payload.expirationTime}`,
payload.resources
? `Resources:\n${payload.resources.join('\n')}`
: '',
].join('\n');

// Sign the message using the private key directly
Expand Down
26 changes: 2 additions & 24 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ export interface SessionPayload {
nonce: string;
issuedAt: string;
expirationTime: string;
resources?: string[];
}

export interface Session {
Expand Down Expand Up @@ -262,20 +261,6 @@ function isValidPayload(payload: SessionPayload): boolean {
throw new Error('Invalid chain ID');
}

// Validate resources URIs if present
if (payload.resources) {
for (const resource of payload.resources) {
if (typeof resource !== 'string') {
throw new Error('Invalid resource type');
}
try {
new URL(resource);
} catch {
throw new Error('Invalid resource URI');
}
}
}

return true;
} catch (error) {
console.error('Payload validation failed:', {
Expand All @@ -287,7 +272,7 @@ function isValidPayload(payload: SessionPayload): boolean {
}

function formatMessage(payload: SessionPayload): string {
const lines = [
return [
`${payload.domain} wants you to sign in with your Ethereum account:`,
payload.address,
'',
Expand All @@ -299,12 +284,5 @@ function formatMessage(payload: SessionPayload): string {
`Nonce: ${payload.nonce}`,
`Issued At: ${payload.issuedAt}`,
`Expiration Time: ${payload.expirationTime}`,
];

if (payload.resources?.length) {
lines.push('Resources:');
lines.push(...payload.resources.map((r) => `- ${r}`));
}

return lines.join('\n');
].join('\n');
}

0 comments on commit cab2b94

Please sign in to comment.