-
Notifications
You must be signed in to change notification settings - Fork 1
/
create2.ts
49 lines (44 loc) · 1.18 KB
/
create2.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { ethers, keccak256 } from "ethers";
export const buildBytecode = (
constructorTypes: any[],
constructorArgs: any[],
contractBytecode: string
) =>
`${contractBytecode}${encodeParams(constructorTypes, constructorArgs).slice(
2
)}`;
const buildCreate2Address = (
factoryAddress: string,
saltHex: string,
byteCode: string
) => {
return `0x${keccak256(
`0x${["ff", factoryAddress, saltHex, keccak256(byteCode)]
.map((x) => x.replace(/0x/, ""))
.join("")}`
).slice(-40)}`.toLowerCase();
};
const saltToHex = (salt: string | number) => ethers.id(salt.toString());
const encodeParams = (dataTypes: any[], data: any[]) => {
const abiCoder = new ethers.AbiCoder();
return abiCoder.encode(dataTypes, data);
};
export function getCreate2Address({
factoryAddress,
salt,
contractBytecode,
constructorTypes = [] as string[],
constructorArgs = [] as any[],
}: {
salt: string | number;
factoryAddress: string;
contractBytecode: string;
constructorTypes?: string[];
constructorArgs?: any[];
}) {
return buildCreate2Address(
factoryAddress,
saltToHex(salt),
buildBytecode(constructorTypes, constructorArgs, contractBytecode)
);
}