Skip to content
Open
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
1,475 changes: 1,475 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
"lint": "next lint"
},
"dependencies": {
"@albedo-link/intent": "^0.13.0",
"@creit.tech/xbull-wallet-connect": "^0.4.0",
"@sorosave/sdk": "workspace:*",
"@stellar/freighter-api": "^2.0.0",
"next": "^14.2.0",
Expand Down
55 changes: 41 additions & 14 deletions src/app/providers.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
"use client";

import React, { createContext, useContext, useState, useCallback, useEffect } from "react";
import { connectWallet, getPublicKey, isFreighterInstalled } from "@/lib/wallet";
import { WALLET_ADAPTERS, WalletAdapter } from "@/lib/wallets";

const ACTIVE_WALLET_KEY = "sorosave_active_wallet";

interface WalletContextType {
address: string | null;
isConnected: boolean;
isFreighterAvailable: boolean;
connect: () => Promise<void>;
activeAdapterId: string | null;
connect: (adapterId: string) => Promise<void>;
disconnect: () => void;
getAdapter: () => WalletAdapter | null;
}

const WalletContext = createContext<WalletContextType>({
address: null,
isConnected: false,
isFreighterAvailable: false,
activeAdapterId: null,
connect: async () => {},
disconnect: () => {},
getAdapter: () => null,
});

export function useWallet() {
Expand All @@ -25,33 +29,56 @@ export function useWallet() {

export function Providers({ children }: { children: React.ReactNode }) {
const [address, setAddress] = useState<string | null>(null);
const [isFreighterAvailable, setIsFreighterAvailable] = useState(false);
const [activeAdapterId, setActiveAdapterId] = useState<string | null>(null);

// Restore wallet connection
useEffect(() => {
isFreighterInstalled().then(setIsFreighterAvailable);
// Try to reconnect on load
getPublicKey().then((key) => {
if (key) setAddress(key);
});
const savedWallet = localStorage.getItem(ACTIVE_WALLET_KEY);
if (savedWallet && WALLET_ADAPTERS[savedWallet]) {
const adapter = WALLET_ADAPTERS[savedWallet];
setActiveAdapterId(savedWallet);
adapter.getPublicKey().then((addr) => {
if (addr) setAddress(addr);
});
}
}, []);

const connect = useCallback(async () => {
const addr = await connectWallet();
if (addr) setAddress(addr);
const getAdapter = useCallback(() => {
if (!activeAdapterId) return null;
return WALLET_ADAPTERS[activeAdapterId] || null;
}, [activeAdapterId]);

const connect = useCallback(async (adapterId: string) => {
const adapter = WALLET_ADAPTERS[adapterId];
if (!adapter) throw new Error(`Wallet adapter ${adapterId} not found`);

try {
const addr = await adapter.connect();
if (addr) {
setAddress(addr);
setActiveAdapterId(adapterId);
localStorage.setItem(ACTIVE_WALLET_KEY, adapterId);
}
} catch (e) {
console.error("Connection failed", e);
}
}, []);

const disconnect = useCallback(() => {
setAddress(null);
setActiveAdapterId(null);
localStorage.removeItem(ACTIVE_WALLET_KEY);
}, []);

return (
<WalletContext.Provider
value={{
address,
isConnected: !!address,
isFreighterAvailable,
activeAdapterId,
connect,
disconnect,
getAdapter,
}}
>
{children}
Expand Down
76 changes: 53 additions & 23 deletions src/components/ConnectWallet.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,24 @@
"use client";

import { useWallet } from "@/app/providers";
import { shortenAddress } from "@sorosave/sdk";
import { useState } from "react";
import { WALLET_ADAPTERS } from "@/lib/wallets";

export function ConnectWallet() {
const { address, isConnected, isFreighterAvailable, connect, disconnect } =
useWallet();
function shortenAddress(address: string) {
return `${address.slice(0, 5)}...${address.slice(-4)}`;
}

if (!isFreighterAvailable) {
return (
<a
href="https://www.freighter.app/"
target="_blank"
rel="noopener noreferrer"
className="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg text-sm font-medium hover:bg-gray-300"
>
Install Freighter
</a>
);
}
export function ConnectWallet() {
const { address, isConnected, connect, disconnect, activeAdapterId } = useWallet();
const [isModalOpen, setIsModalOpen] = useState(false);

if (isConnected && address) {
const activeAdapter = activeAdapterId ? WALLET_ADAPTERS[activeAdapterId] : null;

return (
<div className="flex items-center space-x-3">
<span className="text-sm text-gray-600 bg-gray-100 px-3 py-1 rounded-full">
<span className="text-sm text-gray-600 bg-gray-100 px-3 py-1 rounded-full flex items-center">
{activeAdapter && <span className="mr-2 font-bold">{activeAdapter.name}</span>}
{shortenAddress(address)}
</span>
<button
Expand All @@ -37,11 +32,46 @@ export function ConnectWallet() {
}

return (
<button
onClick={connect}
className="bg-primary-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-primary-700 transition-colors"
>
Connect Wallet
</button>
<>
<button
onClick={() => setIsModalOpen(true)}
className="bg-primary-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-primary-700 transition-colors"
>
Connect Wallet
</button>

{isModalOpen && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
<div className="bg-white rounded-xl shadow-xl w-full max-w-sm overflow-hidden text-black">
<div className="p-4 border-b flex justify-between items-center text-black">
<h2 className="text-lg font-semibold text-gray-800">Select a Wallet</h2>
<button
onClick={() => setIsModalOpen(false)}
className="text-gray-500 hover:text-gray-700 text-xl font-bold"
>
&times;
</button>
</div>

<div className="p-4 space-y-2">
{Object.values(WALLET_ADAPTERS).map((adapter) => (
<button
key={adapter.id}
onClick={async () => {
await connect(adapter.id);
setIsModalOpen(false);
}}
className="w-full flex items-center p-3 rounded-lg border border-gray-200 hover:bg-gray-50 hover:border-gray-500 transition-all text-left"
>
<div className="flex-1 font-medium text-gray-700">
Connect with {adapter.name}
</div>
</button>
))}
</div>
</div>
</div>
)}
</>
);
}
44 changes: 44 additions & 0 deletions src/lib/wallets/albedo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import albedo from "@albedo-link/intent";
import { WalletAdapter } from "./base";

export class AlbedoAdapter implements WalletAdapter {
id = "albedo";
name = "Albedo";
icon = "albedo"; // Placeholder for icon

async isInstalled(): Promise<boolean> {
return true; // Albedo is web-based and always available
}

async connect(): Promise<string> {
try {
const response = await albedo.publicKey({});
return response.pubkey;
} catch (e) {
console.error("Albedo connect error:", e);
throw e;
}
}

async getPublicKey(): Promise<string | null> {
// Albedo connects on a per request basis; usually persistence isn't automatic
// Thus we handle persistence in our state or localStorage.
return null;
}

async signTransaction(xdr: string, networkPassphrase?: string): Promise<string> {
try {
const isTestnet = networkPassphrase?.includes("Test SDF Network");
const network = isTestnet ? "testnet" : "public";

const response = await albedo.tx({
xdr,
network,
});
return response.signed_envelope_xdr;
} catch (e) {
console.error("Albedo sign error:", e);
throw e;
}
}
}
9 changes: 9 additions & 0 deletions src/lib/wallets/base.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface WalletAdapter {
id: string;
name: string;
icon: string | React.ReactNode;
isInstalled(): Promise<boolean>;
connect(): Promise<string>;
getPublicKey(): Promise<string | null>;
signTransaction(xdr: string, networkPassphrase?: string): Promise<string>;
}
35 changes: 35 additions & 0 deletions src/lib/wallets/freighter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import freighter from "@stellar/freighter-api";
import { WalletAdapter } from "./base";

export class FreighterAdapter implements WalletAdapter {
id = "freighter";
name = "Freighter";
icon = "freighter"; // Can be replaced with actual SVG/Image component if needed

async isInstalled(): Promise<boolean> {
try {
return await freighter.isConnected();
} catch {
return false;
}
}

async connect(): Promise<string> {
const address = await freighter.requestAccess();
return address;
}

async getPublicKey(): Promise<string | null> {
try {
return await freighter.getPublicKey();
} catch {
return null;
}
}

async signTransaction(xdr: string, networkPassphrase?: string): Promise<string> {
return await freighter.signTransaction(xdr, {
networkPassphrase: networkPassphrase || "Test SDF Network ; September 2015",
});
}
}
15 changes: 15 additions & 0 deletions src/lib/wallets/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { WalletAdapter } from "./base";
import { FreighterAdapter } from "./freighter";
import { XBullAdapter } from "./xbull";
import { AlbedoAdapter } from "./albedo";

export * from "./base";
export * from "./freighter";
export * from "./xbull";
export * from "./albedo";

export const WALLET_ADAPTERS: Record<string, WalletAdapter> = {
freighter: new FreighterAdapter(),
xbull: new XBullAdapter(),
albedo: new AlbedoAdapter(),
};
53 changes: 53 additions & 0 deletions src/lib/wallets/xbull.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { xBullWalletConnect } from "@creit.tech/xbull-wallet-connect";
import { WalletAdapter } from "./base";

export class XBullAdapter implements WalletAdapter {
id = "xbull";
name = "xBull";
icon = "xbull";

private connection: xBullWalletConnect | null = null;

async isInstalled(): Promise<boolean> {
return true; // Provided via browser extension or app connect
}

async connect(): Promise<string> {
try {
this.connection = new xBullWalletConnect();
await this.connection.connect();
return await this.connection.getPublicKey();
} catch (e) {
console.error("xBull connect error:", e);
throw e;
}
}

async getPublicKey(): Promise<string | null> {
// We shouldn't automatically spin up a new connection if none exists since it pops up UI.
// Return null and let localStorage handle persistence across reloads.
if (!this.connection) return null;
return await this.connection.getPublicKey();
}

async signTransaction(xdr: string, networkPassphrase?: string): Promise<string> {
try {
if (!this.connection) {
this.connection = new xBullWalletConnect();
await this.connection.connect();
}

const isTestnet = networkPassphrase?.includes("Test SDF Network");
const network = isTestnet ? "testnet" : "public";

// The xbull signature accepts the xdr string
return await this.connection.sign({
xdr,
network
});
} catch (e) {
console.error("xBull sign error:", e);
throw e;
}
}
}