Skip to content

Commit

Permalink
used subgraph to get total count of entities instead of onchain function
Browse files Browse the repository at this point in the history
  • Loading branch information
satyajeetkolhapure committed Nov 11, 2024
1 parent e56a25f commit 7a398dd
Show file tree
Hide file tree
Showing 14 changed files with 70 additions and 153 deletions.
10 changes: 0 additions & 10 deletions contracts/src/ModuleRegistry.sol
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@ contract ModuleRegistry is OwnableUpgradeable {
if (bytes(modules[moduleAddress].name).length > 0) revert ModuleAlreadyExists();

modules[moduleAddress] = Module(moduleAddress, name, description);
moduleAddresses.push(moduleAddress);
emit ModuleRegistered(name, description, moduleAddress);
}

Expand Down Expand Up @@ -239,15 +238,6 @@ contract ModuleRegistry is OwnableUpgradeable {
}
}

/**
* @notice Get the number of Modules managed by the contract
* @return The number of Modules already registered
* @dev Returns the length of the `moduleAddresses` array
*/
function getModulesNumber() public view returns (uint256) {
return moduleAddresses.length;
}

/**
* @notice Checks that a module is registered in the module registry
* @param moduleAddress The address of the Module to check
Expand Down
29 changes: 1 addition & 28 deletions contracts/src/PortalRegistry.sol
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@ contract PortalRegistry is OwnableUpgradeable {
// Add portal to mapping
Portal memory newPortal = Portal(id, msg.sender, modules, isRevocable, name, description, ownerName);
portals[id] = newPortal;
portalAddresses.push(id);

// Emit event
emit PortalRegistered(name, description, id);
Expand All @@ -184,24 +183,7 @@ contract PortalRegistry is OwnableUpgradeable {
function revoke(address id) public onlyOwner {
if (!isRegistered(id)) revert PortalNotRegistered();

portals[id] = Portal(address(0), address(0), new address[](0), false, "", "", "");

bool found = false;
uint256 portalAddressIndex;
for (uint256 i = 0; i < portalAddresses.length; i = uncheckedInc256(i)) {
if (portalAddresses[i] == id) {
portalAddressIndex = i;
found = true;
break;
}
}

if (!found) {
revert PortalNotRegistered();
}

portalAddresses[portalAddressIndex] = portalAddresses[portalAddresses.length - 1];
portalAddresses.pop();
delete portals[id];

emit PortalRevoked(id);
}
Expand Down Expand Up @@ -243,15 +225,6 @@ contract PortalRegistry is OwnableUpgradeable {
return portals[id].id != address(0);
}

/**
* @notice Get the number of Portals managed by the contract
* @return The number of Portals already registered
* @dev Returns the length of the `portalAddresses` array
*/
function getPortalsCount() public view returns (uint256) {
return portalAddresses.length;
}

/**
* @notice Checks if the caller is allowlisted.
* @return A flag indicating whether the Verax instance is running on testnet
Expand Down
10 changes: 0 additions & 10 deletions contracts/src/SchemaRegistry.sol
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@ contract SchemaRegistry is OwnableUpgradeable {
}

schemas[schemaId] = Schema(name, description, context, schemaString);
schemaIds.push(schemaId);
schemasIssuers[schemaId] = msg.sender;
emit SchemaCreated(schemaId, name, description, context, schemaString);
}
Expand Down Expand Up @@ -184,15 +183,6 @@ contract SchemaRegistry is OwnableUpgradeable {
return schemas[schemaId];
}

/**
* @notice Get the number of Schemas managed by the contract
* @return The number of Schemas already registered
* @dev Returns the length of the `schemaIds` array
*/
function getSchemasNumber() public view returns (uint256) {
return schemaIds.length;
}

/**
* @notice Check if a Schema is registered
* @param schemaId The ID of the Schema
Expand Down
18 changes: 0 additions & 18 deletions contracts/test/ModuleRegistry.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -132,16 +132,6 @@ contract ModuleRegistryTest is Test {
moduleRegistry.register(expectedName, expectedDescription, expectedAddress);
}

function test_getModulesNumber() public {
uint256 modulesNumber = moduleRegistry.getModulesNumber();
assertEq(modulesNumber, 0);
vm.prank(user);
moduleRegistry.register(expectedName, expectedDescription, expectedAddress);

modulesNumber = moduleRegistry.getModulesNumber();
assertEq(modulesNumber, 1);
}

function test_runModules() public {
// Register 2 modules
address[] memory moduleAddresses = new address[](2);
Expand Down Expand Up @@ -343,14 +333,6 @@ contract ModuleRegistryTest is Test {
vm.stopPrank();
}

function test_getModuleAddress() public {
vm.prank(user);
moduleRegistry.register(expectedName, expectedDescription, expectedAddress);

address moduleAddress = moduleRegistry.moduleAddresses(0);
assertEq(moduleAddress, expectedAddress);
}

function test_isRegistered() public {
bool isRegistered = moduleRegistry.isRegistered(expectedAddress);
assertFalse(isRegistered);
Expand Down
16 changes: 8 additions & 8 deletions contracts/test/PortalRegistry.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ contract PortalRegistryTest is Test {
vm.prank(user);
portalRegistry.register(address(validPortalMock), expectedName, expectedDescription, true, expectedOwnerName);

uint256 portalCount = portalRegistry.getPortalsCount();
assertEq(portalCount, 1);
bool isRegistered = portalRegistry.isRegistered(address(validPortalMock));
assertEq(isRegistered, true);

// Register a portal implementing IPortal
vm.expectEmit();
Expand All @@ -194,8 +194,8 @@ contract PortalRegistryTest is Test {
expectedOwnerName
);

portalCount = portalRegistry.getPortalsCount();
assertEq(portalCount, 2);
isRegistered = portalRegistry.isRegistered(address(iPortalImplementation));
assertEq(isRegistered, true);

Portal memory expectedPortal = Portal(
address(validPortalMock),
Expand Down Expand Up @@ -272,8 +272,8 @@ contract PortalRegistryTest is Test {
expectedOwnerName
);

uint256 portalCount = portalRegistry.getPortalsCount();
assertEq(portalCount, 1);
bool isRegistered = portalRegistry.isRegistered(portalAddress);
assertEq(isRegistered, true);

Portal memory expectedPortal = Portal(
portalAddress,
Expand All @@ -292,8 +292,8 @@ contract PortalRegistryTest is Test {
emit PortalRevoked(portalAddress);
portalRegistry.revoke(portalAddress);

portalCount = portalRegistry.getPortalsCount();
assertEq(portalCount, 0);
isRegistered = portalRegistry.isRegistered(portalAddress);
assertEq(isRegistered, false);

vm.expectRevert(PortalRegistry.PortalNotRegistered.selector);
portalRegistry.getPortalByAddress(portalAddress);
Expand Down
20 changes: 0 additions & 20 deletions contracts/test/SchemaRegistry.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -220,26 +220,6 @@ contract SchemaRegistryTest is Test {
schemaRegistry.getSchema(bytes32("not registered"));
}

function test_getSchemasNumber() public {
uint256 schemasNumber = schemaRegistry.getSchemasNumber();
assertEq(schemasNumber, 0);
vm.startPrank(user);
schemaRegistry.createSchema(expectedName, expectedDescription, expectedContext, expectedString);

schemasNumber = schemaRegistry.getSchemasNumber();
assertEq(schemasNumber, 1);
vm.stopPrank();
}

function test_getSchemaIds() public {
vm.startPrank(user);
schemaRegistry.createSchema(expectedName, expectedDescription, expectedContext, expectedString);

bytes32 schemaId = schemaRegistry.schemaIds(0);
assertEq(schemaId, expectedId);
vm.stopPrank();
}

function test_isRegistered() public {
bool isRegistered = schemaRegistry.isRegistered(expectedId);
assertFalse(isRegistered);
Expand Down
13 changes: 0 additions & 13 deletions sdk/src/abi/ModuleRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,19 +151,6 @@ export const abiModuleRegistry = [
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [],
name: "getModulesNumber",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "initialize",
Expand Down
13 changes: 0 additions & 13 deletions sdk/src/abi/PortalRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,19 +195,6 @@ export const abiPortalRegistry = [
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "getPortalsCount",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "initialize",
Expand Down
13 changes: 0 additions & 13 deletions sdk/src/abi/SchemaRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,19 +191,6 @@ export const abiSchemaRegistry = [
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "getSchemasNumber",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "initialize",
Expand Down
31 changes: 31 additions & 0 deletions sdk/src/dataMapper/BaseDataMapper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,35 @@ describe("BaseDataMapper", () => {
await expect(mockDataMapper.findBy()).rejects.toThrow("Error(s) while fetching TestTypes");
});
});

describe("findTotalCount", () => {
it("should call subgraphCall with the correct query and return the result", async () => {
const mockResponse = { data: { data: { counters: [{ TestTypes: 4 }] } }, status: 200 };
(subgraphCall as jest.Mock).mockResolvedValueOnce(mockResponse);

const result = await mockDataMapper.findTotalCount();

expect(subgraphCall).toHaveBeenCalledWith(
`query get_TestType_Counter { counters { TestTypes } }`,
mockConf.subgraphUrl,
);
expect(result).toEqual(4);
});

it("should throw an error if the status is not 200", async () => {
const mockResponse = { status: 500 };
(subgraphCall as jest.Mock).mockResolvedValueOnce(mockResponse);

await expect(mockDataMapper.findTotalCount()).rejects.toThrow("Error(s) while fetching total count of TestTypes");
});

it("should return 0 if no data is found", async () => {
const mockResponse = { data: null, status: 200 };
(subgraphCall as jest.Mock).mockResolvedValueOnce(mockResponse);

const result = await mockDataMapper.findTotalCount();

expect(result).toEqual(0);
});
});
});
12 changes: 12 additions & 0 deletions sdk/src/dataMapper/BaseDataMapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,16 @@ export default abstract class BaseDataMapper<T, TFilter, TOrder> {

return data?.data ? (data.data[`${this.typeName}s`] as T[]) : [];
}

async findTotalCount() {
const query = `query get_${this.typeName}_Counter { counters { ${this.typeName}s } }`;

const { data, status } = await subgraphCall(query, this.conf.subgraphUrl);

if (status != 200) {
throw new Error(`Error(s) while fetching total count of ${this.typeName}s`);
}

return data?.data ? data.data["counters"][0][`${this.typeName}s`] : 0;
}
}
2 changes: 1 addition & 1 deletion sdk/src/dataMapper/ModuleDataMapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export default class ModuleDataMapper extends BaseDataMapper<Module, Module_filt
}

async getModulesNumber() {
return await this.executeReadMethod("getModulesNumber", []);
return await super.findTotalCount();
}

async isRegistered(moduleAddress: Address) {
Expand Down
2 changes: 1 addition & 1 deletion sdk/src/dataMapper/SchemaDataMapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export default class SchemaDataMapper extends BaseDataMapper<Schema, Schema_filt
}

async getSchemasNumber() {
return this.executeReadMethod("getSchemasNumber", []);
return await super.findTotalCount();
}

async isRegistered(schemaId: string) {
Expand Down
34 changes: 16 additions & 18 deletions sdk/src/dataMapper/UtilsDataMapper.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import BaseDataMapper from "./BaseDataMapper";
import { abiAttestationRegistry } from "../abi/AttestationRegistry";
import { abiModuleRegistry } from "../abi/ModuleRegistry";
import { abiPortalRegistry } from "../abi/PortalRegistry";
import { abiSchemaRegistry } from "../abi/SchemaRegistry";
import { decode, encode } from "../utils/abiCoder";
import { Hex } from "viem";
import { subgraphCall } from "../utils/graphClientHelper";

export default class UtilsDataMapper extends BaseDataMapper<object, unknown, unknown> {
typeName = "counter";
Expand All @@ -16,27 +14,15 @@ export default class UtilsDataMapper extends BaseDataMapper<object, unknown, unk
}`;

async getModulesNumber() {
return this.web3Client.readContract({
abi: abiModuleRegistry,
address: this.conf.moduleRegistryAddress,
functionName: "getModulesNumber",
});
return await this.getCounterForType("module");
}

async getPortalsCount() {
return this.web3Client.readContract({
abi: abiPortalRegistry,
address: this.conf.portalRegistryAddress,
functionName: "getPortalsCount",
});
return await this.getCounterForType("portal");
}

async getSchemasNumber() {
return this.web3Client.readContract({
abi: abiSchemaRegistry,
address: this.conf.schemaRegistryAddress,
functionName: "getSchemasNumber",
});
return await this.getCounterForType("schema");
}

async getVersionNumber() {
Expand All @@ -62,4 +48,16 @@ export default class UtilsDataMapper extends BaseDataMapper<object, unknown, unk
decode(schema: string, attestationData: Hex): readonly unknown[] {
return decode(schema, attestationData);
}

private async getCounterForType(type: string) {
const query = `query get_${type}_counter { counters { ${type}s } }`;

const { data, status } = await subgraphCall(query, this.conf.subgraphUrl);

if (status != 200) {
throw new Error(`Error(s) while fetching total count of ${type}s`);
}

return data?.data ? data.data["counters"][0][`${type}s`] : 0;
}
}

0 comments on commit 7a398dd

Please sign in to comment.