@alephium/web3 0.2.0-rc.12 → 0.2.0-rc.13

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 (35) hide show
  1. package/dist/alephium-web3.min.js +1 -1
  2. package/dist/alephium-web3.min.js.map +1 -1
  3. package/dist/src/api/api-alephium.d.ts +72 -11
  4. package/dist/src/api/api-alephium.js +64 -5
  5. package/dist/src/contract/contract.d.ts +6 -4
  6. package/dist/src/contract/contract.js +32 -30
  7. package/package.json +4 -13
  8. package/src/api/api-alephium.ts +112 -14
  9. package/src/contract/contract.ts +43 -40
  10. package/src/utils/utils.ts +0 -2
  11. package/contracts/greeter/greeter.ral +0 -7
  12. package/contracts/greeter/greeter_interface.ral +0 -4
  13. package/contracts/greeter_main.ral +0 -7
  14. package/dev/user.conf +0 -29
  15. package/dist/scripts/create-project.d.ts +0 -2
  16. package/dist/scripts/create-project.js +0 -125
  17. package/dist/scripts/start-devnet.d.ts +0 -1
  18. package/dist/scripts/start-devnet.js +0 -131
  19. package/dist/scripts/stop-devnet.d.ts +0 -1
  20. package/dist/scripts/stop-devnet.js +0 -32
  21. package/scripts/create-project.ts +0 -137
  22. package/scripts/start-devnet.js +0 -141
  23. package/scripts/stop-devnet.js +0 -32
  24. package/templates/base/README.md +0 -34
  25. package/templates/base/package.json +0 -35
  26. package/templates/base/src/greeter.ts +0 -42
  27. package/templates/base/tsconfig.json +0 -19
  28. package/templates/react/README.md +0 -34
  29. package/templates/react/config-overrides.js +0 -18
  30. package/templates/react/package.json +0 -66
  31. package/templates/react/src/App.tsx +0 -42
  32. package/templates/react/src/artifacts/greeter.ral.json +0 -26
  33. package/templates/react/src/artifacts/greeter_main.ral.json +0 -22
  34. package/templates/shared/.eslintrc.json +0 -12
  35. package/templates/shared/scripts/header.js +0 -0
@@ -124,6 +124,11 @@ export interface Banned {
124
124
  type: string
125
125
  }
126
126
 
127
+ export interface BlockAndEvents {
128
+ block: BlockEntry
129
+ events: ContractEventByBlockHash[]
130
+ }
131
+
127
132
  export interface BlockEntry {
128
133
  /** @format block-hash */
129
134
  hash: string
@@ -174,6 +179,14 @@ export interface BlockHeaderEntry {
174
179
  deps: string[]
175
180
  }
176
181
 
182
+ export interface BlocksAndEventsPerTimeStampRange {
183
+ blocksAndEvents: BlockAndEvents[][]
184
+ }
185
+
186
+ export interface BlocksPerTimeStampRange {
187
+ blocks: BlockEntry[][]
188
+ }
189
+
177
190
  export interface BrokerInfo {
178
191
  /** @format clique-id */
179
192
  cliqueId: string
@@ -490,6 +503,18 @@ export interface ContractEvent {
490
503
  fields: Val[]
491
504
  }
492
505
 
506
+ export interface ContractEventByBlockHash {
507
+ /** @format 32-byte-hash */
508
+ txId: string
509
+
510
+ /** @format address */
511
+ contractAddress: string
512
+
513
+ /** @format int32 */
514
+ eventIndex: number
515
+ fields: Val[]
516
+ }
517
+
493
518
  export interface ContractEventByTxId {
494
519
  /** @format block-hash */
495
520
  blockHash: string
@@ -509,11 +534,12 @@ export interface ContractEvents {
509
534
  nextStart: number
510
535
  }
511
536
 
537
+ export interface ContractEventsByBlockHash {
538
+ events: ContractEventByBlockHash[]
539
+ }
540
+
512
541
  export interface ContractEventsByTxId {
513
542
  events: ContractEventByTxId[]
514
-
515
- /** @format int32 */
516
- nextStart: number
517
543
  }
518
544
 
519
545
  export interface ContractOutput {
@@ -584,10 +610,6 @@ export interface EventSig {
584
610
  fieldTypes: string[]
585
611
  }
586
612
 
587
- export interface FetchResponse {
588
- blocks: BlockEntry[][]
589
- }
590
-
591
613
  export interface FieldsSig {
592
614
  names: string[]
593
615
  types: string[]
@@ -1847,13 +1869,36 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
1847
1869
  * No description
1848
1870
  *
1849
1871
  * @tags Blockflow
1850
- * @name GetBlockflow
1872
+ * @name GetBlockflowBlocks
1851
1873
  * @summary List blocks on the given time interval
1852
- * @request GET:/blockflow
1874
+ * @request GET:/blockflow/blocks
1853
1875
  */
1854
- getBlockflow: (query: { fromTs: number; toTs?: number }, params: RequestParams = {}) =>
1855
- this.request<FetchResponse, BadRequest | Unauthorized | NotFound | InternalServerError | ServiceUnavailable>({
1856
- path: `/blockflow`,
1876
+ getBlockflowBlocks: (query: { fromTs: number; toTs?: number }, params: RequestParams = {}) =>
1877
+ this.request<
1878
+ BlocksPerTimeStampRange,
1879
+ BadRequest | Unauthorized | NotFound | InternalServerError | ServiceUnavailable
1880
+ >({
1881
+ path: `/blockflow/blocks`,
1882
+ method: 'GET',
1883
+ query: query,
1884
+ format: 'json',
1885
+ ...params
1886
+ }).then(convertHttpResponse),
1887
+
1888
+ /**
1889
+ * No description
1890
+ *
1891
+ * @tags Blockflow
1892
+ * @name GetBlockflowBlocksWithEvents
1893
+ * @summary List blocks with events on the given time interval
1894
+ * @request GET:/blockflow/blocks-with-events
1895
+ */
1896
+ getBlockflowBlocksWithEvents: (query: { fromTs: number; toTs?: number }, params: RequestParams = {}) =>
1897
+ this.request<
1898
+ BlocksAndEventsPerTimeStampRange,
1899
+ BadRequest | Unauthorized | NotFound | InternalServerError | ServiceUnavailable
1900
+ >({
1901
+ path: `/blockflow/blocks-with-events`,
1857
1902
  method: 'GET',
1858
1903
  query: query,
1859
1904
  format: 'json',
@@ -1876,6 +1921,22 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
1876
1921
  ...params
1877
1922
  }).then(convertHttpResponse),
1878
1923
 
1924
+ /**
1925
+ * No description
1926
+ *
1927
+ * @tags Blockflow
1928
+ * @name GetBlockflowBlocksWithEventsBlockHash
1929
+ * @summary Get a block and events with hash
1930
+ * @request GET:/blockflow/blocks-with-events/{block_hash}
1931
+ */
1932
+ getBlockflowBlocksWithEventsBlockHash: (blockHash: string, params: RequestParams = {}) =>
1933
+ this.request<BlockAndEvents, BadRequest | Unauthorized | NotFound | InternalServerError | ServiceUnavailable>({
1934
+ path: `/blockflow/blocks-with-events/${blockHash}`,
1935
+ method: 'GET',
1936
+ format: 'json',
1937
+ ...params
1938
+ }).then(convertHttpResponse),
1939
+
1879
1940
  /**
1880
1941
  * No description
1881
1942
  *
@@ -2389,6 +2450,23 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
2389
2450
  ...params
2390
2451
  }).then(convertHttpResponse),
2391
2452
 
2453
+ /**
2454
+ * No description
2455
+ *
2456
+ * @tags Miners
2457
+ * @name PostMinersCpuMiningMineOneBlock
2458
+ * @summary Mine a block on CPU miner. !!! for test only !!!
2459
+ * @request POST:/miners/cpu-mining/mine-one-block
2460
+ */
2461
+ postMinersCpuMiningMineOneBlock: (query: { fromGroup: number; toGroup: number }, params: RequestParams = {}) =>
2462
+ this.request<boolean, BadRequest | Unauthorized | NotFound | InternalServerError | ServiceUnavailable>({
2463
+ path: `/miners/cpu-mining/mine-one-block`,
2464
+ method: 'POST',
2465
+ query: query,
2466
+ format: 'json',
2467
+ ...params
2468
+ }).then(convertHttpResponse),
2469
+
2392
2470
  /**
2393
2471
  * No description
2394
2472
  *
@@ -2433,7 +2511,7 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
2433
2511
  */
2434
2512
  getEventsContractContractaddress: (
2435
2513
  contractAddress: string,
2436
- query: { start: number; end?: number; group?: number },
2514
+ query: { start: number; limit?: number; group?: number },
2437
2515
  params: RequestParams = {}
2438
2516
  ) =>
2439
2517
  this.request<ContractEvents, BadRequest | Unauthorized | NotFound | InternalServerError | ServiceUnavailable>({
@@ -2465,7 +2543,7 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
2465
2543
  *
2466
2544
  * @tags Events
2467
2545
  * @name GetEventsTxIdTxid
2468
- * @summary Get events for a TxScript
2546
+ * @summary Get contract events for a transaction
2469
2547
  * @request GET:/events/tx-id/{txId}
2470
2548
  */
2471
2549
  getEventsTxIdTxid: (txId: string, query?: { group?: number }, params: RequestParams = {}) =>
@@ -2478,6 +2556,26 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
2478
2556
  query: query,
2479
2557
  format: 'json',
2480
2558
  ...params
2559
+ }).then(convertHttpResponse),
2560
+
2561
+ /**
2562
+ * No description
2563
+ *
2564
+ * @tags Events
2565
+ * @name GetEventsBlockHashBlockhash
2566
+ * @summary Get contract events for a block
2567
+ * @request GET:/events/block-hash/{blockHash}
2568
+ */
2569
+ getEventsBlockHashBlockhash: (blockHash: string, query?: { group?: number }, params: RequestParams = {}) =>
2570
+ this.request<
2571
+ ContractEventsByBlockHash,
2572
+ BadRequest | Unauthorized | NotFound | InternalServerError | ServiceUnavailable
2573
+ >({
2574
+ path: `/events/block-hash/${blockHash}`,
2575
+ method: 'GET',
2576
+ query: query,
2577
+ format: 'json',
2578
+ ...params
2481
2579
  }).then(convertHttpResponse)
2482
2580
  }
2483
2581
  }
@@ -90,8 +90,8 @@ class SourceFile {
90
90
  sourceCode: string
91
91
  sourceCodeHash: string
92
92
 
93
- getArtifactPath(artifactsRootPath: string): string {
94
- return artifactsRootPath + this.contractPath.slice(this.contractPath.indexOf('/')) + '.json'
93
+ getArtifactPath(artifactsRootDir: string): string {
94
+ return artifactsRootDir + this.contractPath.slice(this.contractPath.indexOf('/')) + '.json'
95
95
  }
96
96
 
97
97
  constructor(type: SourceType, sourceCode: string, sourceCodeHash: string, contractPath: string) {
@@ -195,8 +195,8 @@ export class Project {
195
195
  scripts: Compiled<Script>[]
196
196
  projectArtifact: ProjectArtifact
197
197
 
198
- readonly contractsRootPath: string
199
- readonly artifactsRootPath: string
198
+ readonly contractsRootDir: string
199
+ readonly artifactsRootDir: string
200
200
  readonly nodeProvider: NodeProvider
201
201
 
202
202
  static currentProject: Project
@@ -246,8 +246,8 @@ export class Project {
246
246
 
247
247
  private constructor(
248
248
  provider: NodeProvider,
249
- contractsRootPath: string,
250
- artifactsRootPath: string,
249
+ contractsRootDir: string,
250
+ artifactsRootDir: string,
251
251
  sourceFiles: SourceFile[],
252
252
  contracts: Compiled<Contract>[],
253
253
  scripts: Compiled<Script>[],
@@ -255,8 +255,8 @@ export class Project {
255
255
  projectArtifact: ProjectArtifact
256
256
  ) {
257
257
  this.nodeProvider = provider
258
- this.contractsRootPath = contractsRootPath
259
- this.artifactsRootPath = artifactsRootPath
258
+ this.contractsRootDir = contractsRootDir
259
+ this.artifactsRootDir = artifactsRootDir
260
260
  this.sourceFiles = sourceFiles
261
261
  this.contracts = contracts
262
262
  this.scripts = scripts
@@ -271,11 +271,11 @@ export class Project {
271
271
  }
272
272
 
273
273
  private getContractPath(path: string): string {
274
- return path.startsWith(`./${this.contractsRootPath}`)
274
+ return path.startsWith(`./${this.contractsRootDir}`)
275
275
  ? path.slice(2)
276
- : path.startsWith(this.contractsRootPath)
276
+ : path.startsWith(this.contractsRootDir)
277
277
  ? path
278
- : this.contractsRootPath + '/' + path
278
+ : this.contractsRootDir + '/' + path
279
279
  }
280
280
 
281
281
  static checkCompilerWarnings(warnings: string[], errorOnWarnings: boolean): void {
@@ -308,14 +308,14 @@ export class Project {
308
308
  }
309
309
 
310
310
  private async saveArtifactsToFile(): Promise<void> {
311
- const artifactsRootPath = this.artifactsRootPath
311
+ const artifactsRootDir = this.artifactsRootDir
312
312
  const saveToFile = async function (compiled: Compiled<Artifact>): Promise<void> {
313
- const artifactPath = compiled.sourceFile.getArtifactPath(artifactsRootPath)
314
- const folder = artifactPath.slice(0, artifactPath.lastIndexOf('/'))
313
+ const artifactDir = compiled.sourceFile.getArtifactPath(artifactsRootDir)
314
+ const folder = artifactDir.slice(0, artifactDir.lastIndexOf('/'))
315
315
  if (!fs.existsSync(folder)) {
316
316
  fs.mkdirSync(folder, { recursive: true })
317
317
  }
318
- return fsPromises.writeFile(artifactPath, compiled.artifact.toString())
318
+ return fsPromises.writeFile(artifactDir, compiled.artifact.toString())
319
319
  }
320
320
  for (const contract of this.contracts) {
321
321
  await saveToFile(contract)
@@ -323,7 +323,7 @@ export class Project {
323
323
  for (const script of this.scripts) {
324
324
  await saveToFile(script)
325
325
  }
326
- await this.projectArtifact.saveToFile(this.artifactsRootPath)
326
+ await this.projectArtifact.saveToFile(this.artifactsRootDir)
327
327
  }
328
328
 
329
329
  contractByCodeHash(codeHash: string): Contract {
@@ -337,8 +337,8 @@ export class Project {
337
337
  private static async compile(
338
338
  provider: NodeProvider,
339
339
  files: SourceFile[],
340
- contractsRootPath: string,
341
- artifactsRootPath: string,
340
+ contractsRootDir: string,
341
+ artifactsRootDir: string,
342
342
  errorOnWarnings: boolean,
343
343
  compilerOptions: node.CompilerOptions
344
344
  ): Promise<Project> {
@@ -362,8 +362,8 @@ export class Project {
362
362
  const projectArtifact = Project.buildProjectArtifact(files, contracts, scripts, compilerOptions)
363
363
  const project = new Project(
364
364
  provider,
365
- contractsRootPath,
366
- artifactsRootPath,
365
+ contractsRootDir,
366
+ artifactsRootDir,
367
367
  files,
368
368
  contracts,
369
369
  scripts,
@@ -378,8 +378,8 @@ export class Project {
378
378
  provider: NodeProvider,
379
379
  files: SourceFile[],
380
380
  projectArtifact: ProjectArtifact,
381
- contractsRootPath: string,
382
- artifactsRootPath: string,
381
+ contractsRootDir: string,
382
+ artifactsRootDir: string,
383
383
  errorOnWarnings: boolean,
384
384
  compilerOptions: node.CompilerOptions
385
385
  ): Promise<Project> {
@@ -392,20 +392,20 @@ export class Project {
392
392
  throw Error(`Unable to find project info for ${file.contractPath}, please rebuild the project`)
393
393
  }
394
394
  const warnings = info.warnings
395
- const artifactPath = file.getArtifactPath(artifactsRootPath)
395
+ const artifactDir = file.getArtifactPath(artifactsRootDir)
396
396
  if (file.type === SourceType.Contract) {
397
- const artifact = await Contract.fromArtifactFile(artifactPath)
397
+ const artifact = await Contract.fromArtifactFile(artifactDir)
398
398
  contracts.push(new Compiled(file, artifact, warnings))
399
399
  } else if (file.type === SourceType.Script) {
400
- const artifact = await Script.fromArtifactFile(artifactPath)
400
+ const artifact = await Script.fromArtifactFile(artifactDir)
401
401
  scripts.push(new Compiled(file, artifact, warnings))
402
402
  }
403
403
  }
404
404
 
405
405
  return new Project(
406
406
  provider,
407
- contractsRootPath,
408
- artifactsRootPath,
407
+ contractsRootDir,
408
+ artifactsRootDir,
409
409
  files,
410
410
  contracts,
411
411
  scripts,
@@ -414,7 +414,7 @@ export class Project {
414
414
  )
415
415
  } catch (error) {
416
416
  console.log(`Failed to load artifacts, error: ${error}, try to re-compile contracts...`)
417
- return Project.compile(provider, files, contractsRootPath, artifactsRootPath, errorOnWarnings, compilerOptions)
417
+ return Project.compile(provider, files, contractsRootDir, artifactsRootDir, errorOnWarnings, compilerOptions)
418
418
  }
419
419
  }
420
420
 
@@ -439,7 +439,7 @@ export class Project {
439
439
  return SourceFile.from(type, sourceStr, contractPath)
440
440
  }
441
441
 
442
- private static async loadSourceFiles(contractsRootPath: string): Promise<SourceFile[]> {
442
+ private static async loadSourceFiles(contractsRootDir: string): Promise<SourceFile[]> {
443
443
  const loadDir = async function (dirPath: string, results: SourceFile[]): Promise<void> {
444
444
  const dirents = await fsPromises.readdir(dirPath, { withFileTypes: true })
445
445
  for (const dirent of dirents) {
@@ -453,7 +453,7 @@ export class Project {
453
453
  }
454
454
  }
455
455
  const sourceFiles: SourceFile[] = []
456
- await loadDir(contractsRootPath, sourceFiles)
456
+ await loadDir(contractsRootDir, sourceFiles)
457
457
  const contractAndScriptSize = sourceFiles.filter(
458
458
  (f) => f.type === SourceType.Contract || f.type === SourceType.Script
459
459
  ).length
@@ -463,33 +463,36 @@ export class Project {
463
463
  return sourceFiles.sort((a, b) => a.type - b.type)
464
464
  }
465
465
 
466
+ static readonly DEFAULT_CONTRACTS_DIR = 'contracts'
467
+ static readonly DEFAULT_ARTIFACTS_DIR = 'artifacts'
468
+
466
469
  static async build(
467
470
  compilerOptionsPartial: Partial<CompilerOptions> = {},
468
- contractsRootPath = 'contracts',
469
- artifactsRootPath = 'artifacts'
471
+ contractsRootDir = Project.DEFAULT_CONTRACTS_DIR,
472
+ artifactsRootDir = Project.DEFAULT_ARTIFACTS_DIR
470
473
  ): Promise<void> {
471
474
  const provider = getCurrentNodeProvider()
472
- const sourceFiles = await Project.loadSourceFiles(contractsRootPath)
475
+ const sourceFiles = await Project.loadSourceFiles(contractsRootDir)
473
476
  const { errorOnWarnings, ...nodeCompilerOptions } = { ...DEFAULT_COMPILER_OPTIONS, ...compilerOptionsPartial }
474
- const projectArtifact = await ProjectArtifact.from(artifactsRootPath)
477
+ const projectArtifact = await ProjectArtifact.from(artifactsRootDir)
475
478
  if (typeof projectArtifact === 'undefined' || projectArtifact.needToReCompile(nodeCompilerOptions, sourceFiles)) {
476
- console.log(`Compile contracts in folder "${contractsRootPath}"`)
479
+ console.log(`Compile contracts in folder "${contractsRootDir}"`)
477
480
  Project.currentProject = await Project.compile(
478
481
  provider,
479
482
  sourceFiles,
480
- contractsRootPath,
481
- artifactsRootPath,
483
+ contractsRootDir,
484
+ artifactsRootDir,
482
485
  errorOnWarnings,
483
486
  nodeCompilerOptions
484
487
  )
485
488
  } else {
486
- console.log(`Load compiled contracts from folder "${artifactsRootPath}"`)
489
+ console.log(`Load compiled contracts from folder "${artifactsRootDir}"`)
487
490
  Project.currentProject = await Project.loadArtifacts(
488
491
  provider,
489
492
  sourceFiles,
490
493
  projectArtifact,
491
- contractsRootPath,
492
- artifactsRootPath,
494
+ contractsRootDir,
495
+ artifactsRootDir,
493
496
  errorOnWarnings,
494
497
  nodeCompilerOptions
495
498
  )
@@ -24,8 +24,6 @@ import { Buffer } from 'buffer/'
24
24
 
25
25
  import { TOTAL_NUMBER_OF_GROUPS } from '../constants'
26
26
  import djb2 from './djb2'
27
- import * as node from '../api/api-alephium'
28
- import * as explorer from '../api/api-explorer'
29
27
 
30
28
  const ec = new EC('secp256k1')
31
29
 
@@ -1,7 +0,0 @@
1
- Contract Greeter(btcPrice: U256) implements GreeterInterface {
2
- @using(readonly = true)
3
- pub fn greet() -> U256 {
4
- checkCaller!(true, 0)
5
- return btcPrice
6
- }
7
- }
@@ -1,4 +0,0 @@
1
- Interface GreeterInterface {
2
- @using(readonly = true)
3
- pub fn greet() -> U256
4
- }
@@ -1,7 +0,0 @@
1
- TxScript GreeterMain(greeterContractId: ByteVec) {
2
- let greeter0 = Greeter(greeterContractId)
3
- assert!(greeter0.greet() == 1, 0)
4
-
5
- let greeter1 = GreeterInterface(greeterContractId)
6
- assert!(greeter1.greet() == 1, 0)
7
- }
package/dev/user.conf DELETED
@@ -1,29 +0,0 @@
1
- // in most cases, modify the following two lines
2
- alephium.genesis.allocations = [{address = "1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH", amount = 1000000000000000000000000, lock-duration = 0 seconds}] // 1 million token allocated for your address
3
- alephium.consensus.num-zeros-at-least-in-hash = 0
4
- alephium.consensus.uncle-dependency-gap-time = 0 seconds
5
- alephium.network.leman-hard-fork-timestamp = 1643500800000 // GMT: 30 January 2022 00:00:00
6
-
7
- alephium.network.network-id = 4
8
- alephium.discovery.bootstrap = []
9
- alephium.wallet.locking-timeout = 99999 minutes
10
- alephium.mempool.auto-mine-for-dev = true
11
- alephium.node.event-log.enabled=true
12
-
13
- alephium.network.rest-port = 22973
14
- alephium.network.ws-port = 21973
15
- alephium.network.miner-api-port = 20973
16
- alephium.api.network-interface = "0.0.0.0"
17
- alephium.api.api-key-enabled = false
18
- alephium.mining.api-interface = "0.0.0.0"
19
- alephium.network.bind-address = "0.0.0.0:19973"
20
- alephium.network.internal-address = "alephium:19973"
21
- alephium.network.coordinator-address = "alephium:19973"
22
-
23
- // arbitrary mining addresses
24
- alephium.mining.miner-addresses = [
25
- "1FsroWmeJPBhcPiUr37pWXdojRBe6jdey9uukEXk1TheA",
26
- "1CQvSXsmM5BMFKguKDPpNUfw1idiut8UifLtT8748JdHc",
27
- "193maApeJWrz9GFwWCfa982ccLARVE9Y1WgKSJaUs7UAx",
28
- "16fZKYPCZJv2TP3FArA9FLUQceTS9U8xVnSjxFG9MBKyY"
29
- ]
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
@@ -1,125 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- /*
4
- Copyright 2018 - 2022 The Alephium Authors
5
- This file is part of the alephium project.
6
-
7
- The library is free software: you can redistribute it and/or modify
8
- it under the terms of the GNU Lesser General Public License as published by
9
- the Free Software Foundation, either version 3 of the License, or
10
- (at your option) any later version.
11
-
12
- The library is distributed in the hope that it will be useful,
13
- but WITHOUT ANY WARRANTY; without even the implied warranty of
14
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
- GNU Lesser General Public License for more details.
16
-
17
- You should have received a copy of the GNU Lesser General Public License
18
- along with the library. If not, see <http://www.gnu.org/licenses/>.
19
- */
20
- var __importDefault = (this && this.__importDefault) || function (mod) {
21
- return (mod && mod.__esModule) ? mod : { "default": mod };
22
- };
23
- Object.defineProperty(exports, "__esModule", { value: true });
24
- const fs_extra_1 = __importDefault(require("fs-extra"));
25
- const process_1 = __importDefault(require("process"));
26
- const path_1 = __importDefault(require("path"));
27
- const find_up_1 = __importDefault(require("find-up"));
28
- const child_process_1 = require("child_process");
29
- const commander_1 = __importDefault(require("commander"));
30
- function getPackageRoot() {
31
- const packageJsonPath = find_up_1.default.sync('package.json', { cwd: path_1.default.dirname(__filename) });
32
- if (packageJsonPath) {
33
- return path_1.default.dirname(packageJsonPath);
34
- }
35
- else {
36
- throw new Error('Cannot find `package.json`');
37
- }
38
- }
39
- function extractProjectType(projectType) {
40
- if (typeof projectType === 'undefined') {
41
- return 'base';
42
- }
43
- else if (['base', 'react'].includes(projectType)) {
44
- return projectType;
45
- }
46
- else {
47
- console.log(`Invalid project type: ${projectType}, expect: base or react`);
48
- process_1.default.exit(1);
49
- }
50
- }
51
- function extractProjectRoot() {
52
- const projectRoot = path_1.default.join(projectParent, projectName);
53
- if (fs_extra_1.default.existsSync(projectRoot)) {
54
- console.log(`Project ${projectName} already exists. Try a different name.`);
55
- console.log();
56
- process_1.default.exit(1);
57
- }
58
- return projectRoot;
59
- }
60
- function copy(dir, files) {
61
- const packageDevDir = path_1.default.join(packageRoot, dir);
62
- const projectDevDir = path_1.default.join(projectRoot, dir);
63
- if (!fs_extra_1.default.existsSync(projectDevDir)) {
64
- fs_extra_1.default.mkdirSync(projectDevDir);
65
- }
66
- for (const file of files) {
67
- fs_extra_1.default.copyFileSync(path_1.default.join(packageDevDir, file), path_1.default.join(projectDevDir, file));
68
- }
69
- }
70
- function prepareShared(packageRoot, projectRoot) {
71
- console.log('Copying files');
72
- console.log(` from ${packageRoot}`);
73
- console.log(` to ${projectRoot}`);
74
- console.log('...');
75
- fs_extra_1.default.copySync(path_1.default.join(packageRoot, 'templates/shared'), projectRoot);
76
- copy('', ['.editorconfig', '.eslintignore', '.gitattributes']);
77
- copy('dev', ['user.conf']);
78
- copy('scripts', ['start-devnet.js', 'stop-devnet.js']);
79
- if (fs_extra_1.default.existsSync(path_1.default.join(packageRoot, 'gitignore'))) {
80
- fs_extra_1.default.copySync(path_1.default.join(packageRoot, 'gitignore'), path_1.default.join(projectRoot, '.gitignore'));
81
- }
82
- else {
83
- fs_extra_1.default.copySync(path_1.default.join(packageRoot, '.gitignore'), path_1.default.join(projectRoot, '.gitignore'));
84
- }
85
- console.log();
86
- }
87
- function prepareBase(packageRoot, projectRoot) {
88
- prepareShared(packageRoot, projectRoot);
89
- copy('contracts', ['greeter_main.ral']);
90
- copy('contracts/greeter', ['greeter.ral', 'greeter_interface.ral']);
91
- fs_extra_1.default.copySync(path_1.default.join(packageRoot, 'templates/base'), projectRoot);
92
- }
93
- function prepareReact(packageRoot, projectRoot, projectName) {
94
- console.log('Creating the React app');
95
- (0, child_process_1.execSync)(`npx create-react-app ${projectName} --template typescript`);
96
- prepareShared(packageRoot, projectRoot);
97
- fs_extra_1.default.copySync(path_1.default.join(packageRoot, 'templates/react'), projectRoot);
98
- console.log('Initialize the project');
99
- (0, child_process_1.execSync)('npm install --save-dev react-app-rewired crypto-browserify stream-browserify buffer process eslint-config-prettier eslint-plugin-header eslint-plugin-prettier eslint-plugin-react', { cwd: projectRoot });
100
- (0, child_process_1.execSync)('npm install && npm run prettier', { cwd: projectRoot });
101
- console.log();
102
- }
103
- const program = new commander_1.default.Command('Create sample project')
104
- .arguments('<project-directory>')
105
- .option('-t, --template <path-to-template>', 'specify a template for the project: either base or react')
106
- .parse(process_1.default.argv);
107
- const projectName = program.processedArgs[0];
108
- const projectType = program.opts()['template'];
109
- const packageRoot = getPackageRoot();
110
- const projectParent = process_1.default.cwd();
111
- const projectRoot = extractProjectRoot();
112
- switch (extractProjectType(projectType)) {
113
- case 'base':
114
- prepareBase(packageRoot, projectRoot);
115
- break;
116
- case 'react':
117
- prepareReact(packageRoot, projectRoot, projectName);
118
- break;
119
- }
120
- console.log('✅ Done.');
121
- console.log();
122
- console.log('✨ Project is initialized!');
123
- console.log();
124
- console.log(`Next step: checkout the readme under <${projectName}>`);
125
- console.log();
@@ -1 +0,0 @@
1
- export {};