@layerzerolabs/hardhat-tron 2.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +78 -0
  2. package/dist/DeploymentFactory.d.ts +13 -0
  3. package/dist/DeploymentFactory.d.ts.map +1 -0
  4. package/dist/DeploymentFactory.js +46 -0
  5. package/dist/DeploymentFactory.js.map +1 -0
  6. package/dist/DeploymentsManager.d.ts +10 -0
  7. package/dist/DeploymentsManager.d.ts.map +1 -0
  8. package/dist/DeploymentsManager.js +78 -0
  9. package/dist/DeploymentsManager.js.map +1 -0
  10. package/dist/constants.d.ts +10 -0
  11. package/dist/constants.d.ts.map +1 -0
  12. package/dist/constants.js +70 -0
  13. package/dist/constants.js.map +1 -0
  14. package/dist/downloader.d.ts +14 -0
  15. package/dist/downloader.d.ts.map +1 -0
  16. package/dist/downloader.js +107 -0
  17. package/dist/downloader.js.map +1 -0
  18. package/dist/extendedArtifactsTron/Diamond.json +17557 -0
  19. package/dist/extendedArtifactsTron/DiamondCutFacet.json +10112 -0
  20. package/dist/extendedArtifactsTron/DiamondERC165Init.json +1549 -0
  21. package/dist/extendedArtifactsTron/DiamondLoupeFacet.json +3194 -0
  22. package/dist/extendedArtifactsTron/EIP173Proxy.json +4707 -0
  23. package/dist/extendedArtifactsTron/EIP173ProxyWithReceive.json +4524 -0
  24. package/dist/extendedArtifactsTron/ERC1967Proxy.json +4039 -0
  25. package/dist/extendedArtifactsTron/OptimizedTransparentUpgradeableProxy.json +6143 -0
  26. package/dist/extendedArtifactsTron/OwnershipFacet.json +793 -0
  27. package/dist/extendedArtifactsTron/ProxyAdmin.json +4339 -0
  28. package/dist/extendedArtifactsTron/TransparentUpgradeableProxy.json +6829 -0
  29. package/dist/helper.d.ts +39 -0
  30. package/dist/helper.d.ts.map +1 -0
  31. package/dist/helper.js +2484 -0
  32. package/dist/helper.js.map +1 -0
  33. package/dist/index.d.ts +3 -0
  34. package/dist/index.d.ts.map +1 -0
  35. package/dist/index.js +159 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/tron/contract.d.ts +12 -0
  38. package/dist/tron/contract.d.ts.map +1 -0
  39. package/dist/tron/contract.js +38 -0
  40. package/dist/tron/contract.js.map +1 -0
  41. package/dist/tron/provider.d.ts +41 -0
  42. package/dist/tron/provider.d.ts.map +1 -0
  43. package/dist/tron/provider.js +165 -0
  44. package/dist/tron/provider.js.map +1 -0
  45. package/dist/tron/signer.d.ts +31 -0
  46. package/dist/tron/signer.d.ts.map +1 -0
  47. package/dist/tron/signer.js +102 -0
  48. package/dist/tron/signer.js.map +1 -0
  49. package/dist/tron/types.d.ts +10 -0
  50. package/dist/tron/types.d.ts.map +1 -0
  51. package/dist/tron/types.js +9 -0
  52. package/dist/tron/types.js.map +1 -0
  53. package/dist/tron/utils.d.ts +26 -0
  54. package/dist/tron/utils.d.ts.map +1 -0
  55. package/dist/tron/utils.js +64 -0
  56. package/dist/tron/utils.js.map +1 -0
  57. package/dist/type-extensions.d.ts +34 -0
  58. package/dist/type-extensions.d.ts.map +1 -0
  59. package/dist/type-extensions.js +4 -0
  60. package/dist/type-extensions.js.map +1 -0
  61. package/dist/types.d.ts +30 -0
  62. package/dist/types.d.ts.map +1 -0
  63. package/dist/types.js +3 -0
  64. package/dist/types.js.map +1 -0
  65. package/dist/utils.d.ts +19 -0
  66. package/dist/utils.d.ts.map +1 -0
  67. package/dist/utils.js +118 -0
  68. package/dist/utils.js.map +1 -0
  69. package/package.json +114 -0
package/dist/helper.js ADDED
@@ -0,0 +1,2484 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.waitForTx = exports.addHelpers = void 0;
30
+ const abi_1 = require("@ethersproject/abi");
31
+ const address_1 = require("@ethersproject/address");
32
+ const bignumber_1 = require("@ethersproject/bignumber");
33
+ const bytes_1 = require("@ethersproject/bytes");
34
+ const constants_1 = require("@ethersproject/constants");
35
+ const contracts_1 = require("@ethersproject/contracts");
36
+ const providers_1 = require("@ethersproject/providers");
37
+ const solidity_1 = require("@ethersproject/solidity");
38
+ const transactions_1 = require("@ethersproject/transactions");
39
+ const wallet_1 = require("@ethersproject/wallet");
40
+ const enquirer_1 = __importDefault(require("enquirer"));
41
+ const fs_extra_1 = __importDefault(require("fs-extra"));
42
+ const errors_1 = require("hardhat-deploy/dist/src/errors");
43
+ const hdpath_1 = require("hardhat-deploy/dist/src/hdpath");
44
+ const utils_1 = require("hardhat-deploy/dist/src/internal/utils");
45
+ const old_diamondbase_json_1 = __importDefault(require("hardhat-deploy/dist/src/old_diamondbase.json"));
46
+ const utils_2 = require("hardhat-deploy/dist/src/utils");
47
+ const types_1 = require("hardhat-deploy/dist/types");
48
+ const zk = __importStar(require("zksync-web3"));
49
+ const DeploymentFactory_1 = require("./DeploymentFactory");
50
+ const provider_1 = require("./tron/provider");
51
+ let LedgerSigner;
52
+ let ethersprojectHardwareWalletsModule;
53
+ let andrestEthersLedgerModule;
54
+ let TrezorSigner;
55
+ let hardwareSigner;
56
+ let OpenZeppelinTransparentProxy;
57
+ let OptimizedTransparentUpgradeableProxy;
58
+ let DefaultProxyAdmin;
59
+ let eip173Proxy;
60
+ let eip173ProxyWithReceive;
61
+ let erc1967Proxy;
62
+ let diamondBase;
63
+ let diamondERC165Init;
64
+ let diamondCutFacet;
65
+ let diamondLoupeFacet;
66
+ let ownershipFacet;
67
+ async function initArtifacts(isTron) {
68
+ const importAssertion = { assert: { type: 'json' } };
69
+ if (isTron) {
70
+ console.log('loading tron artifacts');
71
+ OpenZeppelinTransparentProxy = (await import('./extendedArtifactsTron/TransparentUpgradeableProxy.json', importAssertion)).default;
72
+ OptimizedTransparentUpgradeableProxy = (await import('./extendedArtifactsTron/OptimizedTransparentUpgradeableProxy.json', importAssertion)).default;
73
+ DefaultProxyAdmin = (await import('./extendedArtifactsTron/ProxyAdmin.json', importAssertion)).default;
74
+ eip173Proxy = (await import('./extendedArtifactsTron/EIP173Proxy.json', importAssertion)).default;
75
+ eip173ProxyWithReceive = (await import('./extendedArtifactsTron/EIP173ProxyWithReceive.json', importAssertion))
76
+ .default;
77
+ erc1967Proxy = (await import('./extendedArtifactsTron/ERC1967Proxy.json', importAssertion)).default;
78
+ diamondBase = (await import('./extendedArtifactsTron/Diamond.json', importAssertion)).default;
79
+ diamondERC165Init = (await import('./extendedArtifactsTron/DiamondERC165Init.json', importAssertion)).default;
80
+ diamondCutFacet = (await import('./extendedArtifactsTron/DiamondCutFacet.json', importAssertion)).default;
81
+ diamondLoupeFacet = (await import('./extendedArtifactsTron/DiamondLoupeFacet.json', importAssertion)).default;
82
+ ownershipFacet = (await import('./extendedArtifactsTron/OwnershipFacet.json', importAssertion)).default;
83
+ }
84
+ else {
85
+ OpenZeppelinTransparentProxy = (await import('hardhat-deploy/extendedArtifacts/TransparentUpgradeableProxy.json', importAssertion)).default;
86
+ OptimizedTransparentUpgradeableProxy = (await import('hardhat-deploy/extendedArtifacts/OptimizedTransparentUpgradeableProxy.json', importAssertion)).default;
87
+ DefaultProxyAdmin = (await import('hardhat-deploy/extendedArtifacts/ProxyAdmin.json', importAssertion)).default;
88
+ eip173Proxy = (await import('hardhat-deploy/extendedArtifacts/EIP173Proxy.json', importAssertion)).default;
89
+ eip173ProxyWithReceive = (await import('hardhat-deploy/extendedArtifacts/EIP173ProxyWithReceive.json', importAssertion)).default;
90
+ erc1967Proxy = (await import('hardhat-deploy/extendedArtifacts/ERC1967Proxy.json', importAssertion)).default;
91
+ diamondBase = (await import('hardhat-deploy/extendedArtifacts/Diamond.json', importAssertion)).default;
92
+ diamondERC165Init = (await import('hardhat-deploy/extendedArtifacts/DiamondERC165Init.json', importAssertion))
93
+ .default;
94
+ diamondCutFacet = (await import('hardhat-deploy/extendedArtifacts/DiamondCutFacet.json', importAssertion))
95
+ .default;
96
+ diamondLoupeFacet = (await import('hardhat-deploy/extendedArtifacts/DiamondLoupeFacet.json', importAssertion))
97
+ .default;
98
+ ownershipFacet = (await import('hardhat-deploy/extendedArtifacts/OwnershipFacet.json', importAssertion)).default;
99
+ }
100
+ }
101
+ async function handleSpecificErrors(p) {
102
+ let result;
103
+ try {
104
+ result = await p;
105
+ }
106
+ catch (e) {
107
+ if (typeof e.message === 'string' && e.message.indexOf('already known') !== -1) {
108
+ console.log(`
109
+ Exact same transaction already in the pool, node reject duplicates.
110
+ You'll need to wait the tx resolve, or increase the gas price via --gasprice (this will use old tx type)
111
+ `);
112
+ throw new Error('Exact same transaction already in the pool, node reject duplicates');
113
+ }
114
+ else {
115
+ console.error(e.message, JSON.stringify(e, utils_1.bnReplacer), e);
116
+ throw e;
117
+ }
118
+ }
119
+ return result;
120
+ }
121
+ function fixProvider(providerGiven) {
122
+ if (providerGiven.sendAsync === undefined) {
123
+ providerGiven.sendAsync = (req, callback) => {
124
+ providerGiven
125
+ .send(req.method, req.params)
126
+ .then((result) => callback(null, { result, id: req.id, jsonrpc: req.jsonrpc }))
127
+ .catch((error) => callback(error, null));
128
+ };
129
+ }
130
+ return providerGiven;
131
+ }
132
+ function findAll(toFind, array) {
133
+ for (const f of toFind) {
134
+ if (array.indexOf(f) === -1) {
135
+ return false;
136
+ }
137
+ }
138
+ return true;
139
+ }
140
+ function linkRawLibrary(bytecode, libraryName, libraryAddress) {
141
+ const address = libraryAddress.replace('0x', '');
142
+ let encodedLibraryName;
143
+ if (libraryName.startsWith('$') && libraryName.endsWith('$')) {
144
+ encodedLibraryName = libraryName.slice(1, libraryName.length - 1);
145
+ }
146
+ else {
147
+ encodedLibraryName = (0, solidity_1.keccak256)(['string'], [libraryName]).slice(2, 36);
148
+ }
149
+ const pattern = new RegExp(`_+\\$${encodedLibraryName}\\$_+`, 'g');
150
+ if (!pattern.exec(bytecode)) {
151
+ throw new Error(`Can't link '${libraryName}' (${encodedLibraryName}) in \n----\n ${bytecode}\n----\n`);
152
+ }
153
+ return bytecode.replace(pattern, address);
154
+ }
155
+ function linkRawLibraries(bytecode, libraries) {
156
+ for (const libName of Object.keys(libraries)) {
157
+ const libAddress = libraries[libName];
158
+ bytecode = linkRawLibrary(bytecode, libName, libAddress);
159
+ }
160
+ return bytecode;
161
+ }
162
+ function linkLibraries(artifact, libraries) {
163
+ let bytecode = artifact.bytecode;
164
+ if (libraries) {
165
+ if (artifact.linkReferences) {
166
+ for (const [fileName, fileReferences] of Object.entries(artifact.linkReferences)) {
167
+ for (const [libName, fixups] of Object.entries(fileReferences)) {
168
+ const addr = libraries[libName];
169
+ if (addr === undefined) {
170
+ continue;
171
+ }
172
+ for (const fixup of fixups) {
173
+ bytecode =
174
+ bytecode.substr(0, 2 + fixup.start * 2) +
175
+ addr.substr(2) +
176
+ bytecode.substr(2 + (fixup.start + fixup.length) * 2);
177
+ }
178
+ }
179
+ }
180
+ }
181
+ else {
182
+ bytecode = linkRawLibraries(bytecode, libraries);
183
+ }
184
+ }
185
+ return bytecode;
186
+ }
187
+ function addHelpers(deploymentManager, partialExtension, network, getArtifact, saveDeployment, willSaveToDisk, onPendingTx, getGasPrice, log, print) {
188
+ let provider;
189
+ const availableAccounts = {};
190
+ async function init() {
191
+ await initArtifacts(deploymentManager.isTronNetworkWithTronSolc);
192
+ if (!provider) {
193
+ await deploymentManager.setupAccounts();
194
+ if (network.zksync) {
195
+ provider = new zk.Web3Provider(fixProvider(network.provider));
196
+ }
197
+ else if (network.tron) {
198
+ provider = new provider_1.TronWeb3Provider(fixProvider(network.provider), network.config);
199
+ }
200
+ else {
201
+ provider = new providers_1.Web3Provider(fixProvider(network.provider));
202
+ }
203
+ try {
204
+ const accounts = await provider.send('eth_accounts', []);
205
+ for (const account of accounts) {
206
+ availableAccounts[account.toLowerCase()] = true;
207
+ }
208
+ for (const address of deploymentManager.impersonatedAccounts) {
209
+ availableAccounts[address.toLowerCase()] = true;
210
+ }
211
+ }
212
+ catch (e) { }
213
+ }
214
+ return provider;
215
+ }
216
+ function cleanupOverrides(txRequestOrOverrides) {
217
+ if (txRequestOrOverrides.maxFeePerGas === undefined) {
218
+ delete txRequestOrOverrides.maxFeePerGas;
219
+ }
220
+ if (txRequestOrOverrides.maxPriorityFeePerGas === undefined) {
221
+ delete txRequestOrOverrides.maxPriorityFeePerGas;
222
+ }
223
+ if (txRequestOrOverrides.gasPrice === undefined) {
224
+ delete txRequestOrOverrides.gasPrice;
225
+ }
226
+ if (txRequestOrOverrides.value === undefined) {
227
+ delete txRequestOrOverrides.value;
228
+ }
229
+ return txRequestOrOverrides;
230
+ }
231
+ async function setupGasPrice(txRequestOrOverrides) {
232
+ const gasPriceSetup = await getGasPrice();
233
+ if (!txRequestOrOverrides.gasPrice) {
234
+ txRequestOrOverrides.gasPrice = gasPriceSetup.gasPrice;
235
+ }
236
+ if (!txRequestOrOverrides.maxFeePerGas) {
237
+ txRequestOrOverrides.maxFeePerGas = gasPriceSetup.maxFeePerGas;
238
+ }
239
+ if (!txRequestOrOverrides.maxPriorityFeePerGas) {
240
+ txRequestOrOverrides.maxPriorityFeePerGas = gasPriceSetup.maxPriorityFeePerGas;
241
+ }
242
+ cleanupOverrides(txRequestOrOverrides);
243
+ }
244
+ async function setupNonce(from, txRequestOrOverrides) {
245
+ if (txRequestOrOverrides.nonce === 'pending' || txRequestOrOverrides.nonce === 'latest') {
246
+ txRequestOrOverrides.nonce = await provider.getTransactionCount(from, txRequestOrOverrides.nonce);
247
+ }
248
+ else if (!txRequestOrOverrides.nonce) {
249
+ txRequestOrOverrides.nonce = await provider.getTransactionCount(from, 'latest');
250
+ }
251
+ }
252
+ async function overrideGasLimit(txRequestOrOverrides, options, estimate) {
253
+ const estimatedGasLimit = options.estimatedGasLimit
254
+ ? bignumber_1.BigNumber.from(options.estimatedGasLimit).toNumber()
255
+ : undefined;
256
+ const estimateGasExtra = options.estimateGasExtra
257
+ ? bignumber_1.BigNumber.from(options.estimateGasExtra).toNumber()
258
+ : undefined;
259
+ if (!txRequestOrOverrides.gasLimit) {
260
+ txRequestOrOverrides.gasLimit = estimatedGasLimit;
261
+ txRequestOrOverrides.gasLimit = (await estimate(txRequestOrOverrides)).toNumber();
262
+ if (estimateGasExtra) {
263
+ txRequestOrOverrides.gasLimit = txRequestOrOverrides.gasLimit + estimateGasExtra;
264
+ if (estimatedGasLimit) {
265
+ txRequestOrOverrides.gasLimit = Math.min(txRequestOrOverrides.gasLimit, estimatedGasLimit);
266
+ }
267
+ }
268
+ }
269
+ }
270
+ async function ensureCreate2DeployerReady(options) {
271
+ const { address: from, ethersSigner, hardwareWallet, unknown } = await getFrom(options.from);
272
+ const create2DeployerAddress = await deploymentManager.getDeterministicDeploymentFactoryAddress();
273
+ const code = await provider.getCode(create2DeployerAddress);
274
+ if (code === '0x') {
275
+ const senderAddress = await deploymentManager.getDeterministicDeploymentFactoryDeployer();
276
+ const txRequest = {
277
+ to: senderAddress,
278
+ value: (await deploymentManager.getDeterministicDeploymentFactoryFunding()).toHexString(),
279
+ gasPrice: options.gasPrice,
280
+ maxFeePerGas: options.maxFeePerGas,
281
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas,
282
+ };
283
+ await setupGasPrice(txRequest);
284
+ await setupNonce(from, txRequest);
285
+ if (unknown) {
286
+ throw new errors_1.UnknownSignerError({
287
+ from,
288
+ ...txRequest,
289
+ });
290
+ }
291
+ if (options.log || hardwareWallet) {
292
+ print(`sending eth to create2 contract deployer address (${senderAddress})`);
293
+ if (hardwareWallet) {
294
+ print(` (please confirm on your ${hardwareWallet})`);
295
+ }
296
+ }
297
+ let ethTx = (await handleSpecificErrors(ethersSigner.sendTransaction(txRequest)));
298
+ if (options.log || hardwareWallet) {
299
+ log(` (tx: ${ethTx.hash})...`);
300
+ }
301
+ ethTx = await onPendingTx(ethTx);
302
+ await ethTx.wait();
303
+ if (options.log || hardwareWallet) {
304
+ print(`deploying create2 deployer contract (at ${create2DeployerAddress}) using deterministic deployment (https://github.com/Arachnid/deterministic-deployment-proxy)`);
305
+ if (hardwareWallet) {
306
+ print(` (please confirm on your ${hardwareWallet})`);
307
+ }
308
+ }
309
+ const deployTx = await provider.sendTransaction(await deploymentManager.getDeterministicDeploymentFactoryDeploymentTx());
310
+ if (options.log || hardwareWallet) {
311
+ log(` (tx: ${deployTx.hash})...`);
312
+ }
313
+ await deployTx.wait();
314
+ }
315
+ return create2DeployerAddress;
316
+ }
317
+ async function getArtifactFromOptions(name, options) {
318
+ let artifact;
319
+ let artifactName;
320
+ if (options.contract) {
321
+ if (typeof options.contract === 'string') {
322
+ artifactName = options.contract;
323
+ artifact = await getArtifact(artifactName);
324
+ }
325
+ else {
326
+ artifact = options.contract;
327
+ }
328
+ }
329
+ else {
330
+ artifactName = name;
331
+ artifact = await getArtifact(artifactName);
332
+ }
333
+ return { artifact, artifactName };
334
+ }
335
+ async function getLinkedArtifact(name, options) {
336
+ const { artifact, artifactName } = await getArtifactFromOptions(name, options);
337
+ const byteCode = linkLibraries(artifact, options.libraries);
338
+ return { artifact: { ...artifact, bytecode: byteCode }, artifactName };
339
+ }
340
+ async function _deploy(name, options) {
341
+ const args = options.args ? [...options.args] : [];
342
+ await init();
343
+ const { address: from, ethersSigner, hardwareWallet, unknown } = await getFrom(options.from);
344
+ const { artifact: linkedArtifact, artifactName } = await getLinkedArtifact(name, options);
345
+ const overrides = {
346
+ gasLimit: options.gasLimit,
347
+ gasPrice: options.gasPrice,
348
+ maxFeePerGas: options.maxFeePerGas,
349
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas,
350
+ value: options.value,
351
+ nonce: options.nonce,
352
+ };
353
+ const factory = new DeploymentFactory_1.CustomDeploymentFactory(getArtifact, linkedArtifact, args, network, ethersSigner, overrides);
354
+ const unsignedTx = await factory.getDeployTransaction();
355
+ let create2Address;
356
+ if (options.deterministicDeployment) {
357
+ if (network.tron) {
358
+ throw new Error('deterministic deployment not supported on Tron');
359
+ }
360
+ if (typeof unsignedTx.data === 'string') {
361
+ const create2DeployerAddress = await ensureCreate2DeployerReady(options);
362
+ const create2Salt = typeof options.deterministicDeployment === 'string'
363
+ ? (0, bytes_1.hexlify)((0, bytes_1.zeroPad)(options.deterministicDeployment, 32))
364
+ : '0x0000000000000000000000000000000000000000000000000000000000000000';
365
+ create2Address = await factory.getCreate2Address(create2DeployerAddress, create2Salt);
366
+ unsignedTx.to = create2DeployerAddress;
367
+ unsignedTx.data = create2Salt + unsignedTx.data.slice(2);
368
+ }
369
+ else {
370
+ throw new Error('unsigned tx data as bytes not supported');
371
+ }
372
+ }
373
+ if (network.tron) {
374
+ const feeLimit = await ethersSigner.getFeeLimit(unsignedTx, overrides);
375
+ unsignedTx.feeLimit = feeLimit;
376
+ }
377
+ else {
378
+ await overrideGasLimit(unsignedTx, options, (newOverrides) => ethersSigner.estimateGas(newOverrides));
379
+ await setupGasPrice(unsignedTx);
380
+ await setupNonce(from, unsignedTx);
381
+ if (hardwareWallet === 'ledger') {
382
+ unsignedTx.type = 1;
383
+ }
384
+ else if (hardwareWallet === 'trezor') {
385
+ unsignedTx.type = 1;
386
+ }
387
+ }
388
+ if (unknown) {
389
+ throw new errors_1.UnknownSignerError({
390
+ from,
391
+ ...JSON.parse(JSON.stringify(unsignedTx, utils_1.bnReplacer)),
392
+ });
393
+ }
394
+ if (options.log || hardwareWallet) {
395
+ print(`deploying "${name}"`);
396
+ if (hardwareWallet) {
397
+ print(` (please confirm on your ${hardwareWallet})`);
398
+ }
399
+ }
400
+ let tx = (await handleSpecificErrors(ethersSigner.sendTransaction(unsignedTx)));
401
+ if (options.log || hardwareWallet) {
402
+ print(` (tx: ${tx.hash})...`);
403
+ }
404
+ if (options.autoMine) {
405
+ try {
406
+ await provider.send('evm_mine', []);
407
+ }
408
+ catch (e) { }
409
+ }
410
+ let preDeployment = {
411
+ ...linkedArtifact,
412
+ transactionHash: tx.hash,
413
+ args,
414
+ linkedData: options.linkedData,
415
+ };
416
+ if (artifactName && willSaveToDisk()) {
417
+ const extendedArtifact = await partialExtension.getExtendedArtifact(artifactName);
418
+ preDeployment = {
419
+ ...extendedArtifact,
420
+ ...preDeployment,
421
+ };
422
+ }
423
+ tx = await onPendingTx(tx, name, preDeployment);
424
+ const receipt = await tx.wait(options.waitConfirmations);
425
+ const address = options.deterministicDeployment && create2Address ? create2Address : receipt.contractAddress;
426
+ const deployment = {
427
+ ...preDeployment,
428
+ address,
429
+ receipt,
430
+ transactionHash: receipt.transactionHash,
431
+ libraries: options.libraries,
432
+ };
433
+ await saveDeployment(name, deployment);
434
+ if (options.log || hardwareWallet) {
435
+ print(`: deployed at ${deployment.address} with ${receipt?.gasUsed} gas\n`);
436
+ }
437
+ return {
438
+ ...deployment,
439
+ address,
440
+ newlyDeployed: true,
441
+ };
442
+ }
443
+ async function deterministic(name, options) {
444
+ options = { ...options };
445
+ await init();
446
+ const deployFunction = () => deploy(name, {
447
+ ...options,
448
+ deterministicDeployment: options.salt || true,
449
+ });
450
+ if (options.proxy) {
451
+ let { viaAdminContract, proxyAdminDeployed, proxyAdminName, proxyAdminContract, owner, proxyAdmin, currentProxyAdminOwner, artifact, implementationArgs, implementationName, implementationOptions, proxyName, proxyContract, proxyArgsTemplate, mergedABI, updateMethod, updateArgs, } = await _getProxyInfo(name, options);
452
+ const { address: implementationAddress } = await deterministic(implementationName, {
453
+ ...implementationOptions,
454
+ salt: options.salt,
455
+ });
456
+ const implementationContract = new contracts_1.Contract(implementationAddress, artifact.abi);
457
+ let data = '0x';
458
+ if (updateMethod) {
459
+ updateArgs = updateArgs || [];
460
+ if (!implementationContract[updateMethod]) {
461
+ throw new Error(`contract need to implement function ${updateMethod}`);
462
+ }
463
+ const txData = await implementationContract.populateTransaction[updateMethod](...updateArgs);
464
+ data = txData.data || '0x';
465
+ }
466
+ if (viaAdminContract) {
467
+ if (!proxyAdminName) {
468
+ throw new Error(`no proxy admin name even though viaAdminContract is not undefined`);
469
+ }
470
+ if (!proxyAdminDeployed) {
471
+ const { address: proxyAdminAddress } = await deterministic(proxyAdminName, {
472
+ from: options.from,
473
+ autoMine: options.autoMine,
474
+ estimateGasExtra: options.estimateGasExtra,
475
+ estimatedGasLimit: options.estimatedGasLimit,
476
+ gasPrice: options.gasPrice,
477
+ maxFeePerGas: options.maxFeePerGas,
478
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas,
479
+ log: options.log,
480
+ contract: proxyAdminContract,
481
+ salt: options.salt,
482
+ skipIfAlreadyDeployed: true,
483
+ args: [owner],
484
+ waitConfirmations: options.waitConfirmations,
485
+ });
486
+ proxyAdmin = proxyAdminAddress;
487
+ }
488
+ else {
489
+ proxyAdmin = proxyAdminDeployed.address;
490
+ }
491
+ }
492
+ const proxyOptions = { ...options };
493
+ delete proxyOptions.proxy;
494
+ delete proxyOptions.libraries;
495
+ proxyOptions.contract = proxyContract;
496
+ proxyOptions.args = replaceTemplateArgs(proxyArgsTemplate, {
497
+ implementationAddress,
498
+ proxyAdmin,
499
+ data,
500
+ });
501
+ const { address: proxyAddress } = await deterministic(proxyName, {
502
+ ...proxyOptions,
503
+ salt: options.salt,
504
+ });
505
+ return {
506
+ address: proxyAddress,
507
+ implementationAddress,
508
+ deploy: deployFunction,
509
+ };
510
+ }
511
+ else {
512
+ const args = options.args ? [...options.args] : [];
513
+ const { ethersSigner, unknown, address: from } = await getFrom(options.from);
514
+ const { artifact: linkedArtifact, artifactName } = await getLinkedArtifact(name, options);
515
+ const factory = new DeploymentFactory_1.CustomDeploymentFactory(getArtifact, linkedArtifact, args, network, ethersSigner);
516
+ if (unknown) {
517
+ throw new errors_1.UnknownSignerError({
518
+ from,
519
+ ...JSON.parse(JSON.stringify(await factory.getDeployTransaction(), utils_1.bnReplacer)),
520
+ });
521
+ }
522
+ return {
523
+ address: await factory.getCreate2Address(await deploymentManager.getDeterministicDeploymentFactoryAddress(), options.salt
524
+ ? (0, bytes_1.hexlify)((0, bytes_1.zeroPad)(options.salt, 32))
525
+ : '0x0000000000000000000000000000000000000000000000000000000000000000'),
526
+ deploy: () => deploy(name, {
527
+ ...options,
528
+ deterministicDeployment: options.salt || true,
529
+ }),
530
+ };
531
+ }
532
+ }
533
+ function getDeployment(name) {
534
+ return partialExtension.get(name);
535
+ }
536
+ function getDeploymentOrNUll(name) {
537
+ return partialExtension.getOrNull(name);
538
+ }
539
+ async function fetchIfDifferent(name, options) {
540
+ options = { ...options };
541
+ const args = options.args ? [...options.args] : [];
542
+ await init();
543
+ const { ethersSigner } = await getFrom(options.from);
544
+ const { artifact: linkedArtifact } = await getLinkedArtifact(name, options);
545
+ const factory = new DeploymentFactory_1.CustomDeploymentFactory(getArtifact, linkedArtifact, args, network, ethersSigner);
546
+ if (options.deterministicDeployment) {
547
+ const create2Salt = typeof options.deterministicDeployment === 'string'
548
+ ? (0, bytes_1.hexlify)((0, bytes_1.zeroPad)(options.deterministicDeployment, 32))
549
+ : '0x0000000000000000000000000000000000000000000000000000000000000000';
550
+ const create2DeployerAddress = await deploymentManager.getDeterministicDeploymentFactoryAddress();
551
+ const create2Address = await factory.getCreate2Address(create2DeployerAddress, create2Salt);
552
+ const code = await provider.getCode(create2Address);
553
+ if (code === '0x') {
554
+ return { differences: true, address: undefined };
555
+ }
556
+ else {
557
+ return { differences: false, address: create2Address };
558
+ }
559
+ }
560
+ const deployment = await partialExtension.getOrNull(name);
561
+ if (deployment) {
562
+ if (options.skipIfAlreadyDeployed) {
563
+ return { differences: false, address: undefined };
564
+ }
565
+ let transactionDetailsAvailable = false;
566
+ let transaction;
567
+ if (deployment.receipt) {
568
+ transactionDetailsAvailable = !!deployment.receipt.transactionHash;
569
+ if (transactionDetailsAvailable) {
570
+ transaction = await provider.getTransaction(deployment.receipt.transactionHash);
571
+ }
572
+ }
573
+ else if (deployment.transactionHash) {
574
+ transactionDetailsAvailable = true;
575
+ transaction = await provider.getTransaction(deployment.transactionHash);
576
+ }
577
+ if (transaction) {
578
+ const differences = await factory.compareDeploymentTransaction(transaction);
579
+ return { differences, address: deployment.address };
580
+ }
581
+ else {
582
+ if (transactionDetailsAvailable) {
583
+ throw new Error(`cannot get the transaction for ${name}'s previous deployment, please check your node synced status.`);
584
+ }
585
+ else {
586
+ console.error(`no transaction details found for ${name}'s previous deployment, if the deployment is t be discarded, please delete the file`);
587
+ return { differences: false, address: deployment.address };
588
+ }
589
+ }
590
+ }
591
+ return { differences: true, address: undefined };
592
+ }
593
+ async function _deployOne(name, options, failsOnExistingDeterminisitc) {
594
+ const argsArray = options.args ? [...options.args] : [];
595
+ options = { ...options, args: argsArray };
596
+ let result;
597
+ const diffResult = await fetchIfDifferent(name, options);
598
+ if (diffResult.differences) {
599
+ result = await _deploy(name, options);
600
+ }
601
+ else {
602
+ if (failsOnExistingDeterminisitc && options.deterministicDeployment) {
603
+ throw new Error(`already deployed on same deterministic address: ${diffResult.address}`);
604
+ }
605
+ const deployment = await getDeploymentOrNUll(name);
606
+ if (deployment) {
607
+ if (options.deterministicDeployment &&
608
+ diffResult.address &&
609
+ diffResult.address.toLowerCase() !== deployment.address.toLowerCase()) {
610
+ const { artifact: linkedArtifact, artifactName } = await getLinkedArtifact(name, options);
611
+ const newDeployment = {
612
+ ...linkedArtifact,
613
+ address: diffResult.address,
614
+ linkedData: options.linkedData,
615
+ libraries: options.libraries,
616
+ args: argsArray,
617
+ };
618
+ await saveDeployment(name, newDeployment, artifactName);
619
+ result = {
620
+ ...newDeployment,
621
+ newlyDeployed: false,
622
+ };
623
+ }
624
+ else {
625
+ result = deployment;
626
+ result.newlyDeployed = false;
627
+ }
628
+ }
629
+ else {
630
+ if (!diffResult.address) {
631
+ throw new Error('no differences found but no address, this should be impossible');
632
+ }
633
+ const { artifact: linkedArtifact, artifactName } = await getLinkedArtifact(name, options);
634
+ const newDeployment = {
635
+ ...linkedArtifact,
636
+ address: diffResult.address,
637
+ linkedData: options.linkedData,
638
+ libraries: options.libraries,
639
+ args: argsArray,
640
+ };
641
+ await saveDeployment(name, newDeployment, artifactName);
642
+ result = {
643
+ ...newDeployment,
644
+ newlyDeployed: false,
645
+ };
646
+ }
647
+ if (options.log) {
648
+ log(`reusing "${name}" at ${result.address}`);
649
+ }
650
+ }
651
+ return result;
652
+ }
653
+ function _checkUpgradeIndex(oldDeployment, upgradeIndex) {
654
+ if (typeof upgradeIndex === 'undefined') {
655
+ return;
656
+ }
657
+ if (upgradeIndex === 0) {
658
+ if (oldDeployment) {
659
+ return { ...oldDeployment, newlyDeployed: false };
660
+ }
661
+ }
662
+ else if (upgradeIndex === 1) {
663
+ if (!oldDeployment) {
664
+ throw new Error('upgradeIndex === 1 : expects Deployments to already exists');
665
+ }
666
+ if ((oldDeployment.history && oldDeployment.history.length > 0) ||
667
+ (oldDeployment.numDeployments && oldDeployment.numDeployments > 1)) {
668
+ return { ...oldDeployment, newlyDeployed: false };
669
+ }
670
+ }
671
+ else {
672
+ if (!oldDeployment) {
673
+ throw new Error(`upgradeIndex === ${upgradeIndex} : expects Deployments to already exists`);
674
+ }
675
+ if (!oldDeployment.history) {
676
+ if (oldDeployment.numDeployments && oldDeployment.numDeployments > 1) {
677
+ if (oldDeployment.numDeployments > upgradeIndex) {
678
+ return { ...oldDeployment, newlyDeployed: false };
679
+ }
680
+ else if (oldDeployment.numDeployments < upgradeIndex) {
681
+ throw new Error(`upgradeIndex === ${upgradeIndex} : expects Deployments numDeployments to be at least ${upgradeIndex}`);
682
+ }
683
+ }
684
+ else {
685
+ throw new Error(`upgradeIndex > 1 : expects Deployments history to exists, or numDeployments to be greater than 1`);
686
+ }
687
+ }
688
+ else if (oldDeployment.history.length > upgradeIndex - 1) {
689
+ return { ...oldDeployment, newlyDeployed: false };
690
+ }
691
+ else if (oldDeployment.history.length < upgradeIndex - 1) {
692
+ throw new Error(`upgradeIndex === ${upgradeIndex} : expects Deployments history length to be at least ${upgradeIndex - 1}`);
693
+ }
694
+ }
695
+ }
696
+ async function _getProxyInfo(name, options) {
697
+ const oldDeployment = await getDeploymentOrNUll(name);
698
+ let contractName = options.contract;
699
+ let implementationName = name + '_Implementation';
700
+ let updateMethod;
701
+ let updateArgs;
702
+ let upgradeIndex;
703
+ let proxyContract = eip173Proxy;
704
+ let checkABIConflict = true;
705
+ let checkProxyAdmin = true;
706
+ let viaAdminContract;
707
+ let proxyArgsTemplate = ['{implementation}', '{admin}', '{data}'];
708
+ let upgradeMethod;
709
+ let upgradeArgsTemplate = [];
710
+ if (typeof options.proxy === 'object') {
711
+ if (options.proxy.proxyArgs) {
712
+ proxyArgsTemplate = options.proxy.proxyArgs;
713
+ }
714
+ upgradeIndex = options.proxy.upgradeIndex;
715
+ if (options.proxy.implementationName) {
716
+ implementationName = options.proxy.implementationName;
717
+ if (implementationName === name) {
718
+ throw new Error(`"implementationName" cannot be equal to the deployment's name (${name}) as this is used for the proxy itself.`);
719
+ }
720
+ if (!contractName) {
721
+ contractName = implementationName;
722
+ }
723
+ }
724
+ if ('methodName' in options.proxy) {
725
+ updateMethod = options.proxy.methodName;
726
+ if ('execute' in options.proxy) {
727
+ throw new Error(`cannot have both "methodName" and "execute" options for proxy`);
728
+ }
729
+ }
730
+ else if ('execute' in options.proxy && options.proxy.execute) {
731
+ if ('methodName' in options.proxy.execute) {
732
+ updateMethod = options.proxy.execute.methodName;
733
+ updateArgs = options.proxy.execute.args;
734
+ if ('init' in options.proxy.execute || 'onUpgrade' in options.proxy.execute) {
735
+ throw new Error(`cannot have both "methodName" and ("onUpgrade" or "init") options for proxy.execute`);
736
+ }
737
+ }
738
+ else if (('init' in options.proxy.execute && options.proxy.execute.init) ||
739
+ ('onUpgrade' in options.proxy.execute && options.proxy.execute.onUpgrade)) {
740
+ if (oldDeployment) {
741
+ updateMethod = options.proxy.execute.onUpgrade?.methodName;
742
+ updateArgs = options.proxy.execute.onUpgrade?.args;
743
+ }
744
+ else {
745
+ updateMethod = options.proxy.execute.init.methodName;
746
+ updateArgs = options.proxy.execute.init.args;
747
+ }
748
+ }
749
+ }
750
+ checkABIConflict = options.proxy.checkABIConflict ?? checkABIConflict;
751
+ checkProxyAdmin = options.proxy.checkProxyAdmin ?? checkProxyAdmin;
752
+ if (options.proxy.proxyContract) {
753
+ if (typeof options.proxy.proxyContract === 'string') {
754
+ try {
755
+ proxyContract = await partialExtension.getExtendedArtifact(options.proxy.proxyContract);
756
+ }
757
+ catch (e) { }
758
+ if (!proxyContract || proxyContract === eip173Proxy) {
759
+ if (options.proxy.proxyContract === 'EIP173ProxyWithReceive') {
760
+ proxyContract = eip173ProxyWithReceive;
761
+ }
762
+ else if (options.proxy.proxyContract === 'EIP173Proxy') {
763
+ proxyContract = eip173Proxy;
764
+ }
765
+ else if (options.proxy.proxyContract === 'OpenZeppelinTransparentProxy') {
766
+ checkABIConflict = false;
767
+ proxyContract = OpenZeppelinTransparentProxy;
768
+ viaAdminContract = 'DefaultProxyAdmin';
769
+ }
770
+ else if (options.proxy.proxyContract === 'OptimizedTransparentProxy') {
771
+ checkABIConflict = false;
772
+ proxyContract = OptimizedTransparentUpgradeableProxy;
773
+ viaAdminContract = 'DefaultProxyAdmin';
774
+ }
775
+ else if (options.proxy.proxyContract === 'UUPS') {
776
+ checkABIConflict = false;
777
+ checkProxyAdmin = false;
778
+ proxyContract = erc1967Proxy;
779
+ proxyArgsTemplate = ['{implementation}', '{data}'];
780
+ }
781
+ else {
782
+ throw new Error(`no contract found for ${options.proxy.proxyContract}`);
783
+ }
784
+ }
785
+ }
786
+ }
787
+ if (options.proxy.viaAdminContract) {
788
+ viaAdminContract = options.proxy.viaAdminContract;
789
+ }
790
+ if (options.proxy.upgradeFunction) {
791
+ upgradeMethod = options.proxy.upgradeFunction.methodName;
792
+ upgradeArgsTemplate = options.proxy.upgradeFunction.upgradeArgs;
793
+ }
794
+ }
795
+ else if (typeof options.proxy === 'string') {
796
+ updateMethod = options.proxy;
797
+ }
798
+ const proxyName = name + '_Proxy';
799
+ const { address: owner } = await getProxyOwner(options);
800
+ const implementationArgs = options.args ? [...options.args] : [];
801
+ const implementationOptions = {
802
+ contract: contractName || name,
803
+ from: options.from,
804
+ autoMine: options.autoMine,
805
+ estimateGasExtra: options.estimateGasExtra,
806
+ estimatedGasLimit: options.estimatedGasLimit,
807
+ gasPrice: options.gasPrice,
808
+ maxFeePerGas: options.maxFeePerGas,
809
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas,
810
+ log: options.log,
811
+ deterministicDeployment: options.deterministicDeployment,
812
+ libraries: options.libraries,
813
+ linkedData: options.linkedData,
814
+ args: implementationArgs,
815
+ skipIfAlreadyDeployed: options.skipIfAlreadyDeployed,
816
+ waitConfirmations: options.waitConfirmations,
817
+ };
818
+ const { artifact } = await getArtifactFromOptions(name, implementationOptions);
819
+ const proxyContractConstructor = proxyContract.abi.find((v) => v.type === 'constructor');
820
+ const mergedABI = (0, utils_2.mergeABIs)([proxyContract.abi, artifact.abi], {
821
+ check: checkABIConflict,
822
+ skipSupportsInterface: true,
823
+ }).filter((v) => v.type !== 'constructor');
824
+ mergedABI.push(proxyContractConstructor);
825
+ const constructor = artifact.abi.find((fragment) => fragment.type === 'constructor');
826
+ if ((!constructor && implementationArgs.length > 0) ||
827
+ (constructor && constructor.inputs.length !== implementationArgs.length)) {
828
+ throw new Error(`The number of arguments passed to not match the number of argument in the implementation constructor.
829
+ Please specify the correct number of arguments as part of the deploy options: "args"`);
830
+ }
831
+ if (updateMethod) {
832
+ const updateMethodFound = artifact.abi.find((fragment) => fragment.type === 'function' && fragment.name === updateMethod);
833
+ if (!updateMethodFound) {
834
+ throw new Error(`contract need to implement function ${updateMethod}`);
835
+ }
836
+ if (!updateArgs) {
837
+ if (implementationArgs.length === updateMethodFound.inputs.length) {
838
+ updateArgs = implementationArgs;
839
+ }
840
+ else {
841
+ throw new Error(`
842
+ If only the methodName (and no args) is specified for proxy deployment, the arguments used for the implementation contract will be reused for the update method.
843
+ This allow your contract to both be deployed directly and deployed via proxy.
844
+
845
+ Currently your contract implementation's constructor do not have the same number of arguments as the update method.
846
+ You can either changes the contract or use the "execute" options and specify different arguments for the update method.
847
+ Note that in this case, the contract deployment will not behave the same if deployed without proxy.
848
+ `);
849
+ }
850
+ }
851
+ }
852
+ if (!updateArgs) {
853
+ updateArgs = implementationArgs;
854
+ }
855
+ let proxyAdminName;
856
+ const proxyAdmin = owner;
857
+ let currentProxyAdminOwner;
858
+ let proxyAdminDeployed;
859
+ let proxyAdminContract;
860
+ if (viaAdminContract) {
861
+ let proxyAdminArtifactNameOrContract;
862
+ if (typeof viaAdminContract === 'string') {
863
+ proxyAdminName = viaAdminContract;
864
+ proxyAdminArtifactNameOrContract = viaAdminContract;
865
+ }
866
+ else {
867
+ proxyAdminName = viaAdminContract.name;
868
+ if (!viaAdminContract.artifact) {
869
+ proxyAdminDeployed = await partialExtension.get(proxyAdminName);
870
+ }
871
+ proxyAdminArtifactNameOrContract = viaAdminContract.artifact;
872
+ }
873
+ if (typeof proxyAdminArtifactNameOrContract === 'string') {
874
+ try {
875
+ proxyAdminContract = await partialExtension.getExtendedArtifact(proxyAdminArtifactNameOrContract);
876
+ }
877
+ catch (e) { }
878
+ if (!proxyAdminContract) {
879
+ if (viaAdminContract === 'DefaultProxyAdmin') {
880
+ proxyAdminContract = DefaultProxyAdmin;
881
+ }
882
+ else {
883
+ throw new Error(`no contract found for ${proxyAdminArtifactNameOrContract}`);
884
+ }
885
+ }
886
+ }
887
+ else {
888
+ proxyAdminContract = proxyAdminArtifactNameOrContract;
889
+ }
890
+ }
891
+ if (!upgradeMethod) {
892
+ if (viaAdminContract) {
893
+ if (updateMethod) {
894
+ upgradeMethod = 'upgradeAndCall';
895
+ upgradeArgsTemplate = ['{proxy}', '{implementation}', '{data}'];
896
+ }
897
+ else {
898
+ upgradeMethod = 'upgrade';
899
+ upgradeArgsTemplate = ['{proxy}', '{implementation}'];
900
+ }
901
+ }
902
+ else if (updateMethod) {
903
+ upgradeMethod = 'upgradeToAndCall';
904
+ upgradeArgsTemplate = ['{implementation}', '{data}'];
905
+ }
906
+ else {
907
+ upgradeMethod = 'upgradeTo';
908
+ upgradeArgsTemplate = ['{implementation}'];
909
+ }
910
+ }
911
+ return {
912
+ proxyName,
913
+ proxyContract,
914
+ proxyArgsTemplate,
915
+ mergedABI,
916
+ viaAdminContract,
917
+ proxyAdminDeployed,
918
+ proxyAdminName,
919
+ proxyAdminContract,
920
+ owner,
921
+ proxyAdmin,
922
+ currentProxyAdminOwner,
923
+ artifact,
924
+ implementationArgs,
925
+ implementationName,
926
+ implementationOptions,
927
+ oldDeployment,
928
+ updateMethod,
929
+ updateArgs,
930
+ upgradeIndex,
931
+ checkProxyAdmin,
932
+ upgradeMethod,
933
+ upgradeArgsTemplate,
934
+ };
935
+ }
936
+ async function _deployViaProxy(name, options) {
937
+ let { oldDeployment, updateMethod, updateArgs, upgradeIndex, viaAdminContract, proxyAdminDeployed, proxyAdminName, proxyAdminContract, owner, proxyAdmin, currentProxyAdminOwner, implementationName, implementationOptions, proxyName, proxyContract, proxyArgsTemplate, mergedABI, checkProxyAdmin, upgradeMethod, upgradeArgsTemplate, } = await _getProxyInfo(name, options);
938
+ const deployResult = _checkUpgradeIndex(oldDeployment, upgradeIndex);
939
+ if (deployResult) {
940
+ return deployResult;
941
+ }
942
+ if (viaAdminContract) {
943
+ if (!proxyAdminName) {
944
+ throw new Error(`no proxy admin name even though viaAdminContract is not undefined`);
945
+ }
946
+ if (!proxyAdminDeployed) {
947
+ proxyAdminDeployed = await _deployOne(proxyAdminName, {
948
+ from: options.from,
949
+ autoMine: options.autoMine,
950
+ estimateGasExtra: options.estimateGasExtra,
951
+ estimatedGasLimit: options.estimatedGasLimit,
952
+ gasPrice: options.gasPrice,
953
+ maxFeePerGas: options.maxFeePerGas,
954
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas,
955
+ log: options.log,
956
+ contract: proxyAdminContract,
957
+ deterministicDeployment: options.deterministicDeployment,
958
+ skipIfAlreadyDeployed: true,
959
+ args: [owner],
960
+ waitConfirmations: options.waitConfirmations,
961
+ });
962
+ }
963
+ proxyAdmin = proxyAdminDeployed.address;
964
+ currentProxyAdminOwner = (await read(proxyAdminName, 'owner'));
965
+ if (currentProxyAdminOwner.toLowerCase() !== owner.toLowerCase()) {
966
+ throw new Error(`To change owner/admin, you need to call transferOwnership on ${proxyAdminName}`);
967
+ }
968
+ if (currentProxyAdminOwner === constants_1.AddressZero) {
969
+ throw new Error(`The Proxy Admin (${proxyAdminName}) belongs to no-one. The Proxy cannot be upgraded anymore`);
970
+ }
971
+ }
972
+ const implementation = await _deployOne(implementationName, implementationOptions);
973
+ if (!oldDeployment || implementation.newlyDeployed) {
974
+ const implementationContract = new contracts_1.Contract(implementation.address, implementation.abi);
975
+ let data = '0x';
976
+ if (updateMethod) {
977
+ if (!implementationContract[updateMethod]) {
978
+ throw new Error(`contract need to implement function ${updateMethod}`);
979
+ }
980
+ const txData = await implementationContract.populateTransaction[updateMethod](...updateArgs);
981
+ data = txData.data || '0x';
982
+ }
983
+ let proxy = await getDeploymentOrNUll(proxyName);
984
+ if (!proxy) {
985
+ const proxyOptions = { ...options };
986
+ delete proxyOptions.proxy;
987
+ delete proxyOptions.libraries;
988
+ proxyOptions.contract = proxyContract;
989
+ proxyOptions.args = replaceTemplateArgs(proxyArgsTemplate, {
990
+ implementationAddress: implementation.address,
991
+ proxyAdmin,
992
+ data,
993
+ });
994
+ proxy = await _deployOne(proxyName, proxyOptions, true);
995
+ }
996
+ else {
997
+ let from = options.from;
998
+ const ownerStorage = await provider.getStorageAt(proxy.address, '0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103');
999
+ const currentOwner = (0, address_1.getAddress)(`0x${ownerStorage.substr(-40)}`);
1000
+ if (currentOwner === constants_1.AddressZero) {
1001
+ if (checkProxyAdmin) {
1002
+ throw new Error('The Proxy belongs to no-one. It cannot be upgraded anymore');
1003
+ }
1004
+ }
1005
+ else if (currentOwner.toLowerCase() !== proxyAdmin.toLowerCase()) {
1006
+ throw new Error(`To change owner/admin, you need to call the proxy directly, it currently is ${currentOwner}`);
1007
+ }
1008
+ else {
1009
+ from = currentOwner;
1010
+ }
1011
+ const oldProxy = proxy.abi.find((frag) => frag.name === 'changeImplementation');
1012
+ if (oldProxy) {
1013
+ upgradeMethod = 'changeImplementation';
1014
+ upgradeArgsTemplate = ['{implementation}', '{data}'];
1015
+ }
1016
+ const proxyAddress = proxy.address;
1017
+ const upgradeArgs = replaceTemplateArgs(upgradeArgsTemplate, {
1018
+ implementationAddress: implementation.address,
1019
+ proxyAdmin,
1020
+ data,
1021
+ proxyAddress,
1022
+ });
1023
+ if (!upgradeMethod) {
1024
+ throw new Error(`No upgrade method found, cannot make upgrades`);
1025
+ }
1026
+ let executeReceipt;
1027
+ if (proxyAdminName) {
1028
+ if (oldProxy) {
1029
+ throw new Error(`Old Proxy do not support Proxy Admin contracts`);
1030
+ }
1031
+ if (!currentProxyAdminOwner) {
1032
+ throw new Error(`no currentProxyAdminOwner found in ProxyAdmin`);
1033
+ }
1034
+ executeReceipt = await execute(proxyAdminName, { ...options, from: currentProxyAdminOwner }, upgradeMethod, ...upgradeArgs);
1035
+ }
1036
+ else {
1037
+ executeReceipt = await execute(name, { ...options, from }, upgradeMethod, ...upgradeArgs);
1038
+ }
1039
+ if (!executeReceipt) {
1040
+ throw new Error(`could not execute ${upgradeMethod}`);
1041
+ }
1042
+ }
1043
+ const proxiedDeployment = {
1044
+ ...proxyContract,
1045
+ receipt: proxy.receipt,
1046
+ address: proxy.address,
1047
+ linkedData: options.linkedData,
1048
+ abi: mergedABI,
1049
+ implementation: implementation.address,
1050
+ args: proxy.args,
1051
+ execute: updateMethod
1052
+ ? {
1053
+ methodName: updateMethod,
1054
+ args: updateArgs,
1055
+ }
1056
+ : undefined,
1057
+ };
1058
+ if (oldDeployment) {
1059
+ if (oldDeployment.history) {
1060
+ proxiedDeployment.history = proxiedDeployment.history
1061
+ ? proxiedDeployment.history.concat([oldDeployment])
1062
+ : [oldDeployment];
1063
+ }
1064
+ }
1065
+ await saveDeployment(name, proxiedDeployment);
1066
+ const deployment = await partialExtension.get(name);
1067
+ return {
1068
+ ...deployment,
1069
+ newlyDeployed: true,
1070
+ };
1071
+ }
1072
+ else {
1073
+ if (oldDeployment.implementation !== implementation.address) {
1074
+ const proxiedDeployment = {
1075
+ ...oldDeployment,
1076
+ implementation: implementation.address,
1077
+ linkedData: options.linkedData,
1078
+ abi: mergedABI,
1079
+ execute: updateMethod
1080
+ ? {
1081
+ methodName: updateMethod,
1082
+ args: updateArgs,
1083
+ }
1084
+ : undefined,
1085
+ };
1086
+ if (oldDeployment.history) {
1087
+ proxiedDeployment.history = proxiedDeployment.history
1088
+ ? proxiedDeployment.history.concat([oldDeployment])
1089
+ : [oldDeployment];
1090
+ }
1091
+ await saveDeployment(name, proxiedDeployment);
1092
+ }
1093
+ const deployment = await partialExtension.get(name);
1094
+ return {
1095
+ ...deployment,
1096
+ newlyDeployed: false,
1097
+ };
1098
+ }
1099
+ }
1100
+ async function getProxyOwner(options) {
1101
+ let address = options.from;
1102
+ if (typeof options.proxy === 'object') {
1103
+ address = options.proxy.owner || address;
1104
+ }
1105
+ return getFrom(address);
1106
+ }
1107
+ async function getDiamondOwner(options) {
1108
+ let address = options.from;
1109
+ address = options.owner || address;
1110
+ return getFrom(address);
1111
+ }
1112
+ async function getOptionalFrom(from) {
1113
+ if (!from) {
1114
+ return {
1115
+ address: from,
1116
+ ethersSigner: undefined,
1117
+ hardwareWallet: undefined,
1118
+ };
1119
+ }
1120
+ return getFrom(from);
1121
+ }
1122
+ let ledgerSigner;
1123
+ async function getFrom(from) {
1124
+ let ethersSigner;
1125
+ let wallet;
1126
+ let hardwareWallet = undefined;
1127
+ let unknown = false;
1128
+ let derivationPath = undefined;
1129
+ if (from.length >= 64) {
1130
+ if (from.length === 64) {
1131
+ from = '0x' + from;
1132
+ }
1133
+ if (network.zksync) {
1134
+ wallet = new zk.Wallet(from, provider);
1135
+ ethersSigner = wallet;
1136
+ }
1137
+ else if (network.tron) {
1138
+ wallet = provider.addSigner(from);
1139
+ ethersSigner = wallet;
1140
+ }
1141
+ else {
1142
+ wallet = new wallet_1.Wallet(from, provider);
1143
+ ethersSigner = wallet;
1144
+ }
1145
+ from = wallet.address;
1146
+ }
1147
+ else {
1148
+ if (availableAccounts[from.toLowerCase()]) {
1149
+ ethersSigner = provider.getSigner(from);
1150
+ }
1151
+ else {
1152
+ const registeredProtocol = deploymentManager.addressesToProtocol[from.toLowerCase()];
1153
+ if (registeredProtocol) {
1154
+ if (registeredProtocol === 'external') {
1155
+ ethersSigner = provider.getSigner(from);
1156
+ ethersSigner.sendTransaction = async (txRequest) => {
1157
+ const response = await enquirer_1.default.prompt({
1158
+ type: 'input',
1159
+ name: 'hash',
1160
+ message: `
1161
+ tx hash please
1162
+ to : ${txRequest.to}
1163
+ data : ${txRequest.data}
1164
+ value : ${txRequest.value}
1165
+ `,
1166
+ });
1167
+ return provider.getTransaction(response.hash);
1168
+ };
1169
+ hardwareWallet = 'external';
1170
+ }
1171
+ else if (registeredProtocol.startsWith('ledger')) {
1172
+ if (!LedgerSigner) {
1173
+ let error;
1174
+ try {
1175
+ ethersprojectHardwareWalletsModule = require('@ethersproject/hardware-wallets');
1176
+ LedgerSigner = ethersprojectHardwareWalletsModule.LedgerSigner;
1177
+ }
1178
+ catch (e) {
1179
+ error = e;
1180
+ try {
1181
+ andrestEthersLedgerModule = require('@anders-t/ethers-ledger');
1182
+ LedgerSigner = andrestEthersLedgerModule.LedgerSigner;
1183
+ error = undefined;
1184
+ }
1185
+ catch (e) {
1186
+ error = e;
1187
+ }
1188
+ }
1189
+ if (error) {
1190
+ console.error(`failed to loader hardhware wallet module for ledger, you can either use "@ethersproject/hardware-wallets" which as time of writing does not work or use "@anders-t/ethers-ledger."`);
1191
+ throw error;
1192
+ }
1193
+ }
1194
+ if (ledgerSigner) {
1195
+ const __eth = await ledgerSigner._eth;
1196
+ await __eth.transport.device.close();
1197
+ ledgerSigner = undefined;
1198
+ }
1199
+ if (ethersprojectHardwareWalletsModule) {
1200
+ derivationPath = (0, hdpath_1.getDerivationPath)(network.config.chainId);
1201
+ ethersSigner = new LedgerSigner(provider, 'default', derivationPath);
1202
+ }
1203
+ else {
1204
+ ethersSigner = new LedgerSigner(provider, registeredProtocol);
1205
+ }
1206
+ ledgerSigner = ethersSigner;
1207
+ }
1208
+ else if (registeredProtocol.startsWith('trezor')) {
1209
+ if (!TrezorSigner) {
1210
+ let error;
1211
+ try {
1212
+ const hardwareWalletModule = require('@nxqbao/eth-signer-trezor');
1213
+ derivationPath = (0, hdpath_1.getDerivationPath)(network.config.chainId);
1214
+ if (!derivationPath) {
1215
+ throw new Error(`network is currently unsupported with trezor`);
1216
+ }
1217
+ TrezorSigner = hardwareWalletModule.TrezorSigner;
1218
+ }
1219
+ catch (e) {
1220
+ error = e;
1221
+ }
1222
+ if (error) {
1223
+ console.error(`failed to loader hardware wallet module for trezor`);
1224
+ throw error;
1225
+ }
1226
+ }
1227
+ if (!hardwareSigner) {
1228
+ hardwareSigner = new TrezorSigner(provider, derivationPath, undefined, from, 'hardhat-deploy-trezor');
1229
+ }
1230
+ ethersSigner = hardwareSigner;
1231
+ hardwareWallet = 'trezor';
1232
+ }
1233
+ else if (registeredProtocol.startsWith('privatekey')) {
1234
+ ethersSigner = new wallet_1.Wallet(registeredProtocol.substr(13), provider);
1235
+ }
1236
+ else if (registeredProtocol.startsWith('gnosis')) {
1237
+ ethersSigner = new wallet_1.Wallet(registeredProtocol.substr(13), provider);
1238
+ }
1239
+ }
1240
+ }
1241
+ }
1242
+ if (!ethersSigner) {
1243
+ unknown = true;
1244
+ ethersSigner = provider.getSigner(from);
1245
+ }
1246
+ return { address: from, ethersSigner, hardwareWallet, unknown };
1247
+ }
1248
+ function sigsFromABI(abi) {
1249
+ return abi
1250
+ .filter((fragment) => fragment.type === 'function')
1251
+ .map((fragment) => abi_1.Interface.getSighash(abi_1.FunctionFragment.from(fragment)));
1252
+ }
1253
+ async function _deployViaDiamondProxy(name, options) {
1254
+ let proxy;
1255
+ const proxyName = name + '_DiamondProxy';
1256
+ const oldDeployment = await getDeploymentOrNUll(name);
1257
+ if (oldDeployment) {
1258
+ proxy = await getDeployment(proxyName);
1259
+ }
1260
+ if (proxy && proxy.deployedBytecode === old_diamondbase_json_1.default.deployedBytecode) {
1261
+ return _old_deployViaDiamondProxy(name, options);
1262
+ }
1263
+ const deployResult = _checkUpgradeIndex(oldDeployment, options.upgradeIndex);
1264
+ if (deployResult) {
1265
+ return deployResult;
1266
+ }
1267
+ let diamondArtifact = diamondBase;
1268
+ if (options.diamondContract) {
1269
+ if (typeof options.diamondContract === 'string') {
1270
+ diamondArtifact = await partialExtension.getExtendedArtifact(options.diamondContract);
1271
+ }
1272
+ else {
1273
+ diamondArtifact = options.diamondContract;
1274
+ }
1275
+ }
1276
+ const { address: owner } = await getDiamondOwner(options);
1277
+ const newSelectors = [];
1278
+ const facetSnapshot = [];
1279
+ let oldFacets = [];
1280
+ if (proxy) {
1281
+ const diamondProxy = new contracts_1.Contract(proxy.address, proxy.abi, provider);
1282
+ oldFacets = await diamondProxy.facets();
1283
+ }
1284
+ const facetsSet = [...options.facets];
1285
+ if (options.defaultCutFacet === undefined || options.defaultCutFacet) {
1286
+ facetsSet.push({
1287
+ name: '_DefaultDiamondCutFacet',
1288
+ contract: diamondCutFacet,
1289
+ args: [],
1290
+ deterministic: true,
1291
+ });
1292
+ }
1293
+ if (options.defaultOwnershipFacet === undefined || options.defaultOwnershipFacet) {
1294
+ facetsSet.push({
1295
+ name: '_DefaultDiamondOwnershipFacet',
1296
+ contract: ownershipFacet,
1297
+ args: [],
1298
+ deterministic: true,
1299
+ });
1300
+ }
1301
+ facetsSet.push({
1302
+ name: '_DefaultDiamondLoupeFacet',
1303
+ contract: diamondLoupeFacet,
1304
+ args: [],
1305
+ deterministic: true,
1306
+ });
1307
+ let changesDetected = !oldDeployment;
1308
+ let abi = diamondArtifact.abi.concat([]);
1309
+ const facetCuts = [];
1310
+ let facetFound;
1311
+ const excludeSelectors = options.excludeSelectors || {};
1312
+ for (const facet of facetsSet) {
1313
+ let deterministicFacet = true;
1314
+ let facetName;
1315
+ let artifact;
1316
+ let linkedData = options.linkedData;
1317
+ let libraries = options.libraries;
1318
+ let facetArgs = options.facetsArgs;
1319
+ if (typeof facet !== 'string') {
1320
+ if (facet.deterministic !== undefined) {
1321
+ deterministicFacet = facet.deterministic;
1322
+ }
1323
+ }
1324
+ let argsSpecific = false;
1325
+ if (typeof facet === 'string') {
1326
+ artifact = await partialExtension.getExtendedArtifact(facet);
1327
+ facetName = facet;
1328
+ }
1329
+ else {
1330
+ if (facet.linkedData) {
1331
+ linkedData = facet.linkedData;
1332
+ }
1333
+ if (facet.libraries) {
1334
+ libraries = facet.libraries;
1335
+ }
1336
+ if (facet.args !== undefined) {
1337
+ facetArgs = facet.args;
1338
+ argsSpecific = true;
1339
+ }
1340
+ if (facet.contract) {
1341
+ if (typeof facet.contract === 'string') {
1342
+ artifact = await partialExtension.getExtendedArtifact(facet.contract);
1343
+ }
1344
+ else {
1345
+ artifact = facet.contract;
1346
+ }
1347
+ }
1348
+ else {
1349
+ if (!facet.name) {
1350
+ throw new Error(`no name , not contract is specified for facet, cannot proceed`);
1351
+ }
1352
+ artifact = await partialExtension.getExtendedArtifact(facet.name);
1353
+ }
1354
+ facetName = facet.name;
1355
+ if (!facetName) {
1356
+ if (typeof facet.contract === 'string') {
1357
+ facetName = name + '_facet_' + facet.contract;
1358
+ }
1359
+ else {
1360
+ throw new Error(`facet has no name, please specify one`);
1361
+ }
1362
+ }
1363
+ }
1364
+ const constructor = artifact.abi.find((fragment) => fragment.type === 'constructor');
1365
+ if (!argsSpecific && (!constructor || constructor.inputs.length === 0)) {
1366
+ facetArgs = [];
1367
+ }
1368
+ let excludeSighashes = new Set();
1369
+ if (facetName in excludeSelectors) {
1370
+ const iface = new abi_1.Interface(artifact.abi);
1371
+ excludeSighashes = new Set(excludeSelectors[facetName].map((selector) => iface.getSighash(selector)));
1372
+ }
1373
+ abi = (0, utils_2.mergeABIs)([abi, (0, utils_2.filterABI)(artifact.abi, excludeSighashes)], {
1374
+ check: true,
1375
+ skipSupportsInterface: false,
1376
+ });
1377
+ const implementation = await _deployOne(facetName, {
1378
+ contract: artifact,
1379
+ from: options.from,
1380
+ autoMine: options.autoMine,
1381
+ estimateGasExtra: options.estimateGasExtra,
1382
+ estimatedGasLimit: options.estimatedGasLimit,
1383
+ gasPrice: options.gasPrice,
1384
+ maxFeePerGas: options.maxFeePerGas,
1385
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas,
1386
+ log: options.log,
1387
+ libraries,
1388
+ linkedData,
1389
+ args: facetArgs,
1390
+ deterministicDeployment: deterministicFacet,
1391
+ });
1392
+ let facetAddress;
1393
+ if (implementation.newlyDeployed) {
1394
+ facetAddress = implementation.address;
1395
+ const newFacet = {
1396
+ facetAddress,
1397
+ functionSelectors: sigsFromABI((0, utils_2.filterABI)(implementation.abi, excludeSighashes)),
1398
+ };
1399
+ facetSnapshot.push(newFacet);
1400
+ newSelectors.push(...newFacet.functionSelectors);
1401
+ }
1402
+ else {
1403
+ const oldImpl = await getDeployment(facetName);
1404
+ facetAddress = oldImpl.address;
1405
+ const newFacet = {
1406
+ facetAddress,
1407
+ functionSelectors: sigsFromABI((0, utils_2.filterABI)(oldImpl.abi, excludeSighashes)),
1408
+ };
1409
+ facetSnapshot.push(newFacet);
1410
+ newSelectors.push(...newFacet.functionSelectors);
1411
+ }
1412
+ if (options.execute && !options.execute.contract) {
1413
+ const methods = artifact.abi.filter((v) => v.name === options.execute?.methodName);
1414
+ if (methods.length > 0) {
1415
+ if (methods.length > 1) {
1416
+ throw new Error(`multiple method named "${options.execute.methodName}" found in facet`);
1417
+ }
1418
+ else {
1419
+ if (facetFound) {
1420
+ throw new Error(`multiple facet with method named "${options.execute.methodName}"`);
1421
+ }
1422
+ else {
1423
+ facetFound = facetAddress;
1424
+ }
1425
+ }
1426
+ }
1427
+ }
1428
+ }
1429
+ const oldSelectors = [];
1430
+ const oldSelectorsFacetAddress = {};
1431
+ for (const oldFacet of oldFacets) {
1432
+ for (const selector of oldFacet.functionSelectors) {
1433
+ oldSelectors.push(selector);
1434
+ oldSelectorsFacetAddress[selector] = oldFacet.facetAddress;
1435
+ }
1436
+ }
1437
+ for (const newFacet of facetSnapshot) {
1438
+ const selectorsToAdd = [];
1439
+ const selectorsToReplace = [];
1440
+ for (const selector of newFacet.functionSelectors) {
1441
+ if (oldSelectors.indexOf(selector) >= 0) {
1442
+ if (oldSelectorsFacetAddress[selector].toLowerCase() !== newFacet.facetAddress.toLowerCase()) {
1443
+ selectorsToReplace.push(selector);
1444
+ }
1445
+ }
1446
+ else {
1447
+ selectorsToAdd.push(selector);
1448
+ }
1449
+ }
1450
+ if (selectorsToReplace.length > 0) {
1451
+ changesDetected = true;
1452
+ facetCuts.push({
1453
+ facetAddress: newFacet.facetAddress,
1454
+ functionSelectors: selectorsToReplace,
1455
+ action: types_1.FacetCutAction.Replace,
1456
+ });
1457
+ }
1458
+ if (selectorsToAdd.length > 0) {
1459
+ changesDetected = true;
1460
+ facetCuts.push({
1461
+ facetAddress: newFacet.facetAddress,
1462
+ functionSelectors: selectorsToAdd,
1463
+ action: types_1.FacetCutAction.Add,
1464
+ });
1465
+ }
1466
+ }
1467
+ const selectorsToDelete = [];
1468
+ for (const selector of oldSelectors) {
1469
+ if (newSelectors.indexOf(selector) === -1) {
1470
+ selectorsToDelete.push(selector);
1471
+ }
1472
+ }
1473
+ if (selectorsToDelete.length > 0) {
1474
+ changesDetected = true;
1475
+ facetCuts.unshift({
1476
+ facetAddress: '0x0000000000000000000000000000000000000000',
1477
+ functionSelectors: selectorsToDelete,
1478
+ action: types_1.FacetCutAction.Remove,
1479
+ });
1480
+ }
1481
+ let executeData = '0x';
1482
+ let executeAddress = '0x0000000000000000000000000000000000000000';
1483
+ if (options.execute) {
1484
+ let addressSpecified;
1485
+ let executionContract = new contracts_1.Contract('0x0000000000000000000000000000000000000001', abi);
1486
+ if (options.execute.contract) {
1487
+ if (typeof options.execute.contract === 'string') {
1488
+ const executionDeployment = await _deployOne(options.execute.contract, {
1489
+ from: options.from,
1490
+ autoMine: options.autoMine,
1491
+ estimateGasExtra: options.estimateGasExtra,
1492
+ estimatedGasLimit: options.estimatedGasLimit,
1493
+ gasPrice: options.gasPrice,
1494
+ maxFeePerGas: options.maxFeePerGas,
1495
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas,
1496
+ log: options.log,
1497
+ deterministicDeployment: true,
1498
+ });
1499
+ executionContract = new contracts_1.Contract(executionDeployment.address, executionDeployment.abi);
1500
+ addressSpecified = executionContract.address;
1501
+ }
1502
+ else {
1503
+ const executionDeployment = await _deployOne(options.execute.contract.name, {
1504
+ from: options.from,
1505
+ contract: options.execute.contract.artifact,
1506
+ args: options.execute.contract.args,
1507
+ autoMine: options.autoMine,
1508
+ estimateGasExtra: options.estimateGasExtra,
1509
+ estimatedGasLimit: options.estimatedGasLimit,
1510
+ gasPrice: options.gasPrice,
1511
+ maxFeePerGas: options.maxFeePerGas,
1512
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas,
1513
+ log: options.log,
1514
+ deterministicDeployment: true,
1515
+ });
1516
+ executionContract = new contracts_1.Contract(executionDeployment.address, executionDeployment.abi);
1517
+ }
1518
+ }
1519
+ const txData = await executionContract.populateTransaction[options.execute.methodName](...options.execute.args);
1520
+ executeData = txData.data || '0x';
1521
+ executeAddress = addressSpecified || facetFound || '0x0000000000000000000000000000000000000000';
1522
+ }
1523
+ if (changesDetected) {
1524
+ if (!proxy) {
1525
+ const diamondConstructorArgs = options.diamondContractArgs || [
1526
+ '{owner}',
1527
+ '{facetCuts}',
1528
+ '{initializations}',
1529
+ ];
1530
+ const initializationsArgIndex = diamondConstructorArgs.indexOf('{initializations}');
1531
+ const erc165InitArgIndex = diamondConstructorArgs.indexOf('{erc165}');
1532
+ const initArgIndex = diamondConstructorArgs.indexOf('{init}');
1533
+ const initAddressArgIndex = diamondConstructorArgs.indexOf('{initAddress}');
1534
+ const initDataArgIndex = diamondConstructorArgs.indexOf('{initData}');
1535
+ const ownerArgIndex = diamondConstructorArgs.indexOf('{owner}');
1536
+ const facetCutsArgIndex = diamondConstructorArgs.indexOf('{facetCuts}');
1537
+ if (initializationsArgIndex >= 0 &&
1538
+ (initArgIndex >= 0 || erc165InitArgIndex >= 0 || initDataArgIndex >= 0)) {
1539
+ throw new Error(`{initializations} found but also one or more of {init} {erc165} {initData}`);
1540
+ }
1541
+ const interfaceList = ['0x48e2b093'];
1542
+ if (options.defaultCutFacet) {
1543
+ interfaceList.push('0x1f931c1c');
1544
+ }
1545
+ if (options.defaultOwnershipFacet) {
1546
+ interfaceList.push('0x7f5828d0');
1547
+ }
1548
+ if (initializationsArgIndex >= 0 || erc165InitArgIndex >= 0) {
1549
+ const diamondERC165InitDeployment = await _deployOne('_DefaultDiamondERC165Init', {
1550
+ from: options.from,
1551
+ deterministicDeployment: true,
1552
+ contract: diamondERC165Init,
1553
+ autoMine: options.autoMine,
1554
+ estimateGasExtra: options.estimateGasExtra,
1555
+ estimatedGasLimit: options.estimatedGasLimit,
1556
+ gasPrice: options.gasPrice,
1557
+ maxFeePerGas: options.maxFeePerGas,
1558
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas,
1559
+ log: options.log,
1560
+ });
1561
+ const diamondERC165InitContract = new contracts_1.Contract(diamondERC165InitDeployment.address, diamondERC165InitDeployment.abi);
1562
+ const interfaceInitTx = await diamondERC165InitContract.populateTransaction.setERC165(interfaceList, []);
1563
+ if (initializationsArgIndex >= 0) {
1564
+ const initializations = [];
1565
+ initializations.push({
1566
+ initContract: interfaceInitTx.to,
1567
+ initData: interfaceInitTx.data,
1568
+ });
1569
+ diamondConstructorArgs[initializationsArgIndex] = initializations;
1570
+ }
1571
+ else {
1572
+ diamondConstructorArgs[erc165InitArgIndex] = {
1573
+ initContract: interfaceInitTx.to,
1574
+ initData: interfaceInitTx.data,
1575
+ };
1576
+ }
1577
+ }
1578
+ if (ownerArgIndex >= 0) {
1579
+ diamondConstructorArgs[ownerArgIndex] = owner;
1580
+ }
1581
+ else {
1582
+ }
1583
+ if (facetCutsArgIndex >= 0) {
1584
+ diamondConstructorArgs[facetCutsArgIndex] = facetCuts;
1585
+ }
1586
+ else {
1587
+ throw new Error(`diamond constructor needs a {facetCuts} argument`);
1588
+ }
1589
+ if (executeData) {
1590
+ if (initializationsArgIndex >= 0) {
1591
+ if (executeData !== '0x') {
1592
+ diamondConstructorArgs[initializationsArgIndex].push({
1593
+ initContract: executeAddress,
1594
+ initData: executeData,
1595
+ });
1596
+ }
1597
+ }
1598
+ else {
1599
+ if (initArgIndex >= 0) {
1600
+ diamondConstructorArgs[initArgIndex] = {
1601
+ initContract: executeAddress,
1602
+ initData: executeData,
1603
+ };
1604
+ }
1605
+ else if (initDataArgIndex >= 0) {
1606
+ diamondConstructorArgs[initDataArgIndex] = executeData;
1607
+ if (initAddressArgIndex >= 0) {
1608
+ diamondConstructorArgs[initAddressArgIndex] = executeAddress;
1609
+ }
1610
+ }
1611
+ else {
1612
+ throw new Error(`no {init} or {initData} found in list of args even though execute is set in option`);
1613
+ }
1614
+ }
1615
+ }
1616
+ let deterministicDiamondAlreadyDeployed = false;
1617
+ let expectedAddress = undefined;
1618
+ let salt = '0x0000000000000000000000000000000000000000000000000000000000000000';
1619
+ if (typeof options.deterministicSalt !== 'undefined') {
1620
+ if (typeof options.deterministicSalt === 'string') {
1621
+ if (options.deterministicSalt === salt) {
1622
+ throw new Error(`deterministicSalt cannot be 0x000..., it needs to be a non-zero bytes32 salt. This is to ensure you are explicitly specyfying different addresses for multiple diamonds`);
1623
+ }
1624
+ else {
1625
+ if (options.deterministicSalt.length !== 66) {
1626
+ throw new Error(`deterministicSalt needs to be a string of 66 hexadecimal characters (including the 0x prefix)`);
1627
+ }
1628
+ salt = options.deterministicSalt;
1629
+ const factory = new DeploymentFactory_1.CustomDeploymentFactory(getArtifact, diamondArtifact, diamondConstructorArgs, network);
1630
+ const create2DeployerAddress = await deploymentManager.getDeterministicDeploymentFactoryAddress();
1631
+ expectedAddress = await factory.getCreate2Address(create2DeployerAddress, salt);
1632
+ const code = await provider.getCode(expectedAddress);
1633
+ if (code !== '0x') {
1634
+ deterministicDiamondAlreadyDeployed = true;
1635
+ }
1636
+ }
1637
+ }
1638
+ else {
1639
+ throw new Error(`deterministicSalt need to be a string, an non-zero bytes32 salt`);
1640
+ }
1641
+ }
1642
+ if (expectedAddress && deterministicDiamondAlreadyDeployed) {
1643
+ proxy = {
1644
+ ...diamondArtifact,
1645
+ address: expectedAddress,
1646
+ args: diamondConstructorArgs,
1647
+ };
1648
+ await saveDeployment(proxyName, proxy);
1649
+ await saveDeployment(name, {
1650
+ ...proxy,
1651
+ linkedData: options.linkedData,
1652
+ facets: facetSnapshot,
1653
+ abi,
1654
+ });
1655
+ await _deployViaDiamondProxy(name, options);
1656
+ }
1657
+ else {
1658
+ proxy = await _deployOne(proxyName, {
1659
+ contract: diamondArtifact,
1660
+ from: options.from,
1661
+ args: diamondConstructorArgs,
1662
+ autoMine: options.autoMine,
1663
+ deterministicDeployment: options.deterministicSalt,
1664
+ estimateGasExtra: options.estimateGasExtra,
1665
+ estimatedGasLimit: options.estimatedGasLimit,
1666
+ gasLimit: options.gasLimit,
1667
+ gasPrice: options.gasPrice,
1668
+ log: options.log,
1669
+ nonce: options.nonce,
1670
+ maxFeePerGas: options.maxFeePerGas,
1671
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas,
1672
+ value: options.value,
1673
+ });
1674
+ await saveDeployment(proxyName, { ...proxy, abi });
1675
+ await saveDeployment(name, {
1676
+ ...proxy,
1677
+ linkedData: options.linkedData,
1678
+ facets: facetSnapshot,
1679
+ abi,
1680
+ execute: options.execute,
1681
+ });
1682
+ }
1683
+ }
1684
+ else {
1685
+ if (!oldDeployment) {
1686
+ throw new Error(`Cannot find Deployment for ${name}`);
1687
+ }
1688
+ const currentOwner = await read(proxyName, 'owner');
1689
+ if (currentOwner.toLowerCase() !== owner.toLowerCase()) {
1690
+ throw new Error('To change owner, you need to call `transferOwnership`');
1691
+ }
1692
+ if (currentOwner === constants_1.AddressZero) {
1693
+ throw new Error('The Diamond belongs to no-one. It cannot be upgraded anymore');
1694
+ }
1695
+ const executeReceipt = await execute(name, { ...options, from: currentOwner }, 'diamondCut', facetCuts, executeData === '0x'
1696
+ ? '0x0000000000000000000000000000000000000000'
1697
+ : executeAddress || proxy.address, executeData);
1698
+ if (!executeReceipt) {
1699
+ throw new Error('failed to execute');
1700
+ }
1701
+ const diamondDeployment = {
1702
+ ...oldDeployment,
1703
+ linkedData: options.linkedData,
1704
+ address: proxy.address,
1705
+ abi,
1706
+ facets: facetSnapshot,
1707
+ execute: options.execute,
1708
+ };
1709
+ if (oldDeployment.history) {
1710
+ diamondDeployment.history = diamondDeployment.history
1711
+ ? diamondDeployment.history.concat([oldDeployment])
1712
+ : [oldDeployment];
1713
+ }
1714
+ await saveDeployment(name, diamondDeployment);
1715
+ }
1716
+ const deployment = await partialExtension.get(name);
1717
+ return {
1718
+ ...deployment,
1719
+ newlyDeployed: true,
1720
+ };
1721
+ }
1722
+ else {
1723
+ const deployment = await partialExtension.get(name);
1724
+ return {
1725
+ ...deployment,
1726
+ newlyDeployed: false,
1727
+ };
1728
+ }
1729
+ }
1730
+ async function deploy(name, options) {
1731
+ options = { ...options };
1732
+ await init();
1733
+ if (!options.proxy) {
1734
+ return _deployOne(name, options);
1735
+ }
1736
+ return _deployViaProxy(name, options);
1737
+ }
1738
+ async function diamond(name, options) {
1739
+ options = { ...options };
1740
+ await init();
1741
+ return _deployViaDiamondProxy(name, options);
1742
+ }
1743
+ async function rawTx(tx) {
1744
+ tx = { ...tx };
1745
+ await init();
1746
+ const { address: from, ethersSigner, hardwareWallet, unknown } = await getFrom(tx.from);
1747
+ const transactionData = {
1748
+ to: tx.to,
1749
+ gasLimit: tx.gasLimit,
1750
+ gasPrice: tx.gasPrice ? bignumber_1.BigNumber.from(tx.gasPrice) : undefined,
1751
+ maxFeePerGas: tx.maxFeePerGas ? bignumber_1.BigNumber.from(tx.maxFeePerGas) : undefined,
1752
+ maxPriorityFeePerGas: tx.maxPriorityFeePerGas ? bignumber_1.BigNumber.from(tx.maxPriorityFeePerGas) : undefined,
1753
+ value: tx.value ? bignumber_1.BigNumber.from(tx.value) : undefined,
1754
+ nonce: tx.nonce,
1755
+ data: tx.data,
1756
+ };
1757
+ await overrideGasLimit(transactionData, tx, (newOverrides) => ethersSigner.estimateGas(newOverrides));
1758
+ await setupGasPrice(transactionData);
1759
+ await setupNonce(from, transactionData);
1760
+ if (unknown) {
1761
+ throw new errors_1.UnknownSignerError({
1762
+ from,
1763
+ ...transactionData,
1764
+ });
1765
+ }
1766
+ if (hardwareWallet) {
1767
+ log(` please confirm on your ${hardwareWallet}`);
1768
+ }
1769
+ let pendingTx = (await handleSpecificErrors(ethersSigner.sendTransaction(transactionData)));
1770
+ pendingTx = await onPendingTx(pendingTx);
1771
+ if (tx.autoMine) {
1772
+ try {
1773
+ await provider.send('evm_mine', []);
1774
+ }
1775
+ catch (e) { }
1776
+ }
1777
+ return pendingTx.wait();
1778
+ }
1779
+ async function catchUnknownSigner(action, options) {
1780
+ const outputLog = !options || options.log === undefined || options.log;
1781
+ try {
1782
+ if (action instanceof Promise) {
1783
+ await action;
1784
+ }
1785
+ else {
1786
+ await action();
1787
+ }
1788
+ }
1789
+ catch (e) {
1790
+ if (e instanceof errors_1.UnknownSignerError) {
1791
+ const { from, to, data, value, contract } = e.data;
1792
+ if (outputLog) {
1793
+ console.log(`---------------------------------------------------------------------------------------`);
1794
+ console.error('no signer for ' + from);
1795
+ console.log(`Please execute the following:`);
1796
+ console.log(`---------------------------------------------------------------------------------------`);
1797
+ if (contract) {
1798
+ console.log(`
1799
+ from: ${from}
1800
+ to: ${to} (${contract.name})${value ? '\nvalue: ' + (typeof value === 'string' ? value : value.toString()) : ''}
1801
+ method: ${contract.method}
1802
+ args:
1803
+ - ${contract.args.join('\n - ')}
1804
+
1805
+ (raw data: ${data} )
1806
+ `);
1807
+ }
1808
+ else {
1809
+ console.log(`
1810
+ from: ${from}
1811
+ to: ${to ? to : '0x0000000000000000000000000000000000000000'}${value ? '\nvalue: ' + (typeof value === 'string' ? value : value.toString()) : ''}
1812
+ data: ${data}
1813
+ `);
1814
+ }
1815
+ console.log(`---------------------------------------------------------------------------------------`);
1816
+ }
1817
+ if (!value || typeof value === 'string') {
1818
+ return { from, to, value, data };
1819
+ }
1820
+ return { from, to, value: value?.toString(), data };
1821
+ }
1822
+ else {
1823
+ throw e;
1824
+ }
1825
+ }
1826
+ return null;
1827
+ }
1828
+ async function execute(name, options, methodName, ...args) {
1829
+ options = { ...options };
1830
+ await init();
1831
+ const { address: from, ethersSigner, hardwareWallet, unknown } = await getFrom(options.from);
1832
+ let tx;
1833
+ const deployment = await partialExtension.get(name);
1834
+ const abi = deployment.abi;
1835
+ const overrides = {
1836
+ gasLimit: options.gasLimit,
1837
+ gasPrice: options.gasPrice ? bignumber_1.BigNumber.from(options.gasPrice) : undefined,
1838
+ maxFeePerGas: options.maxFeePerGas ? bignumber_1.BigNumber.from(options.maxFeePerGas) : undefined,
1839
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas
1840
+ ? bignumber_1.BigNumber.from(options.maxPriorityFeePerGas)
1841
+ : undefined,
1842
+ value: options.value ? bignumber_1.BigNumber.from(options.value) : undefined,
1843
+ nonce: options.nonce,
1844
+ };
1845
+ const ethersContract = new contracts_1.Contract(deployment.address, abi, ethersSigner);
1846
+ if (!ethersContract.functions[methodName]) {
1847
+ throw new Error(`No method named "${methodName}" on contract deployed as "${name}"`);
1848
+ }
1849
+ const numArguments = ethersContract.interface.getFunction(methodName).inputs.length;
1850
+ if (args.length !== numArguments) {
1851
+ throw new Error(`expected ${numArguments} arguments for method "${methodName}", got ${args.length}`);
1852
+ }
1853
+ await overrideGasLimit(overrides, options, (newOverrides) => {
1854
+ const ethersArgsWithGasLimit = args ? args.concat([newOverrides]) : [newOverrides];
1855
+ return ethersContract.estimateGas[methodName](...ethersArgsWithGasLimit);
1856
+ });
1857
+ await setupGasPrice(overrides);
1858
+ await setupNonce(from, overrides);
1859
+ const ethersArgs = args ? args.concat([overrides]) : [overrides];
1860
+ if (unknown) {
1861
+ const ethersArgs = args ? args.concat([overrides]) : [overrides];
1862
+ const { data } = await ethersContract.populateTransaction[methodName](...ethersArgs);
1863
+ throw new errors_1.UnknownSignerError({
1864
+ from,
1865
+ to: deployment.address,
1866
+ data,
1867
+ value: options.value,
1868
+ contract: {
1869
+ name,
1870
+ method: methodName,
1871
+ args,
1872
+ },
1873
+ });
1874
+ }
1875
+ if (options.log || hardwareWallet) {
1876
+ print(`executing ${name}.${methodName}`);
1877
+ if (hardwareWallet) {
1878
+ print(` (please confirm on your ${hardwareWallet})`);
1879
+ }
1880
+ }
1881
+ if (network.tron) {
1882
+ const method = ethersContract.interface.getFunction(methodName);
1883
+ const methodParams = method.inputs.map((input) => input.type);
1884
+ const funcSig = `${methodName}(${methodParams.join(',')})`;
1885
+ const tronArgs = args.map((a, i) => ({
1886
+ type: methodParams[i],
1887
+ value: a,
1888
+ }));
1889
+ tx = await handleSpecificErrors(ethersSigner.provider.triggerSmartContract(from, deployment.address, funcSig, tronArgs, overrides));
1890
+ }
1891
+ else {
1892
+ tx = await handleSpecificErrors(ethersContract.functions[methodName](...ethersArgs));
1893
+ }
1894
+ tx = await onPendingTx(tx);
1895
+ if (options.log || hardwareWallet) {
1896
+ print(` (tx: ${tx.hash}) ...`);
1897
+ }
1898
+ if (options.autoMine) {
1899
+ try {
1900
+ await provider.send('evm_mine', []);
1901
+ }
1902
+ catch (e) { }
1903
+ }
1904
+ const receipt = await tx.wait();
1905
+ if (options.log || hardwareWallet) {
1906
+ print(`: performed with ${receipt.gasUsed} gas\n`);
1907
+ }
1908
+ return receipt;
1909
+ }
1910
+ async function read(name, options, methodName, ...args) {
1911
+ if (typeof options === 'string') {
1912
+ if (typeof methodName !== 'undefined') {
1913
+ args.unshift(methodName);
1914
+ }
1915
+ methodName = options;
1916
+ options = {};
1917
+ }
1918
+ options = { ...options };
1919
+ await init();
1920
+ if (typeof args === 'undefined') {
1921
+ args = [];
1922
+ }
1923
+ let caller = provider;
1924
+ const { ethersSigner } = await getOptionalFrom(options.from);
1925
+ if (ethersSigner) {
1926
+ caller = ethersSigner;
1927
+ }
1928
+ const deployment = await partialExtension.get(name);
1929
+ if (!deployment) {
1930
+ throw new Error(`no contract named "${name}"`);
1931
+ }
1932
+ const abi = deployment.abi;
1933
+ const overrides = {
1934
+ gasLimit: options.gasLimit,
1935
+ gasPrice: options.gasPrice ? bignumber_1.BigNumber.from(options.gasPrice) : undefined,
1936
+ maxFeePerGas: options.maxFeePerGas ? bignumber_1.BigNumber.from(options.maxFeePerGas) : undefined,
1937
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas
1938
+ ? bignumber_1.BigNumber.from(options.maxPriorityFeePerGas)
1939
+ : undefined,
1940
+ value: options.value ? bignumber_1.BigNumber.from(options.value) : undefined,
1941
+ nonce: options.nonce,
1942
+ };
1943
+ cleanupOverrides(overrides);
1944
+ const ethersContract = new contracts_1.Contract(deployment.address, abi, caller);
1945
+ const method = ethersContract.callStatic[methodName];
1946
+ if (!method) {
1947
+ throw new Error(`no method named "${methodName}" on contract "${name}"`);
1948
+ }
1949
+ if (args.length > 0) {
1950
+ return method(...args, overrides);
1951
+ }
1952
+ else {
1953
+ return method(overrides);
1954
+ }
1955
+ }
1956
+ async function getSigner(address) {
1957
+ await init();
1958
+ const { ethersSigner } = await getFrom(address);
1959
+ return ethersSigner;
1960
+ }
1961
+ const extension = {
1962
+ ...partialExtension,
1963
+ fetchIfDifferent,
1964
+ deploy,
1965
+ diamond: {
1966
+ deploy: diamond,
1967
+ },
1968
+ catchUnknownSigner,
1969
+ execute,
1970
+ rawTx,
1971
+ read,
1972
+ deterministic,
1973
+ getSigner,
1974
+ };
1975
+ const utils = {
1976
+ dealWithPendingTransactions: async (pendingTxs, pendingTxPath, globalGasPrice) => {
1977
+ await init();
1978
+ const txHashes = Object.keys(pendingTxs);
1979
+ for (const txHash of txHashes) {
1980
+ let tx;
1981
+ const txData = pendingTxs[txHash];
1982
+ if (txData.rawTx || txData.decoded) {
1983
+ if (txData.rawTx) {
1984
+ tx = (0, transactions_1.parse)(txData.rawTx);
1985
+ }
1986
+ else {
1987
+ tx = (0, utils_2.recode)(txData.decoded);
1988
+ }
1989
+ }
1990
+ else {
1991
+ console.error(`no access to raw data for tx ${txHash}`);
1992
+ }
1993
+ const txFromPeers = await network.provider.send('eth_getTransactionByHash', [txHash]);
1994
+ let feeHistory = undefined;
1995
+ let newGasPriceS = globalGasPrice;
1996
+ if (!newGasPriceS) {
1997
+ newGasPriceS = await network.provider.send('eth_gasPrice', []);
1998
+ try {
1999
+ feeHistory = await network.provider.send('eth_feeHistory', [4, 'latest', [25, 75]]);
2000
+ }
2001
+ catch (e) { }
2002
+ }
2003
+ const newGasPrice = bignumber_1.BigNumber.from(newGasPriceS);
2004
+ let newBaseFee = undefined;
2005
+ if (feeHistory) {
2006
+ newBaseFee = bignumber_1.BigNumber.from(feeHistory.baseFeePerGas[feeHistory.baseFeePerGas.length - 1]);
2007
+ }
2008
+ const choices = ['skip (forget tx)'];
2009
+ if (!txFromPeers) {
2010
+ if (tx) {
2011
+ choices.unshift('broadcast again');
2012
+ }
2013
+ console.log(`transaction ${txHash} cannot be found among peers`);
2014
+ }
2015
+ else {
2016
+ choices.unshift('continue waiting');
2017
+ if (tx) {
2018
+ console.log(`transaction ${txHash} still pending... It used a gas pricing config of ${tx.gasPrice
2019
+ ? `(gasPrice: ${tx.gasPrice.toString()} wei)`
2020
+ : tx.maxPriorityFeePerGas || tx.maxPriorityFeePerGas
2021
+ ? `maxPriorityFeePerGas: ${tx.maxPriorityFeePerGas?.toString()} maxFeePerGas: ${tx.maxFeePerGas?.toString()}`
2022
+ : ``} ,
2023
+ current gas price is ${newGasPrice.toString()} wei
2024
+ ${newBaseFee ? `new baseFee is ${newBaseFee.toString()}` : ''}
2025
+ `);
2026
+ }
2027
+ else {
2028
+ console.log(`transaction ${txHash} still pending...`);
2029
+ }
2030
+ }
2031
+ if (tx && tx.gasPrice && tx.gasPrice.lt(newGasPrice)) {
2032
+ choices.unshift('increase gas');
2033
+ }
2034
+ else if (tx && (tx.maxFeePerGas || tx.maxPriorityFeePerGas)) {
2035
+ choices.unshift('increase gas');
2036
+ }
2037
+ const prompt = new enquirer_1.default.Select({
2038
+ name: 'action',
2039
+ message: 'Choose what to do with the pending transaction:',
2040
+ choices,
2041
+ });
2042
+ const answer = await prompt.run();
2043
+ let txHashToWait;
2044
+ if (answer !== 'skip (forget tx)') {
2045
+ if (answer === 'continue waiting') {
2046
+ console.log('waiting for transaction...');
2047
+ txHashToWait = txHash;
2048
+ }
2049
+ else if (answer === 'broadcast again') {
2050
+ if (!tx) {
2051
+ throw new Error(`cannot resubmit a tx if info not available`);
2052
+ }
2053
+ if (txData.rawTx) {
2054
+ const tx = (await handleSpecificErrors(provider.sendTransaction(txData.rawTx)));
2055
+ txHashToWait = tx.hash;
2056
+ if (tx.hash !== txHash) {
2057
+ console.error('non mathcing tx hashes after resubmitting...');
2058
+ }
2059
+ console.log('waiting for newly broadcasted tx ...');
2060
+ }
2061
+ else {
2062
+ console.log('resigning the tx...');
2063
+ const { ethersSigner, hardwareWallet } = await getOptionalFrom(tx.from);
2064
+ if (!ethersSigner) {
2065
+ throw new Error('no signer for ' + tx.from);
2066
+ }
2067
+ if (hardwareWallet) {
2068
+ print(` (please confirm on your ${hardwareWallet})`);
2069
+ }
2070
+ const txReq = await handleSpecificErrors(ethersSigner.sendTransaction(cleanupOverrides({
2071
+ to: tx.to,
2072
+ from: tx.from,
2073
+ nonce: tx.nonce,
2074
+ gasLimit: tx.gasLimit,
2075
+ gasPrice: tx.gasPrice,
2076
+ maxFeePerGas: tx.maxFeePerGas,
2077
+ maxPriorityFeePerGas: tx.maxPriorityFeePerGas,
2078
+ data: tx.data,
2079
+ value: tx.value,
2080
+ chainId: tx.chainId,
2081
+ type: tx.type === null ? undefined : tx.type,
2082
+ accessList: tx.accessList,
2083
+ })));
2084
+ txHashToWait = txReq.hash;
2085
+ if (txReq.hash !== txHash) {
2086
+ delete pendingTxs[txHash];
2087
+ if (Object.keys(pendingTxs).length === 0) {
2088
+ fs_extra_1.default.removeSync(pendingTxPath);
2089
+ }
2090
+ else {
2091
+ fs_extra_1.default.writeFileSync(pendingTxPath, JSON.stringify(pendingTxs, utils_1.bnReplacer, ' '));
2092
+ }
2093
+ await onPendingTx(txReq);
2094
+ console.error('non mathcing tx hashes after resubmitting...');
2095
+ }
2096
+ }
2097
+ }
2098
+ else if (answer === 'increase gas') {
2099
+ if (!tx) {
2100
+ throw new Error(`cannot resubmit a tx if info not available`);
2101
+ }
2102
+ const { ethersSigner, hardwareWallet } = await getOptionalFrom(tx.from);
2103
+ if (!ethersSigner) {
2104
+ throw new Error('no signer for ' + tx.from);
2105
+ }
2106
+ if (hardwareWallet) {
2107
+ print(` (please confirm on your ${hardwareWallet})`);
2108
+ }
2109
+ const gasPriceSetup = await getGasPrice();
2110
+ const maxFeePerGas = gasPriceSetup.maxFeePerGas;
2111
+ const maxPriorityFeePerGas = gasPriceSetup.maxPriorityFeePerGas;
2112
+ let gasPrice;
2113
+ if (!maxFeePerGas && !maxPriorityFeePerGas) {
2114
+ gasPrice = gasPriceSetup.gasPrice;
2115
+ if (gasPrice) {
2116
+ console.log('using legacy gasPrice with gasprice passed in');
2117
+ }
2118
+ }
2119
+ const txReq = await handleSpecificErrors(ethersSigner.sendTransaction(cleanupOverrides({
2120
+ to: tx.to,
2121
+ from: tx.from,
2122
+ nonce: tx.nonce,
2123
+ gasLimit: tx.gasLimit,
2124
+ gasPrice,
2125
+ maxFeePerGas,
2126
+ maxPriorityFeePerGas,
2127
+ data: tx.data,
2128
+ value: tx.value,
2129
+ chainId: tx.chainId,
2130
+ type: tx.type === null ? undefined : tx.type,
2131
+ accessList: tx.accessList,
2132
+ })));
2133
+ txHashToWait = txReq.hash;
2134
+ delete pendingTxs[txHash];
2135
+ if (Object.keys(pendingTxs).length === 0) {
2136
+ fs_extra_1.default.removeSync(pendingTxPath);
2137
+ }
2138
+ else {
2139
+ fs_extra_1.default.writeFileSync(pendingTxPath, JSON.stringify(pendingTxs, utils_1.bnReplacer, ' '));
2140
+ }
2141
+ await onPendingTx(txReq);
2142
+ console.log(`new transaction submitted, waiting... ${txReq.hash}`);
2143
+ }
2144
+ }
2145
+ if (txHashToWait) {
2146
+ const receipt = await waitForTx(network.provider, txHashToWait, false);
2147
+ if ((!receipt.status || receipt.status == 1) &&
2148
+ receipt.contractAddress &&
2149
+ txData.name) {
2150
+ await saveDeployment(txData.name, {
2151
+ ...txData.deployment,
2152
+ receipt,
2153
+ });
2154
+ }
2155
+ }
2156
+ delete pendingTxs[txHash];
2157
+ if (Object.keys(pendingTxs).length === 0) {
2158
+ fs_extra_1.default.removeSync(pendingTxPath);
2159
+ }
2160
+ else {
2161
+ fs_extra_1.default.writeFileSync(pendingTxPath, JSON.stringify(pendingTxs, utils_1.bnReplacer, ' '));
2162
+ }
2163
+ }
2164
+ },
2165
+ };
2166
+ extension.call = (options, name, methodName, ...args) => {
2167
+ if (typeof options === 'string') {
2168
+ args = args || [];
2169
+ if (methodName !== undefined) {
2170
+ args.unshift(methodName);
2171
+ }
2172
+ methodName = name;
2173
+ name = options;
2174
+ options = {};
2175
+ }
2176
+ return read(name, options, methodName, ...args);
2177
+ };
2178
+ extension.sendTxAndWait = (options, name, methodName, ...args) => {
2179
+ return execute(name, options, methodName, ...args);
2180
+ };
2181
+ extension.deployIfDifferent = (name, options, contractName, ...args) => {
2182
+ options.contract = contractName;
2183
+ options.args = args;
2184
+ return deploy(name, options);
2185
+ };
2186
+ async function _old_deployViaDiamondProxy(name, options) {
2187
+ if (options.log) {
2188
+ log(`handling old diamond ${name} ...`);
2189
+ }
2190
+ const oldDeployment = await getDeploymentOrNUll(name);
2191
+ let proxy;
2192
+ const deployResult = _checkUpgradeIndex(oldDeployment, options.upgradeIndex);
2193
+ if (deployResult) {
2194
+ return deployResult;
2195
+ }
2196
+ if (options.deterministicSalt) {
2197
+ throw new Error(`old diamonds do not support determinsitc deployment`);
2198
+ }
2199
+ const proxyName = name + '_DiamondProxy';
2200
+ const { address: owner } = await getDiamondOwner(options);
2201
+ const newSelectors = [];
2202
+ const facetSnapshot = [];
2203
+ const oldFacets = [];
2204
+ const selectorToNotTouch = {};
2205
+ for (const selector of [
2206
+ '0xcdffacc6',
2207
+ '0x52ef6b2c',
2208
+ '0xadfca15e',
2209
+ '0x7a0ed627',
2210
+ '0x01ffc9a7',
2211
+ '0x1f931c1c',
2212
+ '0xf2fde38b',
2213
+ '0x8da5cb5b',
2214
+ ]) {
2215
+ selectorToNotTouch[selector] = true;
2216
+ }
2217
+ if (oldDeployment) {
2218
+ proxy = await getDeployment(proxyName);
2219
+ const diamondProxy = new contracts_1.Contract(proxy.address, proxy.abi, provider);
2220
+ const currentFacets = await diamondProxy.facets();
2221
+ for (const currentFacet of currentFacets) {
2222
+ oldFacets.push(currentFacet);
2223
+ if (findAll(['0xcdffacc6', '0x52ef6b2c', '0xadfca15e', '0x7a0ed627', '0x01ffc9a7'], currentFacet.functionSelectors) ||
2224
+ currentFacet.functionSelectors[0] === '0x1f931c1c' ||
2225
+ findAll(['0xf2fde38b', '0x8da5cb5b'], currentFacet.functionSelectors)) {
2226
+ facetSnapshot.push(currentFacet);
2227
+ newSelectors.push(...currentFacet.functionSelectors);
2228
+ }
2229
+ }
2230
+ }
2231
+ else {
2232
+ throw new Error(`old diamond deployments are now disabled`);
2233
+ }
2234
+ let changesDetected = !oldDeployment;
2235
+ let abi = old_diamondbase_json_1.default.abi.concat([]);
2236
+ const facetCuts = [];
2237
+ for (const facet of options.facets) {
2238
+ let facetName;
2239
+ let artifact;
2240
+ let linkedData = options.linkedData;
2241
+ let libraries = options.libraries;
2242
+ let facetArgs = options.facetsArgs;
2243
+ let argsSpecific = false;
2244
+ if (typeof facet === 'string') {
2245
+ artifact = await partialExtension.getExtendedArtifact(facet);
2246
+ facetName = facet;
2247
+ }
2248
+ else {
2249
+ if (facet.linkedData) {
2250
+ linkedData = facet.linkedData;
2251
+ }
2252
+ if (facet.libraries) {
2253
+ libraries = facet.libraries;
2254
+ }
2255
+ if (facet.args) {
2256
+ facetArgs = facet.args;
2257
+ argsSpecific = true;
2258
+ }
2259
+ if (facet.contract) {
2260
+ if (typeof facet.contract === 'string') {
2261
+ artifact = await partialExtension.getExtendedArtifact(facet.contract);
2262
+ }
2263
+ else {
2264
+ artifact = facet.contract;
2265
+ }
2266
+ }
2267
+ else {
2268
+ if (!facet.name) {
2269
+ throw new Error(`no name , not contract is specified for facet, cannot proceed`);
2270
+ }
2271
+ artifact = await partialExtension.getExtendedArtifact(facet.name);
2272
+ }
2273
+ facetName = facet.name;
2274
+ if (!facetName) {
2275
+ if (typeof facet.contract === 'string') {
2276
+ facetName = name + '_facet_' + facet.contract;
2277
+ }
2278
+ else {
2279
+ throw new Error(`facet has no name, please specify one`);
2280
+ }
2281
+ }
2282
+ }
2283
+ const constructor = artifact.abi.find((fragment) => fragment.type === 'constructor');
2284
+ if ((!argsSpecific && !constructor) || constructor.inputs.length === 0) {
2285
+ facetArgs = [];
2286
+ }
2287
+ abi = (0, utils_2.mergeABIs)([abi, artifact.abi], {
2288
+ check: true,
2289
+ skipSupportsInterface: false,
2290
+ });
2291
+ const implementation = await _deployOne(facetName, {
2292
+ contract: artifact,
2293
+ from: options.from,
2294
+ autoMine: options.autoMine,
2295
+ estimateGasExtra: options.estimateGasExtra,
2296
+ estimatedGasLimit: options.estimatedGasLimit,
2297
+ gasPrice: options.gasPrice,
2298
+ maxFeePerGas: options.maxFeePerGas,
2299
+ maxPriorityFeePerGas: options.maxPriorityFeePerGas,
2300
+ log: options.log,
2301
+ libraries,
2302
+ linkedData,
2303
+ args: facetArgs,
2304
+ });
2305
+ if (implementation.newlyDeployed) {
2306
+ const newFacet = {
2307
+ facetAddress: implementation.address,
2308
+ functionSelectors: sigsFromABI(implementation.abi),
2309
+ };
2310
+ facetSnapshot.push(newFacet);
2311
+ newSelectors.push(...newFacet.functionSelectors);
2312
+ }
2313
+ else {
2314
+ const oldImpl = await getDeployment(facetName);
2315
+ const newFacet = {
2316
+ facetAddress: oldImpl.address,
2317
+ functionSelectors: sigsFromABI(oldImpl.abi),
2318
+ };
2319
+ facetSnapshot.push(newFacet);
2320
+ newSelectors.push(...newFacet.functionSelectors);
2321
+ }
2322
+ }
2323
+ const oldSelectors = [];
2324
+ const oldSelectorsFacetAddress = {};
2325
+ for (const oldFacet of oldFacets) {
2326
+ for (const selector of oldFacet.functionSelectors) {
2327
+ oldSelectors.push(selector);
2328
+ oldSelectorsFacetAddress[selector] = oldFacet.facetAddress;
2329
+ }
2330
+ }
2331
+ for (const newFacet of facetSnapshot) {
2332
+ const selectorsToAdd = [];
2333
+ const selectorsToReplace = [];
2334
+ for (const selector of newFacet.functionSelectors) {
2335
+ if (oldSelectors.indexOf(selector) > 0) {
2336
+ if (oldSelectorsFacetAddress[selector].toLowerCase() !== newFacet.facetAddress.toLowerCase() &&
2337
+ !selectorToNotTouch[selector]) {
2338
+ selectorsToReplace.push(selector);
2339
+ }
2340
+ }
2341
+ else {
2342
+ if (!selectorToNotTouch[selector]) {
2343
+ selectorsToAdd.push(selector);
2344
+ }
2345
+ }
2346
+ }
2347
+ if (selectorsToReplace.length > 0) {
2348
+ changesDetected = true;
2349
+ facetCuts.push({
2350
+ facetAddress: newFacet.facetAddress,
2351
+ functionSelectors: selectorsToReplace,
2352
+ action: types_1.FacetCutAction.Replace,
2353
+ });
2354
+ }
2355
+ if (selectorsToAdd.length > 0) {
2356
+ changesDetected = true;
2357
+ facetCuts.push({
2358
+ facetAddress: newFacet.facetAddress,
2359
+ functionSelectors: selectorsToAdd,
2360
+ action: types_1.FacetCutAction.Add,
2361
+ });
2362
+ }
2363
+ }
2364
+ const selectorsToDelete = [];
2365
+ for (const selector of oldSelectors) {
2366
+ if (newSelectors.indexOf(selector) === -1) {
2367
+ selectorsToDelete.push(selector);
2368
+ }
2369
+ }
2370
+ if (selectorsToDelete.length > 0) {
2371
+ changesDetected = true;
2372
+ facetCuts.unshift({
2373
+ facetAddress: '0x0000000000000000000000000000000000000000',
2374
+ functionSelectors: selectorsToDelete,
2375
+ action: types_1.FacetCutAction.Remove,
2376
+ });
2377
+ }
2378
+ let data = '0x';
2379
+ if (options.execute) {
2380
+ const diamondContract = new contracts_1.Contract('0x0000000000000000000000000000000000000001', abi);
2381
+ const txData = await diamondContract.populateTransaction[options.execute.methodName](...options.execute.args);
2382
+ data = txData.data || '0x';
2383
+ }
2384
+ if (changesDetected) {
2385
+ if (!proxy) {
2386
+ throw new Error(`no proxy found: old diamond deployments are now disabled`);
2387
+ }
2388
+ else {
2389
+ const currentOwner = await read(proxyName, 'owner');
2390
+ if (currentOwner.toLowerCase() !== owner.toLowerCase()) {
2391
+ throw new Error('To change owner, you need to call `transferOwnership`');
2392
+ }
2393
+ if (currentOwner === constants_1.AddressZero) {
2394
+ throw new Error('The Diamond belongs to no-one. It cannot be upgraded anymore');
2395
+ }
2396
+ const executeReceipt = await execute(name, { ...options, from: currentOwner }, 'diamondCut', facetCuts, data === '0x' ? '0x0000000000000000000000000000000000000000' : proxy.address, data);
2397
+ if (!executeReceipt) {
2398
+ throw new Error('failed to execute');
2399
+ }
2400
+ const diamondDeployment = {
2401
+ ...oldDeployment,
2402
+ linkedData: options.linkedData,
2403
+ address: proxy.address,
2404
+ abi,
2405
+ facets: facetSnapshot,
2406
+ execute: options.execute,
2407
+ };
2408
+ if (oldDeployment.history) {
2409
+ diamondDeployment.history = diamondDeployment.history
2410
+ ? diamondDeployment.history.concat([oldDeployment])
2411
+ : [oldDeployment];
2412
+ }
2413
+ await saveDeployment(name, diamondDeployment);
2414
+ }
2415
+ const deployment = await partialExtension.get(name);
2416
+ return {
2417
+ ...deployment,
2418
+ newlyDeployed: true,
2419
+ };
2420
+ }
2421
+ else {
2422
+ const deployment = await partialExtension.get(name);
2423
+ return {
2424
+ ...deployment,
2425
+ newlyDeployed: false,
2426
+ };
2427
+ }
2428
+ }
2429
+ return { extension, utils };
2430
+ }
2431
+ exports.addHelpers = addHelpers;
2432
+ function pause(duration) {
2433
+ return new Promise((res) => setTimeout(res, duration * 1000));
2434
+ }
2435
+ async function waitForTx(ethereum, txHash, isContract) {
2436
+ let receipt;
2437
+ while (true) {
2438
+ try {
2439
+ receipt = await ethereum.send('eth_getTransactionReceipt', [txHash]);
2440
+ }
2441
+ catch (e) { }
2442
+ if (receipt && receipt.blockNumber) {
2443
+ if (isContract) {
2444
+ if (!receipt.contractAddress) {
2445
+ throw new Error('contract not deployed');
2446
+ }
2447
+ else {
2448
+ return receipt;
2449
+ }
2450
+ }
2451
+ else {
2452
+ return receipt;
2453
+ }
2454
+ }
2455
+ await pause(2);
2456
+ }
2457
+ }
2458
+ exports.waitForTx = waitForTx;
2459
+ function replaceTemplateArgs(proxyArgsTemplate, { implementationAddress, proxyAdmin, data, proxyAddress, }) {
2460
+ const proxyArgs = [];
2461
+ for (let i = 0; i < proxyArgsTemplate.length; i++) {
2462
+ const argValue = proxyArgsTemplate[i];
2463
+ if (argValue === '{implementation}') {
2464
+ proxyArgs.push(implementationAddress);
2465
+ }
2466
+ else if (argValue === '{admin}') {
2467
+ proxyArgs.push(proxyAdmin);
2468
+ }
2469
+ else if (argValue === '{data}') {
2470
+ proxyArgs.push(data);
2471
+ }
2472
+ else if (argValue === '{proxy}') {
2473
+ if (!proxyAddress) {
2474
+ throw new Error(`Expected proxy address but none was specified.`);
2475
+ }
2476
+ proxyArgs.push(proxyAddress);
2477
+ }
2478
+ else {
2479
+ proxyArgs.push(argValue);
2480
+ }
2481
+ }
2482
+ return proxyArgs;
2483
+ }
2484
+ //# sourceMappingURL=helper.js.map