Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve membersURI #812

Open
wants to merge 26 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
a386393
improve membersURI
Rashmi-278 Feb 26, 2024
3e5bf86
add limit, pagination and uniqueness check for members
Rashmi-278 Mar 6, 2024
231b6b3
updated approach, get all unique addresses from DB
Rashmi-278 Apr 22, 2024
b828ed3
remove angle brackets from context link
Rashmi-278 Apr 22, 2024
51c4294
add context
Rashmi-278 Apr 22, 2024
7ebe8c7
Update .gitignore
Rashmi-278 May 1, 2024
ac8669b
Update src/eip4824.ts
Rashmi-278 May 1, 2024
9d41dd3
lint
Rashmi-278 May 1, 2024
47e6eb0
requested changes
Rashmi-278 May 1, 2024
a35202b
Merge remote changes into improve-membersURI
Rashmi-278 May 1, 2024
458e794
remove pnpm
Rashmi-278 May 2, 2024
9849c0b
optimize query for speedy retrival
Rashmi-278 Jun 17, 2024
e342770
Exclude known addresses to optimize for speed
Rashmi-278 Jun 17, 2024
252acc3
remove comments
Rashmi-278 Jun 17, 2024
1df3050
Update src/helpers/spaces.ts
Rashmi-278 Jun 18, 2024
1da8ee9
Update src/helpers/spaces.ts
Rashmi-278 Jun 18, 2024
b2c10b8
cursor conditional
Rashmi-278 Jul 1, 2024
0ce6028
Merge branch 'snapshot-labs:master' into improve-membersURI
Rashmi-278 Jul 1, 2024
240ed25
apply changes
Rashmi-278 Jul 1, 2024
1cd13f3
apply changes
Rashmi-278 Jul 1, 2024
ad86432
cursor conditions
Rashmi-278 Jul 1, 2024
3ca9efa
query improved
Rashmi-278 Aug 21, 2024
560a182
Merge branch 'master' into improve-membersURI
Rashmi-278 Aug 21, 2024
d285d3b
Merge branch 'snapshot-labs:master' into improve-membersURI
Rashmi-278 Aug 21, 2024
f96bf1d
Update eip4824.ts
Rashmi-278 Aug 21, 2024
84d905e
lint
Rashmi-278 Aug 21, 2024
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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ coverage

# Remove some common IDE working directories
.idea
.vscode
.vscode
106 changes: 85 additions & 21 deletions src/eip4824.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import express from 'express';
import db, { sequencerDB } from './helpers/mysql';
import { getSpace } from './helpers/spaces';
import { getCombinedMembersAndVoters, getSpace } from './helpers/spaces';

const router = express.Router();
const context = '<http://www.daostar.org/schemas>';
const context = ['https://snapshot.org', 'https://daostar.org/schemas'];

router.get('/:space', async (req, res) => {
let space: any = {};
Expand Down Expand Up @@ -34,29 +34,93 @@ router.get('/:space', async (req, res) => {
});

router.get('/:space/members', async (req, res) => {
let space: any = {};

try {
space = await getSpace(req.params.space);
const spaceId = req.params.space;
const cursor = req.query.cursor || null;
const pageSize = 500; // Default page size

const space = await getSpace(spaceId);
if (!space.verified) {
return res.status(400).json({
error: 'INVALID_SPACE',
message: 'The specified space is not verified.'
});
}

if (!space.verified) return res.status(400).json({ error: 'INVALID' });
} catch (e) {
return res.status(404).json({ error: 'NOT_FOUND' });
}
let members: { type: string; id: string }[] = [];
let nextCursor: string | null = null;

if (cursor) {
const combinedMembersResult = await getCombinedMembersAndVoters(
spaceId,
cursor,
pageSize,
[],
[],
[]
);
members = combinedMembersResult.members.map(voter => ({
type: 'EthereumAddress',
id: voter
}));
nextCursor = combinedMembersResult.nextCursor;
} else {
const combinedMembersResult = await getCombinedMembersAndVoters(
spaceId,
cursor,
pageSize,
space.admins,
space.moderators,
space.members
);
members = [
...space.admins.map(admin => ({ type: 'EthereumAddress', id: admin })),
...space.moderators.map(moderator => ({
type: 'EthereumAddress',
id: moderator
})),
...space.members.map(member => ({
type: 'EthereumAddress',
id: member
})),
...combinedMembersResult.members.map(voter => ({
type: 'EthereumAddress',
id: voter
}))
];
nextCursor = combinedMembersResult.nextCursor;
}

const members = [...space.admins, ...space.moderators, ...space.members].map(
ChaituVR marked this conversation as resolved.
Show resolved Hide resolved
member => ({
type: 'EthereumAddress',
id: member
})
);
const responseObject = {
'@context': context,
type: 'DAO',
name: space.name,
members: members,
nextCursor: nextCursor
};

return res.json({
'@context': context,
type: 'DAO',
name: space.name,
members
});
return res.json(responseObject);
} catch (e) {
const error = e as Error;
console.error(error);

if (error.message.includes('database')) {
return res.status(500).json({
error: 'DATABASE_ERROR',
message: 'Failed to retrieve data from the database.'
});
} else if (error.message.includes('parameter')) {
return res.status(400).json({
error: 'INVALID_PARAMETER',
message: 'Invalid or missing parameter.'
});
} else {
return res.status(500).json({
error: 'INTERNAL_SERVER_ERROR',
message: 'An unexpected error occurred.'
});
}
}
});

router.get('/:space/proposals', async (req, res) => {
Expand Down
47 changes: 47 additions & 0 deletions src/helpers/spaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,53 @@ async function getVotes(): Promise<Record<string, { votesCount7d: number }>> {
);
}

export async function getCombinedMembersAndVoters(
spaceId: string,
cursor: string | null,
pageSize: number,
knownAdmins: string[] = [],
knownModerators: string[] = [],
knownMembers: string[] = []
) {
const params: (string | number)[] = [spaceId];
const exclusionList = [...knownAdmins, ...knownModerators, ...knownMembers];

// Other roles are already known and fetched at the app level while Space Verification
// Building the exclusion clause only if the exclusion list is not empty
let exclusionClause = '';
if (exclusionList.length > 0) {
const placeholders = exclusionList.map(() => '?').join(', ');
exclusionClause = `AND voter NOT IN (${placeholders})`;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't this be used to inject arbitrary SQL? I think placeholders should be added as params so it get parsed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think that would be of concern here because

  1. Placeholders values are not user input values
  2. Placeholder values are either empty lists or space.admins, space.moderators, space.members
  3. params.push(...exclusionList) This pushes the actual exclusion list values (the voters you want to exclude) into the params array, which is passed to the query execution.
  4. const results =await db.queryAsync(query, params); The database library takes care of escaping the values in params, preventing SQL injection.

params.push(...exclusionList);
}

const cursorClause = cursor ? ' AND voter > ?' : '';
if (cursor) {
params.push(cursor);
}

const query = `
SELECT DISTINCT voter AS address
FROM votes
WHERE space = ? ${exclusionClause} ${cursorClause}
ORDER BY voter
LIMIT ?
`;
params.push(pageSize);

const results = await db.queryAsync(query, params);
if (!results || results.length === 0) {
return Promise.reject(new Error('NOT_FOUND'));
}

const nextCursor =
results.length === pageSize ? results[results.length - 1].address : null;
return {
members: results.map(row => row.address),
nextCursor: nextCursor
};
}

async function getFollowers(): Promise<
Record<string, { followersCount7d: number }>
> {
Expand Down