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
14 changes: 14 additions & 0 deletions populate-script/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# General
yarn-error.log
node_modules
.DS_STORE
.vscode

# Config files
.env

# Avoid ignoring gitkeep
!/**/.gitkeep


batches.json
13 changes: 13 additions & 0 deletions populate-script/abis/L2Resolver.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[
{
"type": "function",
"name": "setRecords",
"stateMutability": "nonpayable",
"inputs": [
{ "name": "_nodes", "type": "bytes32[]" },
{ "name": "_keys", "type": "string[]" },
{ "name": "_values", "type": "bytes[]" }
],
"outputs": []
}
]
17 changes: 17 additions & 0 deletions populate-script/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "populate-script",
"version": "1.0.0",
"license": "MIT",
"main": "script.js",
"scripts": {
"populate": "ts-node script.ts",
"test": "vitest run"
},
"devDependencies": {
"@types/node": "24.3.0",
"ts-node": "10.9.2",
"typescript": "5.9.2",
"viem": "2.36.0",
"vitest": "3.2.4"
}
}
156 changes: 156 additions & 0 deletions populate-script/script.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import { writeFile } from 'node:fs/promises';
import { encodeAbiParameters, encodeFunctionData, Hex, hexToBytes, keccak256, namehash, numberToHex, stringToBytes, toHex } from 'viem';
import L2ResolverAbi from '../out/L2Resolver.sol/L2Resolver.json';

type ChainItem = {
name: string;
chainId: number;
subDomain: string;
shortName: string;
};

type BatchOutput = {
chainIds: number[];
forwardCalldata: Hex;
reverseCalldata: Hex;
};

const SOURCE_URL: string = "https://chainid.network/chains_mini.json";
const BATCH_SIZE: number = 10;
const L2_SUFFIX: string = '.l2.eth';
const CHAIN_IDENTIFIER_EIP7930_KEY: string = 'chain.id.eip7930';
const REVERSE_LOOKUP_NODE: Hex = keccak256(stringToBytes('reverse.chain.id.eip7930')) as Hex;

/**
* Processes a batch of chain items and returns the chainIds, forwardCalldata, and reverseCalldata for setRecords.
* @param batch - The batch of chain items to process.
* @returns The chainIds, forwardCalldata, and reverseCalldata.
*/
const processBatch = async (
batch: ChainItem[]
): Promise<[number[], Hex, Hex]> => {
const forwardNodes: Hex[] = [];
const forwardKeys: string[] = [];
const forwardValues: Hex[] = [];

const reverseNodes: Hex[] = [];
const reverseKeys: string[] = [];
const reverseValues: Hex[] = [];

const chainIds: number[] = [];

for (const item of batch) {
const subDomain = item.subDomain || item.shortName || item.name; // TODO: Review this
const domain = `${subDomain}${L2_SUFFIX}`.toLowerCase();

chainIds.push(item.chainId);

const nodeNamehash = namehash(domain);
const chainIdBytes = encodeEIP7930ChainIdBytes(item.chainId);

forwardNodes.push(nodeNamehash);
forwardKeys.push(CHAIN_IDENTIFIER_EIP7930_KEY);
forwardValues.push(chainIdBytes);

const identifierHash = keccak256(chainIdBytes);
const reverseKey = `${CHAIN_IDENTIFIER_EIP7930_KEY}${identifierHash}`;
const encodedDomain = encodeAbiParameters([{ type: 'string' }], [domain]);

reverseNodes.push(REVERSE_LOOKUP_NODE);
reverseKeys.push(reverseKey);
reverseValues.push(encodedDomain);
}

const forwardCalldata = encodeFunctionData({
abi: L2ResolverAbi.abi,
functionName: 'setRecords',
args: [forwardNodes, forwardKeys, forwardValues],
});

const reverseCalldata = encodeFunctionData({
abi: L2ResolverAbi.abi,
functionName: 'setRecords',
args: [reverseNodes, reverseKeys, reverseValues],
});

return [chainIds, forwardCalldata, reverseCalldata];
};

const fetchChains = async (): Promise<ChainItem[]> => {
const response = await fetch(SOURCE_URL);
if (!response.ok) {
throw new Error(`Failed to fetch chains: ${response.status} ${response.statusText}`);
}
return (await response.json()) as ChainItem[];
};

const filteredChainItem = (item: ChainItem): ChainItem => {
return {
name: item.name,
chainId: item.chainId,
subDomain: item.subDomain || '',
shortName: item.shortName,
};
};

const chunkArray = <ChainItem>(items: ChainItem[], chunkSize: number): ChainItem[][] => {
const chunks: ChainItem[][] = [];
for (let i = 0; i < items.length; i += chunkSize) {
chunks.push(items.slice(i, i + chunkSize));
}
return chunks;
};

/**
* Encodes the chainId to the bytes format required by EIP-7930.
* Encodes those with:
* "parent": { "type": "L2", "chain": "eip155-1", ... }
* @param chainId - The chainId to encode.
* @returns The encoded bytes.
*/
const encodeEIP7930ChainIdBytes = (chainId: number): Hex => {
const version = Uint8Array.of(0x00, 0x01);
const chainType = Uint8Array.of(0x00, 0x00);
const chainRef = hexToBytes(numberToHex(chainId));
const chainRefLength = Uint8Array.of(chainRef.length);
const addressLength = Uint8Array.of(0x00);

const bytes = new Uint8Array(version.length + chainType.length + chainRefLength.length + chainRef.length + addressLength.length);
bytes.set(version, 0);
bytes.set(chainType, 2);
bytes.set(chainRefLength, 4);
bytes.set(chainRef, 5);
bytes.set(addressLength, 5 + chainRef.length);

return toHex(bytes);
}

/**
* Main function to fetch chains, filter them, and process them in batches.
* Writes the outputs to batches.json.
*/
const main = async (): Promise<void> => {
const chains: ChainItem[] = await fetchChains();
const records: ChainItem[] = chains.map(filteredChainItem);
const batches: ChainItem[][] = chunkArray(records, BATCH_SIZE);

const outputs: BatchOutput[] = [];
for (const batch of batches) {
const [chainIds, forwardCalldata, reverseCalldata] = await processBatch(batch);
outputs.push({ chainIds, forwardCalldata, reverseCalldata });
}

await writeFile(
'batches.json',
JSON.stringify(outputs, null, 2),
'utf8'
);
};

main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

export { encodeEIP7930ChainIdBytes, processBatch };

30 changes: 30 additions & 0 deletions populate-script/test/script.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest';
import { encodeEIP7930ChainIdBytes, processBatch } from '../script';

describe('processBatch', () => {
it('returns chainIds and encodes forward/reverse calldata', async () => {
const batch = [
{ name: 'OP Mainnet', chainId: 10, subDomain: 'optimism', shortName: 'oeth' },
{ name: 'Arbitrum One', chainId: 42161, subDomain: 'arbitrum', shortName: 'arb1' },
];

const [ids, forward, reverse] = await processBatch(batch);
expect(ids).toEqual([10, 42161]);
expect(forward.startsWith('0x')).toBe(true);
expect(reverse.startsWith('0x')).toBe(true);
});
});

describe('encodeEIP7930ChainIdBytes', () => {
it('encodes optimism chainId to bytes', async () => {
const chainId = 10;
const bytes = encodeEIP7930ChainIdBytes(chainId);
expect(bytes).toEqual('0x00010000010a00');
});

it('encodes arbitrum chainId to bytes', async () => {
const chainId = 42161;
const bytes = encodeEIP7930ChainIdBytes(chainId);
expect(bytes).toEqual('0x0001000002a4b100');
});
});
10 changes: 10 additions & 0 deletions populate-script/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"resolveJsonModule": true
}
}
Loading
Loading