-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathdeploy-contract.ts
More file actions
331 lines (296 loc) · 8.96 KB
/
deploy-contract.ts
File metadata and controls
331 lines (296 loc) · 8.96 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import fs from "fs";
import path from "path";
import { networks } from "./helpers/networks";
import yargs from "yargs";
import {
CallData,
stark,
RawArgs,
transaction,
extractContractHashes,
DeclareContractPayload,
UniversalDetails,
constants,
} from "starknet";
import { DeployContractParams, Network } from "./types";
import { green, red, yellow } from "./helpers/colorize-log";
interface Arguments {
network: string;
reset: boolean;
[x: string]: unknown;
_: (string | number)[];
$0: string;
}
const argv = yargs(process.argv.slice(2))
.option("network", {
type: "string",
description: "Specify the network",
demandOption: true,
})
.option("reset", {
type: "boolean",
description: "Reset deployments (remove existing deployments)",
default: true,
})
.parseSync() as Arguments;
const networkName: string = argv.network;
const resetDeployments: boolean = argv.reset;
let deployments = {};
let deployCalls = [];
const { provider, deployer }: Network = networks[networkName];
const declareIfNot_NotWait = async (
payload: DeclareContractPayload,
options?: UniversalDetails
) => {
const declareContractPayload = extractContractHashes(payload);
try {
await provider.getClassByHash(declareContractPayload.classHash);
} catch (error) {
try {
const { transaction_hash } = await deployer.declare(payload, {
...options,
version: constants.TRANSACTION_VERSION.V3,
});
if (networkName === "sepolia" || networkName === "mainnet") {
console.log(
yellow("Waiting for declaration transaction to be accepted...")
);
const receipt = await provider.waitForTransaction(transaction_hash);
console.log(
yellow("Declaration transaction receipt:"),
JSON.stringify(
receipt,
(_, v) => (typeof v === "bigint" ? v.toString() : v),
2
)
);
const receiptAny = receipt as any;
if (receiptAny.execution_status !== "SUCCEEDED") {
const revertReason = receiptAny.revert_reason || "Unknown reason";
throw new Error(
red(`Declaration failed or reverted. Reason: ${revertReason}`)
);
}
console.log(green("Declaration successful"));
}
} catch (e) {
console.error(red("Error declaring contract:"), e);
throw e;
}
}
return {
classHash: declareContractPayload.classHash,
};
};
const deployContract_NotWait = async (payload: {
salt: string;
classHash: string;
constructorCalldata: RawArgs;
}) => {
try {
const { calls, addresses } = transaction.buildUDCCall(
payload,
deployer.address
);
deployCalls.push(...calls);
return {
contractAddress: addresses[0],
};
} catch (error) {
console.error(red("Error building UDC call:"), error);
throw error;
}
};
const findContractFile = (
contract: string,
fileType: "compiled_contract_class" | "contract_class"
): string => {
const targetDir = path.resolve(__dirname, "../target/dev");
const files = fs.readdirSync(targetDir);
const pattern = new RegExp(`.*${contract}\\.${fileType}\\.json$`);
const matchingFile = files.find((file) => pattern.test(file));
if (!matchingFile) {
throw new Error(
`Could not find ${fileType} file for contract "${contract}". ` +
`Try removing snfoundry/contracts/target, then run 'yarn compile' and check if your contract name is correct inside the contracts/target/dev directory.`
);
}
return path.join(targetDir, matchingFile);
};
/**
* Deploy a contract using the specified parameters.
*
* @param {DeployContractParams} params - The parameters for deploying the contract.
* @param {string} params.contract - The name of the contract to deploy.
* @param {string} [params.contractName] - The name to export the contract as (optional).
* @param {RawArgs} [params.constructorArgs] - The constructor arguments for the contract (optional).
* @param {UniversalDetails} [params.options] - Additional deployment options (optional).
*
* @returns {Promise<{ classHash: string; address: string }>} The deployed contract's class hash and address.
*
* @example
* ///Example usage of deployContract function
* await deployContract({
* contract: "YourContract",
* contractName: "YourContractExportName",
* constructorArgs: { owner: deployer.address },
* options: { maxFee: BigInt(1000000000000) }
* });
*/
const deployContract = async (
params: DeployContractParams
): Promise<{
classHash: string;
address: string;
}> => {
const { contract, constructorArgs, contractName, options } = params;
try {
await deployer.getContractVersion(deployer.address);
} catch (e) {
if (e.toString().includes("Contract not found")) {
const errorMessage = `The wallet you're using to deploy the contract is not deployed in the ${networkName} network.`;
console.error(red(errorMessage));
throw new Error(errorMessage);
} else {
console.error(red("Error getting contract version: "), e);
throw e;
}
}
let compiledContractCasm;
let compiledContractSierra;
try {
compiledContractCasm = JSON.parse(
fs
.readFileSync(findContractFile(contract, "compiled_contract_class"))
.toString("ascii")
);
} catch (error) {
if (error.message.includes("Could not find")) {
console.error(
red(`The contract "${contract}" doesn't exist or is not compiled`)
);
} else {
console.error(red("Error reading compiled contract class file: "), error);
}
return {
classHash: "",
address: "",
};
}
try {
compiledContractSierra = JSON.parse(
fs
.readFileSync(findContractFile(contract, "contract_class"))
.toString("ascii")
);
} catch (error) {
console.error(red("Error reading contract class file: "), error);
return {
classHash: "",
address: "",
};
}
const contractCalldata = new CallData(compiledContractSierra.abi);
const constructorCalldata = constructorArgs
? contractCalldata.compile("constructor", constructorArgs)
: [];
console.log(yellow("Deploying Contract "), contractName || contract);
let { classHash } = await declareIfNot_NotWait(
{
contract: compiledContractSierra,
casm: compiledContractCasm,
},
options
);
let randomSalt = stark.randomAddress();
let { contractAddress } = await deployContract_NotWait({
salt: randomSalt,
classHash,
constructorCalldata,
});
console.log(green("Contract Deployed at "), contractAddress);
let finalContractName = contractName || contract;
deployments[finalContractName] = {
classHash: classHash,
address: contractAddress,
contract: contract,
};
return {
classHash: classHash,
address: contractAddress,
};
};
const executeDeployCalls = async (options?: UniversalDetails) => {
if (deployCalls.length < 1) {
throw new Error(
red(
"Aborted: No contract to deploy. Please prepare the contracts with `deployContract`"
)
);
}
try {
let { transaction_hash } = await deployer.execute(deployCalls, {
...options,
version: constants.TRANSACTION_VERSION.V3,
});
if (networkName === "sepolia" || networkName === "mainnet") {
const receipt = await provider.waitForTransaction(transaction_hash);
const receiptAny = receipt as any;
if (receiptAny.execution_status !== "SUCCEEDED") {
const revertReason = receiptAny.revert_reason;
throw new Error(red(`Deploy Calls Failed: ${revertReason}`));
}
}
console.log(green("Deploy Calls Executed at "), transaction_hash);
} catch (error) {
// split the calls in half and try again recursively
if (deployCalls.length > 100) {
let half = Math.ceil(deployCalls.length / 2);
let firstHalf = deployCalls.slice(0, half);
let secondHalf = deployCalls.slice(half);
deployCalls = firstHalf;
await executeDeployCalls(options);
deployCalls = secondHalf;
await executeDeployCalls(options);
} else {
throw error;
}
}
};
const loadExistingDeployments = () => {
const networkPath = path.resolve(
__dirname,
`../deployments/${networkName}_latest.json`
);
if (fs.existsSync(networkPath)) {
return JSON.parse(fs.readFileSync(networkPath, "utf8"));
}
return {};
};
const exportDeployments = () => {
const networkPath = path.resolve(
__dirname,
`../deployments/${networkName}_latest.json`
);
if (!resetDeployments && fs.existsSync(networkPath)) {
const currentTimestamp = new Date().getTime();
fs.renameSync(
networkPath,
networkPath.replace("_latest.json", `_${currentTimestamp}.json`)
);
}
if (resetDeployments && fs.existsSync(networkPath)) {
fs.unlinkSync(networkPath);
}
fs.writeFileSync(networkPath, JSON.stringify(deployments, null, 2));
};
export {
deployContract,
provider,
deployer,
loadExistingDeployments,
exportDeployments,
executeDeployCalls,
resetDeployments,
networkName,
};