Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
VITE_PROJECT_ID=
VITE_MOCK_GNOSIS_PAY=true

# Supabase
# Get these from your Supabase project settings
# PUBLIC_SUPABASE_URL: Settings > General > Project URL
# PUBLIC_SUPABASE_PUBLISHABLE_KEY: Settings > API > Project API keys > Publishable Key (sb_publishable_*)
# See: https://supabase.com/docs/guides/api/api-keys#overview
PUBLIC_SUPABASE_URL=
PUBLIC_SUPABASE_PUBLISHABLE_KEY=
VITE_USE_SUPABASE=true

# Blockscout API for payment verification
# For Chiado testnet
VITE_BLOCKSCOUT_BASE=https://gnosis-chiado.blockscout.com/api/v2
Expand Down
5 changes: 4 additions & 1 deletion .github/workflows/netlify-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,14 @@ jobs:
run: bun run build
env:
VITE_MOCK_GNOSIS_PAY: true
VITE_USE_SUPABASE: true
PUBLIC_SUPABASE_URL: ${{ secrets.PUBLIC_SUPABASE_URL }}
PUBLIC_SUPABASE_PUBLISHABLE_KEY: ${{ secrets.PUBLIC_SUPABASE_PUBLISHABLE_KEY }}

- name: Deploy to Netlify
uses: nwtgck/actions-netlify@v3.0
with:
publish-dir: './.svelte-kit/output'
publish-dir: './.svelte-kit/build'
production-branch: main
github-token: ${{ secrets.GITHUB_TOKEN }}
deploy-message: 'Deploy from GitHub Actions'
Expand Down
7 changes: 6 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 7 additions & 2 deletions netlify.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
[build]
command = "npm run build"
publish = "build"
command = "bun run build"
publish = ".svelte-kit/build"

[build.environment]
BUN_VERSION = "1.2.15"
VITE_USE_SUPABASE = "true"
VITE_MOCK_GNOSIS_PAY = "true"
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"private": true,
"version": "0.0.1",
"type": "module",
"packageManger": "bun@1.1.38",
"packageManager": "bun@1.2.15",
"scripts": {
"dev": "vite dev",
"build": "vite build",
Expand Down Expand Up @@ -55,6 +55,7 @@
"lucide-svelte": "^0.554.0",
"qrcode": "^1.5.4",
"viem": "^2.39.0",
"wagmi": "^2.19.4"
"wagmi": "^2.19.4",
"zod": "^4.1.13"
}
}
2 changes: 1 addition & 1 deletion src/lib/blockscoutVerifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export async function verifyAndMarkXDAIPaid(splitId: string, split: Split) {
await updateSplit(splitId, (s) => ({
...s,
payments: newPayments
}));
}), split.payerAddress);
}
} catch (error) {
console.error('Blockscout verification error:', error);
Expand Down
25 changes: 25 additions & 0 deletions src/lib/server/supabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { createClient, type SupabaseClient } from '@supabase/supabase-js';
import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY } from '$env/static/public';
import type { Database } from '$lib/supabase-types';

let _supabase: SupabaseClient<Database> | undefined;

export function getSupabase(): SupabaseClient<Database> {
if (!_supabase) {
// Use public env vars (baked in at build time)
const supabaseUrl = PUBLIC_SUPABASE_URL;
const supabaseKey = PUBLIC_SUPABASE_PUBLISHABLE_KEY;

if (!supabaseUrl || !supabaseKey) {
throw new Error(
`Missing Supabase env vars. URL: ${!!supabaseUrl}, KEY: ${!!supabaseKey}. ` +
`Make sure PUBLIC_SUPABASE_URL and PUBLIC_SUPABASE_PUBLISHABLE_KEY are set.`
);
}

_supabase = createClient<Database>(supabaseUrl, supabaseKey, {
auth: { autoRefreshToken: false, persistSession: false } // Server-side: no auth persistence
});
}
return _supabase;
}
158 changes: 61 additions & 97 deletions src/lib/storage.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,39 @@
import { browser } from '$app/environment';
import type { Split, Participant } from './types';
import { supabase } from './supabase';

const USE_SUPABASE = import.meta.env.VITE_USE_SUPABASE === 'true';
const STORAGE_KEY = 'gnosisSplits';
const API_BASE = '/api/splits';

export async function getSplits(): Promise<Split[]> {
export async function getSplits(userAddress?: string): Promise<Split[]> {
if (!USE_SUPABASE) {
if (!browser) return [];

try {
const data = localStorage.getItem(STORAGE_KEY);
return data ? JSON.parse(data) : [];
const splits = data ? JSON.parse(data) : [];
if (userAddress) {
return splits.filter((s: Split) => s.payerAddress.toLowerCase() === userAddress.toLowerCase());
}
return splits;
} catch (error) {
console.error('Failed to load splits:', error);
return [];
}
} else {
const { data, error } = await supabase
.from('splits')
.select('*')
.order('created_at', { ascending: false });
if (error) throw new Error("Error when getting splits: ", error);
if (!data) return [];

return data.map((row) => ({
id: row.id,
description: row.description,
totalAmount: row.total_amount,
date: row.date,
payerAddress: row.payer_address,
participants: row.participants as unknown as Split['participants'],
payments: row.payments as unknown as Split['payments'],
createdAt: row.created_at as unknown as Split['createdAt'],
sourceTxId: row.source_tx_id || undefined
}));
try {
const url = userAddress ? `${API_BASE}?address=${encodeURIComponent(userAddress)}` : API_BASE;
const response = await fetch(url);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
console.error('API error:', response.status, errorData);
throw new Error(`Failed to fetch splits: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Failed to load splits:', error);
return [];
}
}
}

Expand All @@ -54,67 +53,34 @@ export async function saveSplit(split: Omit<Split, 'id' | 'createdAt'>): Promise
}
}

const { data, error } = await supabase
.from('splits')
.insert({
description: split.description,
total_amount: split.totalAmount,
date: split.date,
payer_address: split.payerAddress,
participants: split.participants as any,
payments: split.payments as any,
source_tx_id: split.sourceTxId
})
.select()
.single();

if (error) throw error;

return {
id: data.id,
description: data.description,
totalAmount: data.total_amount,
date: data.date,
payerAddress: data.payer_address,
participants: data.participants as unknown as Split['participants'],
payments: data.payments as unknown as Split['payments'],
createdAt: data.created_at as unknown as Split['createdAt'],
sourceTxId: data.source_tx_id || undefined
};
const response = await fetch(API_BASE, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(split)
});

if (!response.ok) throw new Error('Failed to create split');
return await response.json();
}

export async function getSplit(id: string): Promise<Split | undefined> {
export async function getSplit(id: string, userAddress?: string): Promise<Split | undefined> {
if (!USE_SUPABASE) {
const splits = await getSplits();
const splits = await getSplits(userAddress);
return splits.find((s) => s.id === id);
}

const { data, error } = await supabase
.from('splits')
.select('*')
.eq('id', id)
.single()

if (error || !data) return undefined;

const { id: foundId, description, total_amount, date, payer_address, participants, payments, created_at, source_tx_id } = data;

const foundSplit = {
id: foundId,
description,
totalAmount: total_amount,
date,
payerAddress: payer_address,
participants: participants as unknown as Split['participants'],
payments: payments as unknown as Split['payments'],
createdAt: created_at as unknown as Split['createdAt'],
sourceTxId: source_tx_id || undefined,
try {
const url = userAddress ? `${API_BASE}/${id}?address=${encodeURIComponent(userAddress)}` : `${API_BASE}/${id}`;
const response = await fetch(url);
if (!response.ok) return undefined;
return await response.json();
} catch (error) {
console.error('Failed to load split:', error);
return undefined;
}

return foundSplit;
}

export async function updateSplit(id: string, updater: (split: Split) => Split): Promise<void> {
export async function updateSplit(id: string, updater: (split: Split) => Split, userAddress?: string): Promise<void> {
if (!USE_SUPABASE) {
if (!browser) return;

Expand All @@ -131,24 +97,18 @@ export async function updateSplit(id: string, updater: (split: Split) => Split):
throw error;
}
} else {
const split = await getSplit(id);
const split = await getSplit(id, userAddress);
if (!split) return;

const updated = updater(split);
const { error } = await supabase
.from('splits')
.update({
description: updated.description,
total_amount: updated.totalAmount,
date: updated.date,
payer_address: updated.payerAddress,
participants: updated.participants as any,
payments: updated.payments as any,
source_tx_id: updated.sourceTxId
})
.eq('id', id);

if (error) throw error;
const url = userAddress ? `${API_BASE}/${id}?address=${encodeURIComponent(userAddress)}` : `${API_BASE}/${id}`;
const response = await fetch(url, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updated)
});

if (!response.ok) throw new Error('Failed to update split');
}
}

Expand All @@ -165,8 +125,11 @@ export async function deleteSplit(id: string): Promise<void> {
throw error;
}
} else {
const { error } = await supabase.from('splits').delete().eq('id', id);
if (error) throw error;
const response = await fetch(`${API_BASE}/${id}`, {
method: 'DELETE'
});

if (!response.ok) throw new Error('Failed to delete split');
}
}

Expand All @@ -189,13 +152,14 @@ export async function updateSplitParticipants(splitId: string, participants: Par
}
}

const { error } = await supabase
.from('splits')
.update({ participants: participants as any })
.eq('id', splitId);
const response = await fetch(`${API_BASE}/${splitId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ participants })
});

if (error) {
console.error('Failed to update participants', error);
throw error;
if (!response.ok) {
console.error('Failed to update participants');
throw new Error('Failed to update participants');
}
}
10 changes: 10 additions & 0 deletions src/lib/stores/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ export const appKitStore = writable({
});

if (browser && appKit) {
const account = appKit.getAccount?.();
const state = appKit.getState?.();

appKitStore.set({
open: state?.open ?? false,
selectedNetworkId: state?.selectedNetworkId,
address: account?.address,
isConnected: account?.isConnected ?? false
});

appKit.subscribeState((state) => {
appKitStore.update((current) => ({
...current,
Expand Down
Loading