Skip to content
Merged
Changes from 1 commit
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
54 changes: 53 additions & 1 deletion src/registry/erc8004.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,8 @@ export async function queryAgent(

/**
* Get the total number of registered agents.
* Tries totalSupply() first; if that reverts (proxy contracts without
* ERC-721 Enumerable), falls back to a binary search on ownerOf().
*/
export async function getTotalAgents(
network: Network = "mainnet",
Expand All @@ -471,10 +473,60 @@ export async function getTotalAgents(
});
return Number(supply);
} catch {
return 0;
// totalSupply() reverted — proxy may lack ERC-721 Enumerable.
// Binary search for the highest minted tokenId via ownerOf().
return estimateTotalByBinarySearch(publicClient, contracts.identity);
}
}

/**
* Estimate total minted tokens by binary-searching ownerOf().
* Token IDs are sequential starting from 1, so the highest existing
* tokenId equals the total minted count.
*/
async function estimateTotalByBinarySearch(
client: { readContract: (args: any) => Promise<any> },
contractAddress: Address,
): Promise<number> {
const exists = async (id: number): Promise<boolean> => {
try {
await client.readContract({
address: contractAddress,
abi: IDENTITY_ABI,
functionName: "ownerOf",
args: [BigInt(id)],
});
return true;
} catch {
return false;
}
};

// Quick probe to find an upper bound
let upper = 1024;
while (await exists(upper)) {
upper *= 2;
if (upper > 10_000_000) break; // safety cap
}

// Binary search between upper/2 and upper
let lo = Math.floor(upper / 2);
let hi = upper;
while (lo < hi) {
const mid = Math.floor((lo + hi + 1) / 2);
if (await exists(mid)) {
lo = mid;
} else {
hi = mid - 1;
}
}

if (lo > 0) {
logger.info(`Binary search estimated total agents: ${lo}`);
}
return lo;
}

/**
* Discover registered agents by scanning Transfer mint events.
* Fallback for contracts that don't implement totalSupply (ERC-721 Enumerable).
Expand Down
Loading