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
4 changes: 4 additions & 0 deletions package-lock.json

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

3 changes: 0 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,6 @@
"swagger-ui-express": "^5.0.1",
"winston": "^3.14.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3",
"winston-daily-rotate-file": "^5.0.0"
"winston-daily-rotate-file": "^5.0.0",
"ws": "^8.21.0",
"yamljs": "^0.3.0",
"zod": "^4.4.3"
Expand Down
5 changes: 1 addition & 4 deletions src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,9 @@ module.exports = {
redis: {
url: env.REDIS_URL,
},
databaseUrl: process.env.DATABASE_URL || 'postgres://postgres:postgres@localhost:5432/smartdrop',
stellar: {
horizonUrl: process.env.STELLAR_HORIZON_URL || 'https://horizon.stellar.org',
sorobanRpcUrl: process.env.SOROBAN_RPC_URL || 'https://soroban-rpc.mainnet.stellar.gateway.fm',
usdcIssuer: process.env.USDC_ISSUER || 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335AX2OBFLDTQLNUEHRGPTM6RIA',
horizonUrl: env.STELLAR_HORIZON_URL,
sorobanRpcUrl: process.env.SOROBAN_RPC_URL || 'https://soroban-rpc.mainnet.stellar.gateway.fm',
usdcIssuer,
},
indexer: {
Expand Down
65 changes: 13 additions & 52 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,7 @@ const apiDocsRouter = require('./routes/apiDocs');
const priceWebSocket = require('./ws/priceWebSocket');

const app = express();
let server = {
close(callback) {
if (callback) callback();
},
};
let server;

app.use(requestIdMiddleware);
app.use(helmet());
Expand Down Expand Up @@ -114,40 +110,11 @@ app.use('/api-docs', apiDocsRouter);
app.use(notFoundHandler);
app.use(errorHandler);

const server = app.listen(config.port, () => {
logger.info(`SmartDrop backend running on port ${config.port}`);
priceRefreshJob.start();
indexerPoller.start();
});

let server;

if (require.main === module) {
server = app.listen(config.port, () => {
logger.info(`SmartDrop backend running on port ${config.port}`);
priceRefreshJob.start();
});
process.on('SIGTERM', async () => {
logger.info('SIGTERM received, shutting down');
priceRefreshJob.stop();
indexerPoller.stop();
server.close();
await cache.disconnect();
process.exit(0);
});

process.on('SIGINT', async () => {
logger.info('SIGINT received, shutting down');
priceRefreshJob.stop();
indexerPoller.stop();
server.close();
await cache.disconnect();
process.exit(0);
});
function shutdown(signal) {
return async () => {
logger.info(`${signal} received, shutting down`);
priceRefreshJob.stop();
indexerPoller.stop();
webhookRetryWorker.stop();
airdropExpiryJob.stop();
require('./ws/PriceSubscriptionManager').stopHeartbeat();
Expand All @@ -157,23 +124,14 @@ function shutdown(signal) {
};
}

if (require.main === module) {
startServer().catch((err) => {
logger.error('Startup failed', { error: err.message });
process.exit(1);
});

process.on('SIGTERM', shutdown('SIGTERM'));
process.on('SIGINT', shutdown('SIGINT'));
}

async function startServer() {
await warmCache(config.watchedAssets);

server = app.listen(config.port, () => {
logger.info(`SmartDrop backend running on port ${config.port}`);
priceWebSocket.attach(server);
priceRefreshJob.start();
indexerPoller.start();
webhookRetryWorker.start();
airdropExpiryJob.start();
});
Expand All @@ -182,12 +140,15 @@ async function startServer() {
return server;
}

if (require.main === module) {
startServer().catch((err) => {
logger.error('Startup failed', { error: err.message });
process.exit(1);
});

process.on('SIGTERM', shutdown('SIGTERM'));
process.on('SIGINT', shutdown('SIGINT'));
}

module.exports = { app, server };
module.exports = app;
module.exports.app = app;
module.exports.server = server || {
close(callback) {
if (callback) callback();
},
};
module.exports.startServer = startServer;
61 changes: 12 additions & 49 deletions src/routes/airdrops.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,15 @@ const {
recipientsSchema,
routeIdParamsSchema,
} = require('../validation/schemas');
const buildRateLimit = require('../middleware/rateLimit');
const { StrKey } = require('stellar-sdk');

const router = express.Router();
const upload = multer();
const CSV_PARSE_CHUNK_BYTES = 64 * 1024;
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: config.airdrops.csvMaxBytes },
});
const validateRouteIdParams = validate(routeIdParamsSchema, 'params');
const validatePaginationQuery = validate(paginationQuerySchema, 'query');
const validateRecipientBody = validate(airdropRecipientsBodySchema);
Expand All @@ -31,15 +37,9 @@ function validateWithCurrentLedger(schemaFactory) {
} catch (err) {
logger.error('Airdrop validation error', { error: err.message });
return next(err);
const buildRateLimit = require('../middleware/rateLimit');
const { StrKey } = require('stellar-sdk');

const router = express.Router();
const CSV_PARSE_CHUNK_BYTES = 64 * 1024;
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: config.airdrops.csvMaxBytes },
});
}
};
}

const createAirdropLimit = buildRateLimit({
windowSeconds: config.airdrops.rateLimit.windowSeconds,
Expand Down Expand Up @@ -75,41 +75,6 @@ function isValidStellarAddress(address) {
}
}

function validateAirdropCreate(body, currentLedger) {
const { name, asset, asset_issuer, total_amount, expiry_ledger, recipients = [] } = body;

if (!name || typeof name !== 'string') {
return 'name is required and must be a string';
}
if (!asset || typeof asset !== 'string' || !/^[A-Z0-9]{1,12}$/i.test(asset)) {
return 'asset is required and must be 1-12 alphanumeric characters';
}
if (!asset_issuer || !isValidStellarAddress(asset_issuer)) {
return 'asset_issuer is required and must be a valid Stellar address';
}
if (typeof total_amount !== 'number' || total_amount <= 0) {
return 'total_amount is required and must be a positive number';
}
if (typeof expiry_ledger !== 'number' || expiry_ledger <= currentLedger) {
return `expiry_ledger is required and must be greater than current ledger (${currentLedger})`;
}
if (recipients.length > config.airdrops.maxRecipients) {
return 'recipients cannot exceed 10,000';
}

const recipientSet = new Set();
let sum = 0;
for (let i = 0; i < recipients.length; i++) {
const r = recipients[i];
if (!r.address || !isValidStellarAddress(r.address)) {
return `recipient ${i}: invalid Stellar address`;
}
if (recipientSet.has(r.address)) {
return `recipient ${i}: duplicate address ${r.address}`;
}
};
}

function parseRecipients(recipients, next) {
const result = recipientsSchema.safeParse(recipients);
if (!result.success) {
Expand Down Expand Up @@ -147,8 +112,7 @@ async function parseCSV(buffer) {
return results;
}

router.post('/airdrops', validateWithCurrentLedger(airdropCreateBodySchema), async (req, res, next) => {
router.post('/airdrops', createAirdropLimit, async (req, res, next) => {
router.post('/airdrops', createAirdropLimit, validateWithCurrentLedger(airdropCreateBodySchema), async (req, res, next) => {
try {
const airdrop = await airdropsService.create(req.validated.body);
return res.status(201).json(airdrop);
Expand Down Expand Up @@ -221,8 +185,7 @@ router.post('/airdrops/:id/cancel', validateRouteIdParams, async (req, res, next
}
});

router.post('/airdrops/:id/recipients', validateRouteIdParams, upload.single('file'), validateRecipientBody, async (req, res, next) => {
router.post('/airdrops/:id/recipients', addRecipientsLimit, uploadRecipientsFile, async (req, res, next) => {
router.post('/airdrops/:id/recipients', validateRouteIdParams, addRecipientsLimit, uploadRecipientsFile, validateRecipientBody, async (req, res, next) => {
try {
const airdrop = await airdropsService.get(req.params.id);
if (!airdrop) {
Expand Down
2 changes: 1 addition & 1 deletion src/routes/indexer.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ router.get('/airdrops/:id/status', async (req, res) => {
}
});

router.get('/airdrops/:id/recipients', async (req, res) => {
router.get('/airdrops/:id/onchain-recipients', async (req, res) => {
try {
if (!isValidId(req.params.id)) {
return res.status(400).json({ error: 'Invalid airdrop id' });
Expand Down
5 changes: 2 additions & 3 deletions src/services/priceOracle.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,14 @@ const SOURCES = [
name: 'coingecko',
fetch: coingecko.fetchPrice,
breaker: new CircuitBreaker('coingecko', breakerOptions),
getCircuitState: coingecko.getCircuitState,
},
{
name: 'coinmarketcap',
fetch: coinmarketcap.fetchPrice,
breaker: new CircuitBreaker('coinmarketcap', breakerOptions),
getCircuitState: coinmarketcap.getCircuitState,
},
{ name: 'stellar_dex', fetch: stellarDex.fetchPrice },
{ name: 'coingecko', fetch: coingecko.fetchPrice, getCircuitState: coingecko.getCircuitState },
{ name: 'coinmarketcap', fetch: coinmarketcap.fetchPrice, getCircuitState: coinmarketcap.getCircuitState },
];

/**
Expand Down
21 changes: 3 additions & 18 deletions test/airdrops.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

const mockStore = new Map();
const mockSets = new Map();
const mockSortedSets = new Map();
const mockZSets = new Map();
const mockLists = new Map();
const mockCounters = new Map();
Expand All @@ -17,20 +16,6 @@ const mockRedis = {
mockSets.get(key)?.delete(val);
}),
zadd: jest.fn(async (key, score, member) => {
if (!mockSortedSets.has(key)) mockSortedSets.set(key, new Map());
mockSortedSets.get(key).set(member, score);
}),
zrem: jest.fn(async (key, member) => {
mockSortedSets.get(key)?.delete(member);
}),
zcard: jest.fn(async (key) => mockSortedSets.get(key)?.size || 0),
zrevrange: jest.fn(async (key, start, stop) => {
const sortedSet = mockSortedSets.get(key);
if (!sortedSet) return [];
const entries = Array.from(sortedSet.entries()).sort((a, b) => b[1] - a[1]);
const startIdx = start === -1 ? entries.length + start : start;
const stopIdx = stop === -1 ? entries.length + stop : stop;
return entries.slice(startIdx, stopIdx + 1).map(([member]) => member);
if (!mockZSets.has(key)) mockZSets.set(key, new Map());
mockZSets.get(key).set(member, Number(score));
}),
Expand Down Expand Up @@ -118,6 +103,9 @@ jest.mock('stellar-sdk', () => ({
StrKey: {
isValidEd25519PublicKey: jest.fn((address) => address.startsWith('G') && address.length === 56),
},
SorobanRpc: {
Server: jest.fn(() => ({})),
},
}));

const request = require('supertest');
Expand All @@ -127,14 +115,11 @@ let app;

beforeAll(() => {
app = require('../src/index').app;
const { app: importedApp } = require('../src/index');
app = importedApp;
});

beforeEach(() => {
mockStore.clear();
mockSets.clear();
mockSortedSets.clear();
mockZSets.clear();
mockLists.clear();
mockCounters.clear();
Expand Down
17 changes: 0 additions & 17 deletions test/alerts-routes.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ process.env.ADMIN_API_KEY = adminApiKey;

const mockStore = new Map();
const mockSortedSets = new Map();
const mockZSets = new Map();

const mockRedis = {
smembers: jest.fn(async () => []),
Expand All @@ -25,22 +24,6 @@ const mockRedis = {
const stopIdx = stop === -1 ? entries.length + stop : stop;
return entries.slice(startIdx, stopIdx + 1).map(([member]) => member);
}),
if (!mockZSets.has(key)) mockZSets.set(key, new Map());
mockZSets.get(key).set(member, Number(score));
}),
zrem: jest.fn(async (key, ...members) => {
const z = mockZSets.get(key);
if (!z) return;
for (const m of members) z.delete(m);
}),
zrevrange: jest.fn(async (key, start, stop) => {
const z = mockZSets.get(key);
if (!z) return [];
const sorted = [...z.entries()].sort((a, b) => b[1] - a[1]).map(([m]) => m);
const end = stop === -1 ? sorted.length : stop + 1;
return sorted.slice(start, end);
}),
zcard: jest.fn(async (key) => (mockZSets.get(key)?.size || 0)),
};

jest.mock('../src/services/cache', () => ({
Expand Down
15 changes: 0 additions & 15 deletions test/auth.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ const crypto = require('crypto');
const mockStore = new Map();
const mockSets = new Map();
const mockSortedSets = new Map();
const mockZSets = new Map();

const mockRedis = {
smembers: jest.fn(async (key) => [...(mockSets.get(key) || [])]),
Expand All @@ -32,20 +31,6 @@ const mockRedis = {
const startIdx = start === -1 ? entries.length + start : start;
const stopIdx = stop === -1 ? entries.length + stop : stop;
return entries.slice(startIdx, stopIdx + 1).map(([member]) => member);
if (!mockZSets.has(key)) mockZSets.set(key, new Map());
mockZSets.get(key).set(member, Number(score));
}),
zrem: jest.fn(async (key, ...members) => {
const z = mockZSets.get(key);
if (!z) return;
for (const m of members) z.delete(m);
}),
zrevrange: jest.fn(async (key, start, stop) => {
const z = mockZSets.get(key);
if (!z) return [];
const sorted = [...z.entries()].sort((a, b) => b[1] - a[1]).map(([m]) => m);
const end = stop === -1 ? sorted.length : stop + 1;
return sorted.slice(start, end);
}),
};

Expand Down
Loading
Loading