@alephium/web3 0.2.0-rc.5 → 0.2.0-rc.8

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 (83) hide show
  1. package/.eslintignore +2 -2
  2. package/README.md +2 -135
  3. package/contracts/greeter/greeter.ral +1 -1
  4. package/dist/alephium-web3.min.js +1 -1
  5. package/dist/alephium-web3.min.js.LICENSE.txt +0 -17
  6. package/dist/alephium-web3.min.js.map +1 -1
  7. package/dist/scripts/create-project.js +1 -1
  8. package/dist/src/api/api-alephium.d.ts +19 -6
  9. package/dist/src/api/api-explorer.d.ts +16 -16
  10. package/dist/src/api/index.js +5 -1
  11. package/dist/src/contract/contract.d.ts +30 -8
  12. package/dist/src/contract/contract.js +105 -58
  13. package/dist/src/contract/index.js +5 -1
  14. package/dist/src/global.d.ts +3 -0
  15. package/{src/utils/djb2.test.ts → dist/src/global.js} +20 -17
  16. package/dist/src/index.d.ts +2 -0
  17. package/dist/src/index.js +20 -1
  18. package/dist/src/signer/index.d.ts +0 -1
  19. package/dist/src/signer/index.js +5 -2
  20. package/dist/src/signer/signer.d.ts +1 -1
  21. package/dist/src/signer/signer.js +8 -3
  22. package/dist/src/transaction/index.d.ts +0 -1
  23. package/dist/src/transaction/index.js +5 -2
  24. package/dist/src/utils/index.d.ts +0 -1
  25. package/dist/src/utils/index.js +5 -2
  26. package/dist/src/utils/subscription.d.ts +0 -1
  27. package/dist/src/utils/subscription.js +2 -1
  28. package/dist/src/utils/utils.d.ts +3 -2
  29. package/dist/src/utils/utils.js +16 -15
  30. package/jest-config.json +11 -0
  31. package/package.json +6 -32
  32. package/scripts/create-project.ts +1 -1
  33. package/src/api/api-alephium.ts +14 -0
  34. package/src/contract/contract.ts +161 -65
  35. package/src/{test/index.ts → global.ts} +14 -10
  36. package/src/index.ts +3 -0
  37. package/src/signer/index.ts +0 -1
  38. package/src/signer/signer.ts +3 -2
  39. package/src/transaction/index.ts +0 -1
  40. package/src/utils/index.ts +0 -1
  41. package/src/utils/subscription.ts +2 -2
  42. package/src/utils/utils.ts +7 -7
  43. package/templates/base/package.json +2 -2
  44. package/templates/base/src/greeter.ts +8 -7
  45. package/templates/react/package.json +2 -2
  46. package/templates/react/src/App.tsx +2 -2
  47. package/.eslintrc.json +0 -21
  48. package/LICENSE +0 -165
  49. package/contracts/add/add.ral +0 -15
  50. package/contracts/main.ral +0 -4
  51. package/contracts/sub/sub.ral +0 -10
  52. package/contracts/test/metadata.ral +0 -18
  53. package/contracts/test/warnings.ral +0 -8
  54. package/dist/src/signer/node-wallet.d.ts +0 -13
  55. package/dist/src/signer/node-wallet.js +0 -60
  56. package/dist/src/test/index.d.ts +0 -7
  57. package/dist/src/test/index.js +0 -41
  58. package/dist/src/test/privatekey-wallet.d.ts +0 -12
  59. package/dist/src/test/privatekey-wallet.js +0 -68
  60. package/dist/src/transaction/sign-verify.d.ts +0 -2
  61. package/dist/src/transaction/sign-verify.js +0 -58
  62. package/dist/src/utils/password-crypto.d.ts +0 -2
  63. package/dist/src/utils/password-crypto.js +0 -69
  64. package/gitignore +0 -9
  65. package/src/contract/ralph.test.ts +0 -178
  66. package/src/fixtures/address.json +0 -36
  67. package/src/fixtures/balance.json +0 -9
  68. package/src/fixtures/self-clique.json +0 -19
  69. package/src/fixtures/transaction.json +0 -13
  70. package/src/fixtures/transactions.json +0 -179
  71. package/src/signer/fixtures/genesis.json +0 -26
  72. package/src/signer/fixtures/wallets.json +0 -26
  73. package/src/signer/node-wallet.ts +0 -74
  74. package/src/test/privatekey-wallet.ts +0 -58
  75. package/src/transaction/sign-verify.test.ts +0 -50
  76. package/src/transaction/sign-verify.ts +0 -39
  77. package/src/utils/address.test.ts +0 -47
  78. package/src/utils/password-crypto.test.ts +0 -27
  79. package/src/utils/password-crypto.ts +0 -77
  80. package/src/utils/utils.test.ts +0 -161
  81. package/test/contract.test.ts +0 -213
  82. package/test/events.test.ts +0 -143
  83. package/test/transaction.test.ts +0 -74
@@ -73,7 +73,7 @@ function prepareShared(packageRoot, projectRoot) {
73
73
  console.log(` to ${projectRoot}`);
74
74
  console.log('...');
75
75
  fs_extra_1.default.copySync(path_1.default.join(packageRoot, 'templates/shared'), projectRoot);
76
- copy('', ['.editorconfig', '.eslintignore', '.gitattributes', 'LICENSE']);
76
+ copy('', ['.editorconfig', '.eslintignore', '.gitattributes']);
77
77
  copy('dev', ['user.conf']);
78
78
  copy('scripts', ['start-devnet.js', 'stop-devnet.js']);
79
79
  if (fs_extra_1.default.existsSync(path_1.default.join(packageRoot, 'gitignore'))) {
@@ -305,6 +305,7 @@ export interface ChangeActiveAddress {
305
305
  address: string;
306
306
  }
307
307
  export interface CompileContractResult {
308
+ name: string;
308
309
  bytecode: string;
309
310
  /** @format 32-byte-hash */
310
311
  codeHash: string;
@@ -318,11 +319,20 @@ export interface CompileProjectResult {
318
319
  scripts: CompileScriptResult[];
319
320
  }
320
321
  export interface CompileScriptResult {
322
+ name: string;
321
323
  bytecodeTemplate: string;
322
324
  fields: FieldsSig;
323
325
  functions: FunctionSig[];
324
326
  warnings: string[];
325
327
  }
328
+ export interface CompilerOptions {
329
+ ignoreUnusedConstantsWarnings?: boolean;
330
+ ignoreUnusedVariablesWarnings?: boolean;
331
+ ignoreUnusedFieldsWarnings?: boolean;
332
+ ignoreUnusedPrivateFunctionsWarnings?: boolean;
333
+ ignoreReadonlyCheckWarnings?: boolean;
334
+ ignoreExternalCallCheckWarnings?: boolean;
335
+ }
326
336
  export interface Confirmed {
327
337
  /** @format block-hash */
328
338
  blockHash: string;
@@ -338,6 +348,7 @@ export interface Confirmed {
338
348
  }
339
349
  export interface Contract {
340
350
  code: string;
351
+ compilerOptions?: CompilerOptions;
341
352
  }
342
353
  export interface ContractEvent {
343
354
  /** @format block-hash */
@@ -532,6 +543,7 @@ export interface Penalty {
532
543
  }
533
544
  export interface Project {
534
545
  code: string;
546
+ compilerOptions?: CompilerOptions;
535
547
  }
536
548
  export interface Reachable {
537
549
  peers: string[];
@@ -553,6 +565,7 @@ export interface RevealMnemonicResult {
553
565
  }
554
566
  export interface Script {
555
567
  code: string;
568
+ compilerOptions?: CompilerOptions;
556
569
  }
557
570
  export interface SelfClique {
558
571
  /** @format clique-id */
@@ -1024,8 +1037,8 @@ export declare class Api<SecurityDataType extends unknown> extends HttpClient<Se
1024
1037
  * @request POST:/wallets/{wallet_name}/derive-next-address
1025
1038
  */
1026
1039
  postWalletsWalletNameDeriveNextAddress: (walletName: string, query?: {
1027
- group?: number | undefined;
1028
- } | undefined, params?: RequestParams) => Promise<AddressInfo>;
1040
+ group?: number;
1041
+ }, params?: RequestParams) => Promise<AddressInfo>;
1029
1042
  /**
1030
1043
  * @description Your wallet need to have been created with the miner flag set to true
1031
1044
  *
@@ -1157,8 +1170,8 @@ export declare class Api<SecurityDataType extends unknown> extends HttpClient<Se
1157
1170
  * @request GET:/infos/current-hashrate
1158
1171
  */
1159
1172
  getInfosCurrentHashrate: (query?: {
1160
- timespan?: number | undefined;
1161
- } | undefined, params?: RequestParams) => Promise<string>;
1173
+ timespan?: number;
1174
+ }, params?: RequestParams) => Promise<string>;
1162
1175
  };
1163
1176
  blockflow: {
1164
1177
  /**
@@ -1505,8 +1518,8 @@ export declare class Api<SecurityDataType extends unknown> extends HttpClient<Se
1505
1518
  * @request GET:/events/tx-id/{txId}
1506
1519
  */
1507
1520
  getEventsTxIdTxid: (txId: string, query?: {
1508
- group?: number | undefined;
1509
- } | undefined, params?: RequestParams) => Promise<ContractEventsByTxId>;
1521
+ group?: number;
1522
+ }, params?: RequestParams) => Promise<ContractEventsByTxId>;
1510
1523
  };
1511
1524
  }
1512
1525
  export {};
@@ -269,10 +269,10 @@ export declare class Api<SecurityDataType extends unknown> extends HttpClient<Se
269
269
  * @request GET:/blocks
270
270
  */
271
271
  getBlocks: (query?: {
272
- page?: number | undefined;
273
- limit?: number | undefined;
274
- reverse?: boolean | undefined;
275
- } | undefined, params?: RequestParams) => Promise<ListBlocks>;
272
+ page?: number;
273
+ limit?: number;
274
+ reverse?: boolean;
275
+ }, params?: RequestParams) => Promise<ListBlocks>;
276
276
  /**
277
277
  * @description Get a block with hash
278
278
  *
@@ -289,10 +289,10 @@ export declare class Api<SecurityDataType extends unknown> extends HttpClient<Se
289
289
  * @request GET:/blocks/{block-hash}/transactions
290
290
  */
291
291
  getBlocksBlockHashTransactions: (blockHash: string, query?: {
292
- page?: number | undefined;
293
- limit?: number | undefined;
294
- reverse?: boolean | undefined;
295
- } | undefined, params?: RequestParams) => Promise<Transaction[]>;
292
+ page?: number;
293
+ limit?: number;
294
+ reverse?: boolean;
295
+ }, params?: RequestParams) => Promise<Transaction[]>;
296
296
  };
297
297
  transactions: {
298
298
  /**
@@ -321,10 +321,10 @@ export declare class Api<SecurityDataType extends unknown> extends HttpClient<Se
321
321
  * @request GET:/addresses/{address}/transactions
322
322
  */
323
323
  getAddressesAddressTransactions: (address: string, query?: {
324
- page?: number | undefined;
325
- limit?: number | undefined;
326
- reverse?: boolean | undefined;
327
- } | undefined, params?: RequestParams) => Promise<Transaction[]>;
324
+ page?: number;
325
+ limit?: number;
326
+ reverse?: boolean;
327
+ }, params?: RequestParams) => Promise<Transaction[]>;
328
328
  /**
329
329
  * @description Get total transactions of a given address
330
330
  *
@@ -367,10 +367,10 @@ export declare class Api<SecurityDataType extends unknown> extends HttpClient<Se
367
367
  * @request GET:/infos/supply
368
368
  */
369
369
  getInfosSupply: (query?: {
370
- page?: number | undefined;
371
- limit?: number | undefined;
372
- reverse?: boolean | undefined;
373
- } | undefined, params?: RequestParams) => Promise<TokenSupply[]>;
370
+ page?: number;
371
+ limit?: number;
372
+ reverse?: boolean;
373
+ }, params?: RequestParams) => Promise<TokenSupply[]>;
374
374
  /**
375
375
  * @description Get the ALPH total supply
376
376
  *
@@ -18,7 +18,11 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.
18
18
  */
19
19
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
20
20
  if (k2 === undefined) k2 = k;
21
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
21
+ var desc = Object.getOwnPropertyDescriptor(m, k);
22
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
23
+ desc = { enumerable: true, get: function() { return m[k]; } };
24
+ }
25
+ Object.defineProperty(o, k2, desc);
22
26
  }) : (function(o, m, k, k2) {
23
27
  if (k2 === undefined) k2 = k;
24
28
  o[k2] = m[k];
@@ -1,5 +1,4 @@
1
- import { NodeProvider } from '../api';
2
- import { node } from '../api';
1
+ import { node, NodeProvider } from '../api';
3
2
  import { SignDeployContractTxParams, SignExecuteScriptTxParams, SignerWithNodeProvider } from '../signer';
4
3
  import { CompileContractResult, CompileScriptResult } from '../api/api-alephium';
5
4
  declare type FieldsSig = node.FieldsSig;
@@ -11,6 +10,11 @@ declare enum SourceType {
11
10
  AbstractContract = 2,
12
11
  Interface = 3
13
12
  }
13
+ export declare type CompilerOptions = node.CompilerOptions & {
14
+ errorOnWarnings: boolean;
15
+ };
16
+ export declare const DEFAULT_NODE_COMPILER_OPTIONS: node.CompilerOptions;
17
+ export declare const DEFAULT_COMPILER_OPTIONS: CompilerOptions;
14
18
  declare class TypedMatcher<T extends SourceType> {
15
19
  matcher: RegExp;
16
20
  type: T;
@@ -23,7 +27,8 @@ declare class SourceFile {
23
27
  sourceCode: string;
24
28
  sourceCodeHash: string;
25
29
  getArtifactPath(artifactsRootPath: string): string;
26
- constructor(type: SourceType, sourceCode: string, contractPath: string);
30
+ constructor(type: SourceType, sourceCode: string, sourceCodeHash: string, contractPath: string);
31
+ static from(type: SourceType, sourceCode: string, contractPath: string): Promise<SourceFile>;
27
32
  }
28
33
  declare class Compiled<T extends Artifact> {
29
34
  sourceFile: SourceFile;
@@ -31,10 +36,27 @@ declare class Compiled<T extends Artifact> {
31
36
  warnings: string[];
32
37
  constructor(sourceFile: SourceFile, artifact: T, warnings: string[]);
33
38
  }
39
+ declare class ProjectArtifact {
40
+ static readonly artifactFileName = ".project.json";
41
+ compilerOptionsUsed: node.CompilerOptions;
42
+ infos: Map<string, {
43
+ sourceCodeHash: string;
44
+ warnings: string[];
45
+ }>;
46
+ static checkCompilerOptionsParameter(compilerOptions: node.CompilerOptions): void;
47
+ constructor(compilerOptionsUsed: node.CompilerOptions, infos: Map<string, {
48
+ sourceCodeHash: string;
49
+ warnings: string[];
50
+ }>);
51
+ saveToFile(rootPath: string): Promise<void>;
52
+ needToReCompile(compilerOptions: node.CompilerOptions, files: SourceFile[]): boolean;
53
+ static from(rootPath: string): Promise<ProjectArtifact | undefined>;
54
+ }
34
55
  export declare class Project {
35
56
  sourceFiles: SourceFile[];
36
57
  contracts: Compiled<Contract>[];
37
58
  scripts: Compiled<Script>[];
59
+ projectArtifact: ProjectArtifact;
38
60
  readonly contractsRootPath: string;
39
61
  readonly artifactsRootPath: string;
40
62
  readonly nodeProvider: NodeProvider;
@@ -44,19 +66,19 @@ export declare class Project {
44
66
  static readonly interfaceMatcher: TypedMatcher<SourceType.Interface>;
45
67
  static readonly scriptMatcher: TypedMatcher<SourceType.Script>;
46
68
  static readonly matchers: TypedMatcher<SourceType>[];
69
+ static buildProjectArtifact(sourceFiles: SourceFile[], contracts: Compiled<Contract>[], scripts: Compiled<Script>[], compilerOptions: node.CompilerOptions): ProjectArtifact;
47
70
  private constructor();
48
71
  private getContractPath;
49
- private static checkCompilerWarnings;
50
- static contract(path: string, errorOnWarnings?: boolean, ignoreUnusedConstantsWarnings?: boolean): Contract;
51
- static script(path: string, errorOnWarnings?: boolean, ignoreUnusedConstantsWarnings?: boolean): Script;
72
+ static checkCompilerWarnings(warnings: string[], errorOnWarnings: boolean): void;
73
+ static contract(path: string): Contract;
74
+ static script(path: string): Script;
52
75
  private saveArtifactsToFile;
53
76
  contractByCodeHash(codeHash: string): Contract;
54
- private saveProjectArtifactToFile;
55
77
  private static compile;
56
78
  private static loadArtifacts;
57
79
  private static loadSourceFile;
58
80
  private static loadSourceFiles;
59
- static build(provider: NodeProvider, contractsRootPath?: string, artifactsRootPath?: string): Promise<void>;
81
+ static build(compilerOptionsPartial?: Partial<CompilerOptions>, contractsRootPath?: string, artifactsRootPath?: string): Promise<void>;
60
82
  }
61
83
  export declare abstract class Artifact {
62
84
  readonly functions: FunctionSig[];
@@ -18,7 +18,11 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.
18
18
  */
19
19
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
20
20
  if (k2 === undefined) k2 = k;
21
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
21
+ var desc = Object.getOwnPropertyDescriptor(m, k);
22
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
23
+ desc = { enumerable: true, get: function() { return m[k]; } };
24
+ }
25
+ Object.defineProperty(o, k2, desc);
22
26
  }) : (function(o, m, k, k2) {
23
27
  if (k2 === undefined) k2 = k;
24
28
  o[k2] = m[k];
@@ -39,14 +43,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
39
43
  return (mod && mod.__esModule) ? mod : { "default": mod };
40
44
  };
41
45
  Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.toApiVal = exports.extractArray = exports.Script = exports.Contract = exports.Artifact = exports.Project = void 0;
46
+ exports.toApiVal = exports.extractArray = exports.Script = exports.Contract = exports.Artifact = exports.Project = exports.DEFAULT_COMPILER_OPTIONS = exports.DEFAULT_NODE_COMPILER_OPTIONS = void 0;
43
47
  const buffer_1 = require("buffer/");
44
- const cryptojs = __importStar(require("crypto-js"));
45
- const crypto = __importStar(require("crypto"));
48
+ const crypto_1 = require("crypto");
46
49
  const fs_1 = __importDefault(require("fs"));
47
50
  const fs_2 = require("fs");
48
51
  const ralph = __importStar(require("./ralph"));
49
52
  const utils_1 = require("../utils");
53
+ const global_1 = require("../global");
50
54
  var SourceType;
51
55
  (function (SourceType) {
52
56
  SourceType[SourceType["Contract"] = 0] = "Contract";
@@ -54,6 +58,15 @@ var SourceType;
54
58
  SourceType[SourceType["AbstractContract"] = 2] = "AbstractContract";
55
59
  SourceType[SourceType["Interface"] = 3] = "Interface";
56
60
  })(SourceType || (SourceType = {}));
61
+ exports.DEFAULT_NODE_COMPILER_OPTIONS = {
62
+ ignoreUnusedConstantsWarnings: false,
63
+ ignoreUnusedVariablesWarnings: false,
64
+ ignoreUnusedFieldsWarnings: false,
65
+ ignoreUnusedPrivateFunctionsWarnings: false,
66
+ ignoreReadonlyCheckWarnings: false,
67
+ ignoreExternalCallCheckWarnings: false
68
+ };
69
+ exports.DEFAULT_COMPILER_OPTIONS = { errorOnWarnings: true, ...exports.DEFAULT_NODE_COMPILER_OPTIONS };
57
70
  class TypedMatcher {
58
71
  constructor(pattern, type) {
59
72
  this.matcher = new RegExp(pattern, 'mg');
@@ -65,15 +78,19 @@ class TypedMatcher {
65
78
  }
66
79
  }
67
80
  class SourceFile {
68
- constructor(type, sourceCode, contractPath) {
81
+ constructor(type, sourceCode, sourceCodeHash, contractPath) {
69
82
  this.type = type;
70
83
  this.sourceCode = sourceCode;
71
- this.sourceCodeHash = cryptojs.SHA256(sourceCode).toString();
84
+ this.sourceCodeHash = sourceCodeHash;
72
85
  this.contractPath = contractPath;
73
86
  }
74
87
  getArtifactPath(artifactsRootPath) {
75
88
  return artifactsRootPath + this.contractPath.slice(this.contractPath.indexOf('/')) + '.json';
76
89
  }
90
+ static async from(type, sourceCode, contractPath) {
91
+ const sourceCodeHash = await crypto_1.webcrypto.subtle.digest('SHA-256', buffer_1.Buffer.from(sourceCode));
92
+ return new SourceFile(type, sourceCode, buffer_1.Buffer.from(sourceCodeHash).toString('hex'), contractPath);
93
+ }
77
94
  }
78
95
  class Compiled {
79
96
  constructor(sourceFile, artifact, warnings) {
@@ -83,15 +100,35 @@ class Compiled {
83
100
  }
84
101
  }
85
102
  class ProjectArtifact {
86
- constructor(infos) {
103
+ constructor(compilerOptionsUsed, infos) {
104
+ ProjectArtifact.checkCompilerOptionsParameter(compilerOptionsUsed);
105
+ this.compilerOptionsUsed = compilerOptionsUsed;
87
106
  this.infos = infos;
88
107
  }
108
+ static checkCompilerOptionsParameter(compilerOptions) {
109
+ if (Object.keys(compilerOptions).length != Object.keys(exports.DEFAULT_NODE_COMPILER_OPTIONS).length) {
110
+ throw Error(`Not all compiler options are set: ${compilerOptions}`);
111
+ }
112
+ const combined = { ...compilerOptions, ...exports.DEFAULT_NODE_COMPILER_OPTIONS };
113
+ if (Object.keys(combined).length !== Object.keys(exports.DEFAULT_NODE_COMPILER_OPTIONS).length) {
114
+ throw Error(`There are unknown compiler options: ${compilerOptions}`);
115
+ }
116
+ }
89
117
  async saveToFile(rootPath) {
90
118
  const filepath = rootPath + '/' + ProjectArtifact.artifactFileName;
91
- const content = JSON.stringify(Object.fromEntries(this.infos), null, 2);
119
+ const artifact = { compilerOptionsUsed: this.compilerOptionsUsed, infos: Object.fromEntries(this.infos) };
120
+ const content = JSON.stringify(artifact, null, 2);
92
121
  return fs_2.promises.writeFile(filepath, content);
93
122
  }
94
- sourceHasChanged(files) {
123
+ needToReCompile(compilerOptions, files) {
124
+ ProjectArtifact.checkCompilerOptionsParameter(compilerOptions);
125
+ const optionsMatched = Object.entries(compilerOptions).every(([key, inputOption]) => {
126
+ const usedOption = this.compilerOptionsUsed[`${key}`];
127
+ return usedOption === inputOption;
128
+ });
129
+ if (!optionsMatched) {
130
+ return true;
131
+ }
95
132
  if (files.length !== this.infos.size) {
96
133
  return true;
97
134
  }
@@ -109,19 +146,48 @@ class ProjectArtifact {
109
146
  return undefined;
110
147
  }
111
148
  const content = await fs_2.promises.readFile(filepath);
112
- const files = new Map(Object.entries(JSON.parse(content.toString())));
113
- return new ProjectArtifact(files);
149
+ const json = JSON.parse(content.toString());
150
+ const compilerOptionsUsed = json.compilerOptionsUsed;
151
+ const files = new Map(Object.entries(json.infos));
152
+ return new ProjectArtifact(compilerOptionsUsed, files);
114
153
  }
115
154
  }
116
155
  ProjectArtifact.artifactFileName = '.project.json';
117
156
  class Project {
118
- constructor(provider, contractsRootPath, artifactsRootPath, sourceFiles, contracts, scripts) {
157
+ constructor(provider, contractsRootPath, artifactsRootPath, sourceFiles, contracts, scripts, errorOnWarnings, projectArtifact) {
119
158
  this.nodeProvider = provider;
120
159
  this.contractsRootPath = contractsRootPath;
121
160
  this.artifactsRootPath = artifactsRootPath;
122
161
  this.sourceFiles = sourceFiles;
123
162
  this.contracts = contracts;
124
163
  this.scripts = scripts;
164
+ this.projectArtifact = projectArtifact;
165
+ if (errorOnWarnings) {
166
+ Project.checkCompilerWarnings([...contracts.map((c) => c.warnings).flat(), ...scripts.map((s) => s.warnings).flat()], errorOnWarnings);
167
+ }
168
+ }
169
+ static buildProjectArtifact(sourceFiles, contracts, scripts, compilerOptions) {
170
+ const files = new Map();
171
+ contracts.forEach((c) => {
172
+ files.set(c.sourceFile.contractPath, {
173
+ sourceCodeHash: c.sourceFile.sourceCodeHash,
174
+ warnings: c.warnings
175
+ });
176
+ });
177
+ scripts.forEach((s) => {
178
+ files.set(s.sourceFile.contractPath, {
179
+ sourceCodeHash: s.sourceFile.sourceCodeHash,
180
+ warnings: s.warnings
181
+ });
182
+ });
183
+ const compiledSize = contracts.length + scripts.length;
184
+ sourceFiles.slice(compiledSize).forEach((c) => {
185
+ files.set(c.contractPath, {
186
+ sourceCodeHash: c.sourceCodeHash,
187
+ warnings: []
188
+ });
189
+ });
190
+ return new ProjectArtifact(compilerOptions, files);
125
191
  }
126
192
  getContractPath(path) {
127
193
  return path.startsWith(`./${this.contractsRootPath}`)
@@ -130,12 +196,11 @@ class Project {
130
196
  ? path
131
197
  : this.contractsRootPath + '/' + path;
132
198
  }
133
- static checkCompilerWarnings(warnings, errorOnWarnings, ignoreUnusedConstantsWarnings) {
134
- const remains = ignoreUnusedConstantsWarnings ? warnings.filter((s) => !s.includes('unused constants')) : warnings;
135
- if (remains.length !== 0) {
199
+ static checkCompilerWarnings(warnings, errorOnWarnings) {
200
+ if (warnings.length !== 0) {
136
201
  const prefixPerWarning = ' - ';
137
- const warningString = prefixPerWarning + remains.join('\n' + prefixPerWarning);
138
- const output = 'Compilation warnings:\n' + warningString + '\n';
202
+ const warningString = prefixPerWarning + warnings.join('\n' + prefixPerWarning);
203
+ const output = `Compilation warnings:\n` + warningString + '\n';
139
204
  if (errorOnWarnings) {
140
205
  throw new Error(output);
141
206
  }
@@ -144,22 +209,20 @@ class Project {
144
209
  }
145
210
  }
146
211
  }
147
- static contract(path, errorOnWarnings = true, ignoreUnusedConstantsWarnings = true) {
212
+ static contract(path) {
148
213
  const contractPath = Project.currentProject.getContractPath(path);
149
214
  const contract = Project.currentProject.contracts.find((c) => c.sourceFile.contractPath === contractPath);
150
215
  if (typeof contract === 'undefined') {
151
216
  throw new Error(`Contract ${contractPath} does not exist`);
152
217
  }
153
- Project.checkCompilerWarnings(contract.warnings, errorOnWarnings, ignoreUnusedConstantsWarnings);
154
218
  return contract.artifact;
155
219
  }
156
- static script(path, errorOnWarnings = true, ignoreUnusedConstantsWarnings = true) {
220
+ static script(path) {
157
221
  const contractPath = Project.currentProject.getContractPath(path);
158
222
  const script = Project.currentProject.scripts.find((c) => c.sourceFile.contractPath === contractPath);
159
223
  if (typeof script === 'undefined') {
160
224
  throw new Error(`Script ${contractPath} does not exist`);
161
225
  }
162
- Project.checkCompilerWarnings(script.warnings, errorOnWarnings, ignoreUnusedConstantsWarnings);
163
226
  return script.artifact;
164
227
  }
165
228
  async saveArtifactsToFile() {
@@ -178,6 +241,7 @@ class Project {
178
241
  for (const script of this.scripts) {
179
242
  await saveToFile(script);
180
243
  }
244
+ await this.projectArtifact.saveToFile(this.artifactsRootPath);
181
245
  }
182
246
  contractByCodeHash(codeHash) {
183
247
  const contract = this.contracts.find((c) => c.artifact.codeHash === codeHash);
@@ -186,34 +250,11 @@ class Project {
186
250
  }
187
251
  return contract.artifact;
188
252
  }
189
- async saveProjectArtifactToFile() {
190
- const files = new Map();
191
- this.contracts.forEach((c) => {
192
- files.set(c.sourceFile.contractPath, {
193
- sourceCodeHash: c.sourceFile.sourceCodeHash,
194
- warnings: c.warnings
195
- });
196
- });
197
- this.scripts.forEach((s) => {
198
- files.set(s.sourceFile.contractPath, {
199
- sourceCodeHash: s.sourceFile.sourceCodeHash,
200
- warnings: s.warnings
201
- });
202
- });
203
- const compiledSize = this.contracts.length + this.scripts.length;
204
- this.sourceFiles.slice(compiledSize).forEach((c) => {
205
- files.set(c.contractPath, {
206
- sourceCodeHash: c.sourceCodeHash,
207
- warnings: []
208
- });
209
- });
210
- const projectArtifact = new ProjectArtifact(files);
211
- await projectArtifact.saveToFile(this.artifactsRootPath);
212
- }
213
- static async compile(provider, files, contractsRootPath, artifactsRootPath) {
253
+ static async compile(provider, files, contractsRootPath, artifactsRootPath, errorOnWarnings, compilerOptions) {
214
254
  const sourceStr = files.map((f) => f.sourceCode).join('\n');
215
255
  const result = await provider.contracts.postContractsCompileProject({
216
- code: sourceStr
256
+ code: sourceStr,
257
+ compilerOptions: compilerOptions
217
258
  });
218
259
  const contracts = [];
219
260
  const scripts = [];
@@ -227,12 +268,12 @@ class Project {
227
268
  const script = Script.fromCompileResult(scriptResult);
228
269
  scripts.push(new Compiled(sourceFile, script, scriptResult.warnings));
229
270
  });
230
- const project = new Project(provider, contractsRootPath, artifactsRootPath, files, contracts, scripts);
271
+ const projectArtifact = Project.buildProjectArtifact(files, contracts, scripts, compilerOptions);
272
+ const project = new Project(provider, contractsRootPath, artifactsRootPath, files, contracts, scripts, errorOnWarnings, projectArtifact);
231
273
  await project.saveArtifactsToFile();
232
- await project.saveProjectArtifactToFile();
233
274
  return project;
234
275
  }
235
- static async loadArtifacts(provider, files, projectArtifact, contractsRootPath, artifactsRootPath) {
276
+ static async loadArtifacts(provider, files, projectArtifact, contractsRootPath, artifactsRootPath, errorOnWarnings, compilerOptions) {
236
277
  try {
237
278
  const contracts = [];
238
279
  const scripts = [];
@@ -252,11 +293,11 @@ class Project {
252
293
  scripts.push(new Compiled(file, artifact, warnings));
253
294
  }
254
295
  }
255
- return new Project(provider, contractsRootPath, artifactsRootPath, files, contracts, scripts);
296
+ return new Project(provider, contractsRootPath, artifactsRootPath, files, contracts, scripts, errorOnWarnings, projectArtifact);
256
297
  }
257
298
  catch (error) {
258
299
  console.log(`Failed to load artifacts, error: ${error}, try to re-compile contracts...`);
259
- return Project.compile(provider, files, contractsRootPath, artifactsRootPath);
300
+ return Project.compile(provider, files, contractsRootPath, artifactsRootPath, errorOnWarnings, compilerOptions);
260
301
  }
261
302
  }
262
303
  static async loadSourceFile(dirPath, filename) {
@@ -276,7 +317,7 @@ class Project {
276
317
  }
277
318
  const matcherIndex = results.indexOf(1);
278
319
  const type = this.matchers[`${matcherIndex}`].type;
279
- return new SourceFile(type, sourceStr, contractPath);
320
+ return SourceFile.from(type, sourceStr, contractPath);
280
321
  }
281
322
  static async loadSourceFiles(contractsRootPath) {
282
323
  const loadDir = async function (dirPath, results) {
@@ -300,14 +341,18 @@ class Project {
300
341
  }
301
342
  return sourceFiles.sort((a, b) => a.type - b.type);
302
343
  }
303
- static async build(provider, contractsRootPath = 'contracts', artifactsRootPath = 'artifacts') {
344
+ static async build(compilerOptionsPartial = {}, contractsRootPath = 'contracts', artifactsRootPath = 'artifacts') {
345
+ const provider = (0, global_1.getCurrentNodeProvider)();
304
346
  const sourceFiles = await Project.loadSourceFiles(contractsRootPath);
347
+ const { errorOnWarnings, ...nodeCompilerOptions } = { ...exports.DEFAULT_COMPILER_OPTIONS, ...compilerOptionsPartial };
305
348
  const projectArtifact = await ProjectArtifact.from(artifactsRootPath);
306
- if (typeof projectArtifact === 'undefined' || projectArtifact.sourceHasChanged(sourceFiles)) {
307
- Project.currentProject = await Project.compile(provider, sourceFiles, contractsRootPath, artifactsRootPath);
349
+ if (typeof projectArtifact === 'undefined' || projectArtifact.needToReCompile(nodeCompilerOptions, sourceFiles)) {
350
+ console.log(`Compile contracts in folder "${contractsRootPath}"`);
351
+ Project.currentProject = await Project.compile(provider, sourceFiles, contractsRootPath, artifactsRootPath, errorOnWarnings, nodeCompilerOptions);
308
352
  }
309
353
  else {
310
- Project.currentProject = await Project.loadArtifacts(provider, sourceFiles, projectArtifact, contractsRootPath, artifactsRootPath);
354
+ console.log(`Load compiled contracts from folder "${artifactsRootPath}"`);
355
+ Project.currentProject = await Project.loadArtifacts(provider, sourceFiles, projectArtifact, contractsRootPath, artifactsRootPath, errorOnWarnings, nodeCompilerOptions);
311
356
  }
312
357
  }
313
358
  }
@@ -394,8 +439,10 @@ class Contract extends Artifact {
394
439
  asset: asset
395
440
  };
396
441
  }
442
+ // no need to be cryptographically strong random
397
443
  static randomAddress() {
398
- const bytes = crypto.randomBytes(33);
444
+ const bytes = new Uint8Array(33);
445
+ crypto_1.webcrypto.getRandomValues(bytes);
399
446
  bytes[0] = 3;
400
447
  return utils_1.bs58.encode(bytes);
401
448
  }
@@ -18,7 +18,11 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.
18
18
  */
19
19
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
20
20
  if (k2 === undefined) k2 = k;
21
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
21
+ var desc = Object.getOwnPropertyDescriptor(m, k);
22
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
23
+ desc = { enumerable: true, get: function() { return m[k]; } };
24
+ }
25
+ Object.defineProperty(o, k2, desc);
22
26
  }) : (function(o, m, k, k2) {
23
27
  if (k2 === undefined) k2 = k;
24
28
  o[k2] = m[k];
@@ -0,0 +1,3 @@
1
+ import { NodeProvider } from './api';
2
+ export declare function setCurrentNodeProvider(provider: NodeProvider | string): void;
3
+ export declare function getCurrentNodeProvider(): NodeProvider;
@@ -1,3 +1,4 @@
1
+ "use strict";
1
2
  /*
2
3
  Copyright 2018 - 2022 The Alephium Authors
3
4
  This file is part of the alephium project.
@@ -15,21 +16,23 @@ GNU Lesser General Public License for more details.
15
16
  You should have received a copy of the GNU Lesser General Public License
16
17
  along with the library. If not, see <http://www.gnu.org/licenses/>.
17
18
  */
18
-
19
- import { Buffer } from 'buffer/'
20
- import djb2 from './djb2'
21
-
22
- describe('djb2', function () {
23
- it('djb2', async () => {
24
- function check(str: string, expected: number) {
25
- const bytes = Buffer.from(str, 'utf8')
26
- expect(djb2(bytes)).toEqual(expected)
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.getCurrentNodeProvider = exports.setCurrentNodeProvider = void 0;
21
+ const api_1 = require("./api");
22
+ let _currentNodeProvider = undefined;
23
+ function setCurrentNodeProvider(provider) {
24
+ if (typeof provider == 'string') {
25
+ _currentNodeProvider = new api_1.NodeProvider(provider);
27
26
  }
28
-
29
- check('', 5381)
30
- check('a', 177670)
31
- check('z', 177695)
32
- check('foo', 193491849)
33
- check('bar', 193487034)
34
- })
35
- })
27
+ else {
28
+ _currentNodeProvider = provider;
29
+ }
30
+ }
31
+ exports.setCurrentNodeProvider = setCurrentNodeProvider;
32
+ function getCurrentNodeProvider() {
33
+ if (typeof _currentNodeProvider === 'undefined') {
34
+ throw Error('No node provider is set.');
35
+ }
36
+ return _currentNodeProvider;
37
+ }
38
+ exports.getCurrentNodeProvider = getCurrentNodeProvider;
@@ -4,3 +4,5 @@ export * from './signer';
4
4
  export * from './utils';
5
5
  export * from './transaction';
6
6
  export * from './constants';
7
+ export * from './global';
8
+ export * as utils from './utils';