Skip to content

Commit

Permalink
Implement no-magic-numbers linter rule
Browse files Browse the repository at this point in the history
  • Loading branch information
LogvinovLeon committed Feb 29, 2024
1 parent bef5e97 commit 47b8ea4
Show file tree
Hide file tree
Showing 12 changed files with 543 additions and 505 deletions.
9 changes: 8 additions & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ module.exports = {
assertionStyle: 'as',
objectLiteralTypeAssertions: 'allow'
}
]
],
'no-magic-numbers': ['error', { ignore: [0, 1, 16, 256, '0n', '1n'] }]
},
overrides: [
{
Expand All @@ -25,6 +26,12 @@ module.exports = {
parserOptions: {
sourceType: 'script'
}
},
{
files: ['*.test.ts'],
rules: {
'no-magic-numbers': 'off'
}
}
]
};
986 changes: 498 additions & 488 deletions .pnp.cjs

Large diffs are not rendered by default.

Binary file modified .yarn/install-state.gz
Binary file not shown.
1 change: 1 addition & 0 deletions ethereum_history_api/oracles/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@noir-lang/noir_js": "0.23.0",
"dotenv": "^16.3.1",
"fastify": "^4.25.2",
"http-status-codes": "^2.3.0",
"json-bigint": "^1.0.0",
"json-rpc-2.0": "^1.7.0",
"lodash.isequal": "^4.5.0",
Expand Down
8 changes: 5 additions & 3 deletions ethereum_history_api/oracles/src/noir/noir_js/encode.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { isHex } from 'viem';

const BYTE_HEX_LENGTH = 2;

// ENCODERS
export function encodeHexString(value: string): Uint8Array {
if (!isHex(value)) {
throw new Error(`Invalid hexstring: ${value}`);
}
const arr = [];
for (let i = 2; i < value.length; i += 2) {
arr.push(parseInt(value.substr(i, 2), 16));
for (let i = 2; i < value.length; i += BYTE_HEX_LENGTH) {
arr.push(parseInt(value.substr(i, BYTE_HEX_LENGTH), 16));
}
return new Uint8Array(arr);
}
Expand All @@ -17,7 +19,7 @@ export function decodeHexString(proof: Uint8Array): string {
return (
'0x' +
Array.from(proof)
.map((byte) => byte.toString(16).padStart(2, '0'))
.map((byte) => byte.toString(16).padStart(BYTE_HEX_LENGTH, '0'))
.join('')
);
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type ForeignCallOutput } from '@noir-lang/noir_js';
import { fromRlp, type GetProofReturnType, type Hex, isHex, type PublicClient } from 'viem';
import { assert } from '../../util/assert.js';
import { decodeField, decodeHexAddress, encodeField, encodeHex } from './encode.js';
import { ADDRESS_LENGTH, decodeField, decodeHexAddress, encodeField, encodeHex } from './encode.js';
import { padArray } from '../../util/array.js';
import { NoirArguments } from './oracles.js';

Expand All @@ -11,6 +11,7 @@ const PROOF_LENGTH = PROOF_ONE_LEVEL_LENGTH * MAX_PROOF_LEVELS;
const MAX_ACCOUNT_STATE_LENGTH = 134;
const ZERO_PAD_VALUE = '0x0';
const RLP_VALUE_INDEX = 1;
const GET_ACCOUNT_ARGS_COUNT = 2;

export const getAccountOracle = async (client: PublicClient, args: NoirArguments): Promise<ForeignCallOutput[]> => {
const { blockNumber, address } = parseNoirGetAccountArguments(args);
Expand All @@ -28,14 +29,14 @@ export function parseNoirGetAccountArguments(args: NoirArguments): {
blockNumber: bigint;
address: Hex;
} {
assert(args.length === 2, 'get_account requires 2 arguments');
assert(args.length === GET_ACCOUNT_ARGS_COUNT, 'get_account requires 2 arguments');

const [noirBlockNumber, noirAddress] = args;

assert(noirBlockNumber.length === 1, 'get_account first argument must be an array of length 1');
assert(isHex(noirBlockNumber[0]), 'get_account first argument must be a hex value');

assert(noirAddress.length === 20, 'get_account second argument must be an address');
assert(noirAddress.length === ADDRESS_LENGTH, 'get_account second argument must be an address');
assert(
noirAddress.every((it) => isHex(it)),
'get_account second argument must be an array of hex string values'
Expand Down
21 changes: 13 additions & 8 deletions ethereum_history_api/oracles/src/noir/oracles/encode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ import { type Address, isAddress, isHex } from 'viem';
import { assert } from '../../util/assert.js';

export const MODULUS = 21888242871839275222246405745257275088696311157297823662689037894645226208583n;
const BYTE_HEX_LENGTH = 2;
const BYTES32_LENGTH = 32;
export const ADDRESS_LENGTH = 20;
const BITS_IN_BYTE = 8n;
const MAX_U8 = 255;

// ENCODERS
export function encodeField(arg: number | bigint): string {
Expand All @@ -11,7 +16,7 @@ export function encodeField(arg: number | bigint): string {
}

export function encodeBytes32(value: bigint): string[] {
return encodeBytes(value, 32);
return encodeBytes(value, BYTES32_LENGTH);
}

export function encodeAddress(value: Address): string[] {
Expand All @@ -21,8 +26,8 @@ export function encodeAddress(value: Address): string[] {

export function encodeBytes(value: bigint, length: number): string[] {
assert(value >= 0n, 'Invalid Bytes32: Negative');
assert(value < 1n << (8n * BigInt(length)), 'Invalid Bytes32: Overflow');
const hexValue = value.toString(16).padStart(length * 2, '0');
assert(value < 1n << (BITS_IN_BYTE * BigInt(length)), 'Invalid Bytes32: Overflow');
const hexValue = value.toString(16).padStart(length * BYTE_HEX_LENGTH, '0');
return encodeHex(`0x${hexValue}`);
}

Expand All @@ -31,26 +36,26 @@ export function encodeHex(hexString: string): string[] {
throw new Error(`Invalid hexstring: ${hexString}`);
}
const chunks = [];
for (let i = 2; i < hexString.length; i += 2) {
const chunk = hexString.substring(i, i + 2);
for (let i = BYTE_HEX_LENGTH; i < hexString.length; i += BYTE_HEX_LENGTH) {
const chunk = hexString.substring(i, i + BYTE_HEX_LENGTH);
chunks.push(`0x${chunk[0] === '0' ? chunk[1] : chunk}`);
}
return chunks;
}

// DECODERS
export function decodeHexAddress(arg: string[]): Address {
assert(arg.length === 20, `Invalid address length: ${arg.length}`);
assert(arg.length === ADDRESS_LENGTH, `Invalid address length: ${arg.length}`);
for (const e of arg) {
const d = parseInt(e, 16);
assert(0 <= d && d <= 255 && isHex(e), `Invalid address, with byte: ${e}`);
assert(0 <= d && d <= MAX_U8 && isHex(e), `Invalid address, with byte: ${e}`);
}

const result =
'0x' +
arg
.map((e) => parseInt(e, 16))
.map((e) => e.toString(16).padStart(2, '0'))
.map((e) => e.toString(16).padStart(BYTE_HEX_LENGTH, '0'))
.join('');

assert(isAddress(result), `Invalid address: ${result}`);
Expand Down
3 changes: 2 additions & 1 deletion ethereum_history_api/oracles/src/noir/oracles/server/app.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { JSONRPCRequest, JSONRPCServer, TypedJSONRPCServer } from 'json-rpc-2.0';
import Fastify from 'fastify';
import { StatusCodes } from 'http-status-codes';
import http from 'http';
import { getHeaderHandler, getAccountHandler, JSONRPCServerMethods, ServerParams } from './handlers.js';
import { createDefaultClient } from '../../../ethereum/client.js';
Expand All @@ -24,7 +25,7 @@ export function buildOracleServer(
if (jsonRPCResponse) {
reply.send(jsonRPCResponse);
} else {
reply.status(204).send();
reply.status(StatusCodes.NO_CONTENT).send();
}
});
});
Expand Down
1 change: 1 addition & 0 deletions ethereum_history_api/oracles/src/script/encodeHeader.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-magic-numbers */
import { blockHeaders } from '../../fixtures/blockHeader.json';
import { assert } from '../util/assert.js';
import { type BlockHeader } from '../ethereum/blockHeader.js';
Expand Down
1 change: 1 addition & 0 deletions ethereum_history_api/oracles/src/script/fetchBlocks.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-magic-numbers */
import { createDefaultClient } from '../ethereum/client.js';
import { writeFile } from 'fs/promises';
import { stringify } from '../util/json-bigint.js';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { GetBlockReturnType } from 'viem';
import { encodeHexString } from '../../noir/noir_js/encode.js';
import { blockToHeader, headerToRlp } from '../../ethereum/blockHeader.js';
import { padArray } from '../../util/array.js';
import { MAX_HEADER_RLP_SIZE } from '../../noir/oracles/headerOracle.js';

export function createHeaderFixture(block: GetBlockReturnType): string {
const blockHash = encodeHexString(block.hash);
Expand All @@ -12,7 +13,7 @@ export function createHeaderFixture(block: GetBlockReturnType): string {
const header = blockToHeader(block);
const headerHex = headerToRlp(header);
const headerUint8Array = encodeHexString(headerHex);
const headerData = JSON.stringify(padArray(Array.from(headerUint8Array), 708, 0));
const headerData = JSON.stringify(padArray(Array.from(headerUint8Array), MAX_HEADER_RLP_SIZE, 0));

const headerFixture = `use crate::header::{BlockHeaderPartial, BlockHeaderRlp};
Expand Down
8 changes: 8 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2563,6 +2563,13 @@ __metadata:
languageName: node
linkType: hard

"http-status-codes@npm:^2.3.0":
version: 2.3.0
resolution: "http-status-codes@npm:2.3.0"
checksum: 10c0/c2412188929e8eed6623eef468c62d0c3c082919c03e9b74fd79cfd060d11783dba44603e38a3cee52d26563fe32005913eaf6120aa8ba907da1238f3eaad5fe
languageName: node
linkType: hard

"https-proxy-agent@npm:^7.0.1":
version: 7.0.3
resolution: "https-proxy-agent@npm:7.0.3"
Expand Down Expand Up @@ -3359,6 +3366,7 @@ __metadata:
dotenv: "npm:^16.3.1"
eslint: "npm:^8.56.0"
fastify: "npm:^4.25.2"
http-status-codes: "npm:^2.3.0"
json-bigint: "npm:^1.0.0"
json-rpc-2.0: "npm:^1.7.0"
lodash.isequal: "npm:^4.5.0"
Expand Down

0 comments on commit 47b8ea4

Please sign in to comment.