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
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
PORT=3000
RPC_URL=https://soroban-testnet.stellar.org
HORIZON_URL=https://horizon-testnet.stellar.org
NETWORK_PASSPHRASE=Test SDF Network ; September 2015
CONTRACT_ID=CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2QD
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
Expand Down
13 changes: 10 additions & 3 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ try {

// Initialize Stellar/Soroban dependencies
const server = new StellarSdk.SorobanRpc.Server(config.RPC_URL);
const horizonServer = new StellarSdk.Horizon.Server(config.HORIZON_URL);
const contract = new StellarSdk.Contract(config.CONTRACT_ID);

// Initialize Prisma
Expand All @@ -35,15 +36,19 @@ const { createEscrowRepository } = require('./repositories/escrow.repository');
const { createTransactionRepository } = require('./repositories/transaction.repository');

createUserRepository({ prisma });
createWalletRepository({ prisma });
const walletRepository = createWalletRepository({ prisma });
const escrowRepository = createEscrowRepository({ prisma });
const transactionRepository = createTransactionRepository({ prisma });

// Bootstrap Dependency Injection Container
const transactionBuilder = createTransactionBuilder({ server, contract, config });
const escrowService = createEscrowService({ transactionBuilder, config, escrowRepository, transactionRepository });
const horizonService = createHorizonService({ server });
const horizonService = createHorizonService({ server, horizonServer });
const stellarService = createStellarService({ config, server });

const { createWalletProvider } = require('./providers/wallet.provider');
const walletProvider = createWalletProvider({ config, horizonService });

// eslint-disable-next-line no-unused-vars
const embeddedWalletProvider = createEmbeddedWalletProvider({ config });

Expand All @@ -56,10 +61,12 @@ app.use(express.json());
const authRoutes = require('./routes/auth.routes');
const usersRoutes = require('./routes/users.routes');
const accountsRoutes = require('./routes/accounts.routes');
const walletsRoutes = require('./routes/wallets.routes');
const { createWalletsRoutes } = require('./routes/wallets.routes');

// API Routes
const relayerRoutes = createRelayerRoutes({ escrowService, horizonService, stellarService });
const walletsRoutes = createWalletsRoutes({ walletProvider, walletRepository });

app.use('/health', healthRoutes);
app.use('/api/auth', authRoutes);
app.use('/api/users/me', authenticate, usersRoutes);
Expand Down
1 change: 1 addition & 0 deletions src/config/env.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ require('dotenv').config();
const envSchema = z.object({
PORT: z.string().default('3000'),
RPC_URL: z.string().url(),
HORIZON_URL: z.string().url(),
NETWORK_PASSPHRASE: z.string().min(1),
CONTRACT_ID: z.string().min(1),
FEE_BUMP_SECRET_KEY: z.string().min(1),
Expand Down
13 changes: 8 additions & 5 deletions src/providers/wallet.provider.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ const crypto = require('crypto');
*
* @param {Object} [deps] - Dependencies
* @param {Object} [deps.config] - Application configuration.
* @param {Object} [deps.horizonService] - The horizon network service
*/
const createWalletProvider = ({ config } = {}) => {
const createWalletProvider = ({ config, horizonService } = {}) => {
/**
* Executes a managed wallet top-up through the underlying provider.
*
Expand Down Expand Up @@ -61,14 +62,16 @@ const createWalletProvider = ({ config } = {}) => {
};

/**
* Retrieves the mock balance of the wallet.
* Retrieves the real on-chain native balance of the wallet from the network.
*
* @param {string} walletAddress - The managed wallet address.
* @returns {Promise<string>} The balance as a string.
*/
const getBalance = async (_walletAddress) => {
// Stub: Returns a mock balance of 1000.00 for testing withdrawals.
return '1000.00';
const getBalance = async (walletAddress) => {
if (!horizonService) {
throw new Error('horizonService is required to fetch real balances');
}
return horizonService.getAccountBalance(walletAddress);
};

return { fundWallet, withdrawFromWallet, getBalance };
Expand Down
119 changes: 62 additions & 57 deletions src/routes/wallets.routes.js
Original file line number Diff line number Diff line change
@@ -1,75 +1,80 @@
const express = require('express');
const router = express.Router();
const AppError = require('../errors/AppError');
const prisma = require('../clients/prisma.client');
const { WalletRepository } = require('../repositories/wallet.repository');
const { createWalletProvider } = require('../providers/wallet.provider');
const { validate } = require('../middleware/validate.middleware');
const { withdrawSchema } = require('../validation/schemas/wallet.schema');
const { StrKey } = require('stellar-sdk');

const walletRepository = new WalletRepository(prisma);
const walletProvider = createWalletProvider();
/**
* Factory function for Wallets API routes.
* @param {Object} deps - Dependencies
* @param {Object} deps.walletProvider - The wallet provider instance
* @param {Object} deps.walletRepository - The wallet repository instance
*/
const createWalletsRoutes = ({ walletProvider, walletRepository }) => {
const router = express.Router();

router.get('/me', async (req, res, next) => {
try {
const userId = req.user.id;
const wallet = await walletRepository.findByUserId(userId);
router.get('/me', async (req, res, next) => {
try {
const userId = req.user.id;
const wallet = await walletRepository.findByUserId(userId);

if (!wallet) {
throw new AppError('Wallet not found', 404);
if (!wallet) {
throw new AppError('Wallet not found', 404);
}

res.status(200).json({
success: true,
message: 'Wallet retrieved successfully',
data: {
id: wallet.id,
publicKey: wallet.publicKey,
createdAt: wallet.createdAt,
},
});
} catch (error) {
next(error);
}
});

res.status(200).json({
success: true,
message: 'Wallet retrieved successfully',
data: {
id: wallet.id,
publicKey: wallet.publicKey,
createdAt: wallet.createdAt,
},
});
} catch (error) {
next(error);
}
});
router.post('/withdraw', validate(withdrawSchema), async (req, res, next) => {
try {
const userId = req.user.id;
const { destinationAddress, amount, asset } = req.body;

router.post('/withdraw', validate(withdrawSchema), async (req, res, next) => {
try {
const userId = req.user.id;
const { destinationAddress, amount, asset } = req.body;
if (!StrKey.isValidEd25519PublicKey(destinationAddress)) {
throw new AppError('Invalid Stellar destination address', 400);
}

if (!StrKey.isValidEd25519PublicKey(destinationAddress)) {
throw new AppError('Invalid Stellar destination address', 400);
}
const wallet = await walletRepository.findByUserId(userId);
if (!wallet) {
throw new AppError('Wallet not found', 404);
}

const wallet = await walletRepository.findByUserId(userId);
if (!wallet) {
throw new AppError('Wallet not found', 404);
}
const balanceStr = await walletProvider.getBalance(wallet.publicKey);
const balance = Number(balanceStr);
const withdrawAmount = Number(amount);

const balanceStr = await walletProvider.getBalance(wallet.publicKey);
const balance = Number(balanceStr);
const withdrawAmount = Number(amount);
if (withdrawAmount > balance) {
throw new AppError('Withdrawal amount exceeds available balance', 400);
}

if (withdrawAmount > balance) {
throw new AppError('Withdrawal amount exceeds available balance', 400);
}
const receipt = await walletProvider.withdrawFromWallet({
walletAddress: wallet.publicKey,
amount,
asset,
});

const receipt = await walletProvider.withdrawFromWallet({
walletAddress: wallet.publicKey,
amount,
asset,
});
res.status(200).json({
success: true,
message: 'Withdrawal initiated successfully',
data: receipt,
});
} catch (error) {
next(error);
}
});

res.status(200).json({
success: true,
message: 'Withdrawal initiated successfully',
data: receipt,
});
} catch (error) {
next(error);
}
});
return router;
};

module.exports = router;
module.exports = { createWalletsRoutes };
25 changes: 23 additions & 2 deletions src/services/horizon.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,29 @@ const { parseTransactionStatus } = require('../utils/status.parser');
* Factory function for the Network Service (Horizon/RPC) handling network queries.
* @param {Object} deps - Dependencies
* @param {StellarSdk.SorobanRpc.Server} deps.server - The Soroban RPC server instance
* @param {StellarSdk.Horizon.Server} deps.horizonServer - The Horizon server instance
*/
const createHorizonService = ({ server }) => {
const createHorizonService = ({ server, horizonServer }) => {
/**
* Retrieves the native XLM balance for a given Stellar account.
* @param {string} accountId - The Stellar account ID (public key).
* @returns {Promise<string>} The balance as a string.
*/
const getAccountBalance = async (accountId) => {
try {
const account = await horizonServer.loadAccount(accountId);
const nativeBalance = account.balances.find((b) => b.asset_type === 'native');
return nativeBalance ? nativeBalance.balance : '0.0000000';
} catch (error) {
if (error.response && error.response.status === 404) {
// Account not found on the network means it has 0 balance (not funded yet)
return '0.0000000';
}
console.error('[BALANCE EXCEPTION]', error);
throw new RpcError('Failed to fetch account balance from Horizon.');
}
};

/**
* Queries the Stellar RPC network for the status of a specific transaction.
* @param {string} txId - The transaction ID hash to query.
Expand All @@ -22,7 +43,7 @@ const createHorizonService = ({ server }) => {
}
};

return { getTransactionStatus };
return { getTransactionStatus, getAccountBalance };
};

module.exports = { createHorizonService };
9 changes: 7 additions & 2 deletions tests/config/env.config.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ describe('Environment Configuration', () => {

it('should load configuration when all required variables are present', () => {
process.env.RPC_URL = 'https://rpc-testnet.stellar.org';
process.env.HORIZON_URL = 'https://horizon-testnet.stellar.org';
process.env.NETWORK_PASSPHRASE = 'Test SDF Network ; September 2015';
process.env.CONTRACT_ID = 'CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2QD';
process.env.FEE_BUMP_SECRET_KEY = 'SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABUQQQ';
Expand All @@ -27,6 +28,7 @@ describe('Environment Configuration', () => {
expect(config).toBeDefined();
expect(config.PORT).toBe('3000'); // Default
expect(config.RPC_URL).toBe(process.env.RPC_URL);
expect(config.HORIZON_URL).toBe(process.env.HORIZON_URL);
});

it('should throw ConfigError if required variables are missing', () => {
Expand All @@ -39,21 +41,23 @@ describe('Environment Configuration', () => {

it('should throw ConfigError if variables are invalid (e.g., bad URL)', () => {
process.env.RPC_URL = 'not-a-url';
process.env.HORIZON_URL = 'https://horizon-testnet.stellar.org';
process.env.NETWORK_PASSPHRASE = 'Test SDF Network ; September 2015';
process.env.CONTRACT_ID = 'CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2QD';
process.env.FEE_BUMP_SECRET_KEY = 'SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABUQQQ';
process.env.DATABASE_URL = 'postgresql://user:password@localhost:5432/mydb';
process.env.JWT_SECRET = 'super-secret-key-that-is-at-least-32-chars-long!';
process.env.GOOGLE_CLIENT_ID = 'test-google-client-id';

expect(() => loadConfig()).toThrow(ConfigError);
});

it('should throw ConfigError if DATABASE_URL is missing', () => {
process.env.RPC_URL = 'https://rpc-testnet.stellar.org';
process.env.HORIZON_URL = 'https://horizon-testnet.stellar.org';
process.env.NETWORK_PASSPHRASE = 'Test SDF Network ; September 2015';
process.env.CONTRACT_ID = 'CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2QD';
process.env.FEE_BUMP_SECRET_KEY = 'SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABUQQQ';
process.env.JWT_SECRET = 'super-secret-key-that-is-at-least-32-chars-long!';
process.env.GOOGLE_CLIENT_ID = 'test-google-client-id';
delete process.env.DATABASE_URL;

expect(() => loadConfig()).toThrow(ConfigError);
Expand All @@ -62,6 +66,7 @@ describe('Environment Configuration', () => {

it('should throw ConfigError if JWT_SECRET is too short', () => {
process.env.RPC_URL = 'https://rpc-testnet.stellar.org';
process.env.HORIZON_URL = 'https://horizon-testnet.stellar.org';
process.env.NETWORK_PASSPHRASE = 'Test SDF Network ; September 2015';
process.env.CONTRACT_ID = 'CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2QD';
process.env.FEE_BUMP_SECRET_KEY = 'SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABUQQQ';
Expand Down
19 changes: 19 additions & 0 deletions tests/providers/wallet.provider.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,23 @@ describe('Wallet Provider', () => {
expect(receipt.network).toBe('unknown');
});
});

describe('getBalance', () => {
it('should fetch real balance from horizonService', async () => {
const mockHorizonService = {
getAccountBalance: jest.fn().mockResolvedValue('500.1234567'),
};
const provider = createWalletProvider({ horizonService: mockHorizonService });

const balance = await provider.getBalance('G_WALLET_ADDRESS');

expect(mockHorizonService.getAccountBalance).toHaveBeenCalledWith('G_WALLET_ADDRESS');
expect(balance).toBe('500.1234567');
});

it('should throw an error if horizonService is not provided', async () => {
const provider = createWalletProvider();
await expect(provider.getBalance('G_WALLET_ADDRESS')).rejects.toThrow('horizonService is required to fetch real balances');
});
});
});
Loading
Loading