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

Add contract address calculator based on from and nonce #95

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@ethereumjs/common": "^2.6.3",
"@ethereumjs/tx": "^3.5.1",
"@ethersproject/abi": "^5.6.0",
"@ethersproject/address": "^5.6.0",
"@ethersproject/bignumber": "^5.5.0",
"@ethersproject/logger": "^5.6.0",
"@ethersproject/strings": "5.0.0",
Expand Down
106 changes: 106 additions & 0 deletions pages/contract-address-calculator/index.page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import React, { ReactElement, useState } from 'react';

import { CopyableConversionInput } from '../../src/components/CopyableConversionInput';
import { CalculatorIcon } from '../../src/components/icons/CalculatorIcon';
import { Button } from '../../src/components/lib/Button';
import { Header } from '../../src/components/lib/Header';
import { NodeBlock } from '../../src/components/lib/NodeBlock';
import { ToolContainer } from '../../src/components/ToolContainer';
import { getContractAddress } from '../../src/lib/contractAddress';
import { handleChangeValidated } from '../../src/misc/handleChangeValidated';
import { WithError } from '../../src/misc/types';
import { addressValidator } from '../../src/misc/validation/validators/addressValidator';
import { numberValidator } from '../../src/misc/validation/validators/numberValidator';

export default function ContractAddressCalculator(): ReactElement {
const [fromAddress, setFromAddress] = useState<WithError<string>>({
value: '',
});
const [nonce, setNonce] = useState<WithError<string>>({
value: '',
});

const [calculatedContractAddress, setCalculatedContractAddress] = useState<
string | undefined
>();

function flushResults(): void {
setCalculatedContractAddress(undefined);
}

function handleChangeFromAddress(newValue: string): void {
handleChangeValidated({
newValue,
validateFn: (newValue) => addressValidator(newValue),
setState: setFromAddress,
flushFn: flushResults,
});
}

function handleChangeNonce(newValue: string): void {
handleChangeValidated({
newValue,
validateFn: (newValue) => numberValidator(newValue),
setState: setNonce,
flushFn: flushResults,
});
}

function handleCalculateContractAddress(): void {
try {
setCalculatedContractAddress(
getContractAddress({
from: fromAddress.value,
nonce: nonce.value,
}),
);
} catch {
flushResults();
}
}

const calculateButtonIsDisabled = Boolean(
!fromAddress.value || fromAddress.error || !nonce.value || nonce.error,
);

return (
<ToolContainer>
<form className="flex w-full flex-col items-start sm:mr-auto sm:items-center md:items-start">
<Header
icon={<CalculatorIcon height={24} width={24} />}
text={['Calculators', 'Contract Address Calculator']}
/>
<section className="flex w-full flex-col gap-5">
<CopyableConversionInput
name="From"
value={fromAddress.value}
error={fromAddress.error}
placeholder="0x0.."
onChange={(event) => handleChangeFromAddress(event.target.value)}
/>
<CopyableConversionInput
name="Nonce"
value={nonce.value}
error={nonce.error}
onChange={(event) => handleChangeNonce(event.target.value)}
/>
</section>
</form>
<Button
title="Calculate"
className="mt-6"
disabled={calculateButtonIsDisabled}
onClick={handleCalculateContractAddress}
>
Calculate
</Button>
{calculatedContractAddress && (
<section className="mt-10 rounded-md border border-gray-600 bg-gray-900 p-8">
<NodeBlock toggle={false} str={calculatedContractAddress}>
Contract address:
</NodeBlock>
</section>
)}
</ToolContainer>
);
}
5 changes: 4 additions & 1 deletion pages/vanity-address-generator/index.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,10 @@ export default function VanityAddressGenerator(): ReactElement {
const handleChangeCpuCoreCount = (newValue: string): void =>
handleChangeValidated({
newValue,
validateFn: (newValue) => numberValidator(newValue),
validateFn: (newValue) =>
7sne marked this conversation as resolved.
Show resolved Hide resolved
numberValidator(newValue, (schema) =>
schema.refine((n) => n >= 0 && n <= 128),
),
setState: setCpuCores,
flushFn: flushResults,
});
Expand Down
4 changes: 4 additions & 0 deletions src/components/ToolTree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ const tree: Tree = {
title: 'String Bytes32 Conversion',
pageHref: 'string-bytes32-conversion',
},
{
title: 'Contract Address Calculator',
pageHref: 'contract-address-calculator',
},
],
},
decoders: {
Expand Down
14 changes: 14 additions & 0 deletions src/lib/contractAddress.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { expect } from 'earljs';

import { getContractAddress } from './contractAddress';

describe(getContractAddress.name, () => {
it('calculates a contract address based on a from address and a nonce', () => {
expect(
getContractAddress({
from: '0x9C33eaCc2F50E39940D3AfaF2c7B8246B681A374',
nonce: '0',
}),
).toEqual('0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f');
});
});
8 changes: 8 additions & 0 deletions src/lib/contractAddress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { getContractAddress as getContractAddressImpl } from '@ethersproject/address';

export function getContractAddress(params: {
from: string;
nonce: string;
}): string {
return getContractAddressImpl(params);
}
5 changes: 5 additions & 0 deletions src/misc/validation/schemas/addressSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { z } from 'zod';

export const addressSchema = z.string().regex(/^0x[0-9a-fA-F]{40}$/, {
message: 'The value must be a valid address',
});
20 changes: 8 additions & 12 deletions src/misc/validation/schemas/decimalSchema.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import { z } from 'zod';

export const decimalSchema = z
.number()
.or(
z
.string()
.regex(/^\d*$/, {
message:
'The value must be a hexadecimal number, 0x-prefix is required',
})
.transform(Number),
)
.refine((n) => n >= 0 && n <= 128);
export const decimalSchema = z.number().or(
z
.string()
.regex(/^\d*$/, {
message: 'The value must be a decimal number',
})
.transform(Number),
);
9 changes: 9 additions & 0 deletions src/misc/validation/validators/addressValidator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { zodResultMessage } from '../../../../src/misc/zodResultMessage';
import { addressSchema } from '../schemas/addressSchema';
import { ValidatorResult } from './result';

export function addressValidator(newValue: string): ValidatorResult {
const validated = addressSchema.safeParse(newValue);
if (validated.success) return { success: true };
else return { success: false, error: zodResultMessage(validated) };
}
10 changes: 8 additions & 2 deletions src/misc/validation/validators/numberValidator.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { identity } from 'lodash';
import { ZodTypeAny } from 'zod';

import { zodResultMessage } from '../../../../src/misc/zodResultMessage';
import { decimalSchema } from '../schemas/decimalSchema';
import { ValidatorResult } from './result';

export function numberValidator(newValue: string): ValidatorResult {
const validated = decimalSchema.safeParse(newValue);
export function numberValidator(
newValue: string,
enhanceSchema: (schema: ZodTypeAny) => ZodTypeAny = identity,
): ValidatorResult {
const validated = enhanceSchema(decimalSchema).safeParse(newValue);
if (validated.success) return { success: true };
else return { success: false, error: zodResultMessage(validated) };
}