@alephium/web3 0.2.0-rc.0 → 0.2.0-rc.11

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 (98) hide show
  1. package/.eslintignore +2 -2
  2. package/README.md +2 -135
  3. package/contracts/greeter/greeter.ral +3 -3
  4. package/contracts/greeter/greeter_interface.ral +1 -0
  5. package/contracts/greeter_main.ral +3 -5
  6. package/dist/alephium-web3.min.js +1 -1
  7. package/dist/alephium-web3.min.js.LICENSE.txt +0 -17
  8. package/dist/alephium-web3.min.js.map +1 -1
  9. package/dist/scripts/create-project.js +3 -2
  10. package/dist/src/api/api-alephium.d.ts +46 -13
  11. package/dist/src/api/api-alephium.js +19 -3
  12. package/dist/src/api/api-explorer.d.ts +32 -16
  13. package/dist/src/api/api-explorer.js +26 -0
  14. package/dist/src/api/index.d.ts +3 -2
  15. package/dist/src/api/index.js +22 -3
  16. package/dist/src/api/types.d.ts +23 -0
  17. package/dist/src/api/types.js +240 -0
  18. package/dist/src/contract/contract.d.ts +104 -64
  19. package/dist/src/contract/contract.js +370 -426
  20. package/dist/src/contract/events.d.ts +4 -4
  21. package/dist/src/contract/index.js +5 -1
  22. package/dist/src/contract/ralph.d.ts +4 -4
  23. package/dist/src/global.d.ts +4 -0
  24. package/dist/src/global.js +38 -0
  25. package/dist/src/index.d.ts +2 -0
  26. package/dist/src/index.js +20 -1
  27. package/dist/src/signer/index.d.ts +0 -1
  28. package/dist/src/signer/index.js +5 -2
  29. package/dist/src/signer/signer.d.ts +21 -11
  30. package/dist/src/signer/signer.js +46 -9
  31. package/dist/src/transaction/index.d.ts +0 -1
  32. package/dist/src/transaction/index.js +5 -2
  33. package/dist/src/transaction/status.d.ts +2 -1
  34. package/dist/src/utils/index.d.ts +0 -1
  35. package/dist/src/utils/index.js +5 -2
  36. package/dist/src/utils/subscription.d.ts +0 -1
  37. package/dist/src/utils/subscription.js +2 -1
  38. package/dist/src/utils/utils.d.ts +5 -4
  39. package/dist/src/utils/utils.js +18 -17
  40. package/jest-config.json +11 -0
  41. package/package.json +7 -35
  42. package/scripts/create-project.ts +3 -2
  43. package/src/api/api-alephium.ts +56 -8
  44. package/src/api/api-explorer.ts +30 -0
  45. package/src/api/index.ts +14 -3
  46. package/src/api/types.ts +233 -0
  47. package/src/contract/contract.ts +537 -526
  48. package/src/contract/events.ts +6 -6
  49. package/src/contract/ralph.ts +4 -4
  50. package/src/{transaction/sign-verify.ts → global.ts} +14 -15
  51. package/src/index.ts +3 -0
  52. package/src/signer/index.ts +0 -1
  53. package/src/signer/signer.ts +70 -19
  54. package/src/transaction/index.ts +0 -1
  55. package/src/transaction/status.ts +4 -2
  56. package/src/utils/index.ts +0 -1
  57. package/src/utils/subscription.ts +3 -3
  58. package/src/utils/utils.ts +11 -11
  59. package/templates/base/package.json +2 -2
  60. package/templates/base/src/greeter.ts +10 -9
  61. package/templates/react/package.json +2 -2
  62. package/templates/react/src/App.tsx +2 -2
  63. package/.eslintrc.json +0 -21
  64. package/LICENSE +0 -165
  65. package/contracts/add/add.ral +0 -16
  66. package/contracts/main.ral +0 -6
  67. package/contracts/sub/sub.ral +0 -9
  68. package/dist/src/signer/node-wallet.d.ts +0 -13
  69. package/dist/src/signer/node-wallet.js +0 -60
  70. package/dist/src/test/index.d.ts +0 -7
  71. package/dist/src/test/index.js +0 -41
  72. package/dist/src/test/privatekey-wallet.d.ts +0 -12
  73. package/dist/src/test/privatekey-wallet.js +0 -68
  74. package/dist/src/transaction/sign-verify.d.ts +0 -2
  75. package/dist/src/transaction/sign-verify.js +0 -58
  76. package/dist/src/utils/password-crypto.d.ts +0 -2
  77. package/dist/src/utils/password-crypto.js +0 -69
  78. package/gitignore +0 -10
  79. package/src/contract/ralph.test.ts +0 -178
  80. package/src/fixtures/address.json +0 -36
  81. package/src/fixtures/balance.json +0 -9
  82. package/src/fixtures/self-clique.json +0 -19
  83. package/src/fixtures/transaction.json +0 -13
  84. package/src/fixtures/transactions.json +0 -179
  85. package/src/signer/fixtures/genesis.json +0 -26
  86. package/src/signer/fixtures/wallets.json +0 -26
  87. package/src/signer/node-wallet.ts +0 -74
  88. package/src/test/index.ts +0 -32
  89. package/src/test/privatekey-wallet.ts +0 -58
  90. package/src/transaction/sign-verify.test.ts +0 -50
  91. package/src/utils/address.test.ts +0 -47
  92. package/src/utils/djb2.test.ts +0 -35
  93. package/src/utils/password-crypto.test.ts +0 -27
  94. package/src/utils/password-crypto.ts +0 -77
  95. package/src/utils/utils.test.ts +0 -161
  96. package/test/contract.test.ts +0 -178
  97. package/test/events.test.ts +0 -138
  98. package/test/transaction.test.ts +0 -72
@@ -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'))) {
@@ -86,7 +86,8 @@ function prepareShared(packageRoot, projectRoot) {
86
86
  }
87
87
  function prepareBase(packageRoot, projectRoot) {
88
88
  prepareShared(packageRoot, projectRoot);
89
- copy('contracts', ['greeter.ral', 'greeter_interface.ral', 'greeter_main.ral']);
89
+ copy('contracts', ['greeter_main.ral']);
90
+ copy('contracts/greeter', ['greeter.ral', 'greeter_interface.ral']);
90
91
  fs_extra_1.default.copySync(path_1.default.join(packageRoot, 'templates/base'), projectRoot);
91
92
  }
92
93
  function prepareReact(packageRoot, projectRoot, projectName) {
@@ -305,17 +305,33 @@ 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;
311
312
  fields: FieldsSig;
312
313
  functions: FunctionSig[];
313
314
  events: EventSig[];
315
+ warnings: string[];
316
+ }
317
+ export interface CompileProjectResult {
318
+ contracts: CompileContractResult[];
319
+ scripts: CompileScriptResult[];
314
320
  }
315
321
  export interface CompileScriptResult {
322
+ name: string;
316
323
  bytecodeTemplate: string;
317
324
  fields: FieldsSig;
318
325
  functions: FunctionSig[];
326
+ warnings: string[];
327
+ }
328
+ export interface CompilerOptions {
329
+ ignoreUnusedConstantsWarnings?: boolean;
330
+ ignoreUnusedVariablesWarnings?: boolean;
331
+ ignoreUnusedFieldsWarnings?: boolean;
332
+ ignoreUnusedPrivateFunctionsWarnings?: boolean;
333
+ ignoreReadonlyCheckWarnings?: boolean;
334
+ ignoreExternalCallCheckWarnings?: boolean;
319
335
  }
320
336
  export interface Confirmed {
321
337
  /** @format block-hash */
@@ -332,6 +348,7 @@ export interface Confirmed {
332
348
  }
333
349
  export interface Contract {
334
350
  code: string;
351
+ compilerOptions?: CompilerOptions;
335
352
  }
336
353
  export interface ContractEvent {
337
354
  /** @format block-hash */
@@ -409,7 +426,6 @@ export interface Destination {
409
426
  export declare type DiscoveryAction = Reachable | Unreachable;
410
427
  export interface EventSig {
411
428
  name: string;
412
- signature: string;
413
429
  fieldNames: string[];
414
430
  fieldTypes: string[];
415
431
  }
@@ -417,9 +433,9 @@ export interface FetchResponse {
417
433
  blocks: BlockEntry[][];
418
434
  }
419
435
  export interface FieldsSig {
420
- signature: string;
421
436
  names: string[];
422
437
  types: string[];
438
+ isMutable: boolean[];
423
439
  }
424
440
  export interface FixedAssetOutput {
425
441
  /** @format int32 */
@@ -438,9 +454,12 @@ export interface FixedAssetOutput {
438
454
  }
439
455
  export interface FunctionSig {
440
456
  name: string;
441
- signature: string;
442
- argNames: string[];
443
- argTypes: string[];
457
+ usePreapprovedAssets: boolean;
458
+ useAssetsInContract: boolean;
459
+ isPublic: boolean;
460
+ paramNames: string[];
461
+ paramTypes: string[];
462
+ paramIsMutable: boolean[];
444
463
  returnTypes: string[];
445
464
  }
446
465
  export interface Group {
@@ -522,6 +541,10 @@ export interface Penalty {
522
541
  value: number;
523
542
  type: string;
524
543
  }
544
+ export interface Project {
545
+ code: string;
546
+ compilerOptions?: CompilerOptions;
547
+ }
525
548
  export interface Reachable {
526
549
  peers: string[];
527
550
  type: string;
@@ -542,6 +565,7 @@ export interface RevealMnemonicResult {
542
565
  }
543
566
  export interface Script {
544
567
  code: string;
568
+ compilerOptions?: CompilerOptions;
545
569
  }
546
570
  export interface SelfClique {
547
571
  /** @format clique-id */
@@ -855,8 +879,8 @@ export declare class HttpClient<SecurityDataType = unknown> {
855
879
  }
856
880
  /**
857
881
  * @title Alephium API
858
- * @version 1.5.0-rc0
859
- * @baseUrl {protocol}://{host}:{port}
882
+ * @version 1.5.0
883
+ * @baseUrl ../
860
884
  */
861
885
  export declare class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> {
862
886
  wallets: {
@@ -1013,8 +1037,8 @@ export declare class Api<SecurityDataType extends unknown> extends HttpClient<Se
1013
1037
  * @request POST:/wallets/{wallet_name}/derive-next-address
1014
1038
  */
1015
1039
  postWalletsWalletNameDeriveNextAddress: (walletName: string, query?: {
1016
- group?: number | undefined;
1017
- } | undefined, params?: RequestParams) => Promise<AddressInfo>;
1040
+ group?: number;
1041
+ }, params?: RequestParams) => Promise<AddressInfo>;
1018
1042
  /**
1019
1043
  * @description Your wallet need to have been created with the miner flag set to true
1020
1044
  *
@@ -1146,8 +1170,8 @@ export declare class Api<SecurityDataType extends unknown> extends HttpClient<Se
1146
1170
  * @request GET:/infos/current-hashrate
1147
1171
  */
1148
1172
  getInfosCurrentHashrate: (query?: {
1149
- timespan?: number | undefined;
1150
- } | undefined, params?: RequestParams) => Promise<string>;
1173
+ timespan?: number;
1174
+ }, params?: RequestParams) => Promise<string>;
1151
1175
  };
1152
1176
  blockflow: {
1153
1177
  /**
@@ -1334,6 +1358,15 @@ export declare class Api<SecurityDataType extends unknown> extends HttpClient<Se
1334
1358
  * @request POST:/contracts/compile-contract
1335
1359
  */
1336
1360
  postContractsCompileContract: (data: Contract, params?: RequestParams) => Promise<CompileContractResult>;
1361
+ /**
1362
+ * No description
1363
+ *
1364
+ * @tags Contracts
1365
+ * @name PostContractsCompileProject
1366
+ * @summary Compile a project
1367
+ * @request POST:/contracts/compile-project
1368
+ */
1369
+ postContractsCompileProject: (data: Project, params?: RequestParams) => Promise<CompileProjectResult>;
1337
1370
  /**
1338
1371
  * No description
1339
1372
  *
@@ -1485,8 +1518,8 @@ export declare class Api<SecurityDataType extends unknown> extends HttpClient<Se
1485
1518
  * @request GET:/events/tx-id/{txId}
1486
1519
  */
1487
1520
  getEventsTxIdTxid: (txId: string, query?: {
1488
- group?: number | undefined;
1489
- } | undefined, params?: RequestParams) => Promise<ContractEventsByTxId>;
1521
+ group?: number;
1522
+ }, params?: RequestParams) => Promise<ContractEventsByTxId>;
1490
1523
  };
1491
1524
  }
1492
1525
  export {};
@@ -28,7 +28,7 @@ var ContentType;
28
28
  })(ContentType = exports.ContentType || (exports.ContentType = {}));
29
29
  class HttpClient {
30
30
  constructor(apiConfig = {}) {
31
- this.baseUrl = '{protocol}://{host}:{port}';
31
+ this.baseUrl = '../';
32
32
  this.securityData = null;
33
33
  this.abortControllers = new Map();
34
34
  this.customFetch = (...fetchParams) => fetch(...fetchParams);
@@ -158,8 +158,8 @@ class HttpClient {
158
158
  exports.HttpClient = HttpClient;
159
159
  /**
160
160
  * @title Alephium API
161
- * @version 1.5.0-rc0
162
- * @baseUrl {protocol}://{host}:{port}
161
+ * @version 1.5.0
162
+ * @baseUrl ../
163
163
  */
164
164
  class Api extends HttpClient {
165
165
  constructor() {
@@ -901,6 +901,22 @@ class Api extends HttpClient {
901
901
  format: 'json',
902
902
  ...params
903
903
  }).then(convertHttpResponse),
904
+ /**
905
+ * No description
906
+ *
907
+ * @tags Contracts
908
+ * @name PostContractsCompileProject
909
+ * @summary Compile a project
910
+ * @request POST:/contracts/compile-project
911
+ */
912
+ postContractsCompileProject: (data, params = {}) => this.request({
913
+ path: `/contracts/compile-project`,
914
+ method: 'POST',
915
+ body: data,
916
+ type: ContentType.Json,
917
+ format: 'json',
918
+ ...params
919
+ }).then(convertHttpResponse),
904
920
  /**
905
921
  * No description
906
922
  *
@@ -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
  *
@@ -470,6 +470,22 @@ export declare class Api<SecurityDataType extends unknown> extends HttpClient<Se
470
470
  * @request PUT:/utils/sanity-check
471
471
  */
472
472
  putUtilsSanityCheck: (params?: RequestParams) => Promise<void>;
473
+ /**
474
+ * @description Update global log level, accepted: TRACE, DEBUG, INFO, WARN, ERROR
475
+ *
476
+ * @tags Utils
477
+ * @name PutUtilsUpdateGlobalLoglevel
478
+ * @request PUT:/utils/update-global-loglevel
479
+ */
480
+ putUtilsUpdateGlobalLoglevel: (data: 'TRACE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR', params?: RequestParams) => Promise<void>;
481
+ /**
482
+ * @description Update logging file, only logback.xml is accepted
483
+ *
484
+ * @tags Utils
485
+ * @name PutUtilsUpdateLogConfig
486
+ * @request PUT:/utils/update-log-config
487
+ */
488
+ putUtilsUpdateLogConfig: (data: string, params?: RequestParams) => Promise<void>;
473
489
  };
474
490
  }
475
491
  export {};
@@ -450,6 +450,32 @@ class Api extends HttpClient {
450
450
  path: `/utils/sanity-check`,
451
451
  method: 'PUT',
452
452
  ...params
453
+ }).then(convertHttpResponse),
454
+ /**
455
+ * @description Update global log level, accepted: TRACE, DEBUG, INFO, WARN, ERROR
456
+ *
457
+ * @tags Utils
458
+ * @name PutUtilsUpdateGlobalLoglevel
459
+ * @request PUT:/utils/update-global-loglevel
460
+ */
461
+ putUtilsUpdateGlobalLoglevel: (data, params = {}) => this.request({
462
+ path: `/utils/update-global-loglevel`,
463
+ method: 'PUT',
464
+ body: data,
465
+ ...params
466
+ }).then(convertHttpResponse),
467
+ /**
468
+ * @description Update logging file, only logback.xml is accepted
469
+ *
470
+ * @tags Utils
471
+ * @name PutUtilsUpdateLogConfig
472
+ * @request PUT:/utils/update-log-config
473
+ */
474
+ putUtilsUpdateLogConfig: (data, params = {}) => this.request({
475
+ path: `/utils/update-log-config`,
476
+ method: 'PUT',
477
+ body: data,
478
+ ...params
453
479
  }).then(convertHttpResponse)
454
480
  };
455
481
  }
@@ -1,10 +1,11 @@
1
1
  import { Api as NodeApi } from './api-alephium';
2
2
  import { Api as ExplorerApi } from './api-explorer';
3
- export declare class NodeProvider extends NodeApi<null> {
4
- constructor(baseUrl: string);
3
+ export declare class NodeProvider extends NodeApi<string> {
4
+ constructor(baseUrl: string, apiKey?: string);
5
5
  }
6
6
  export declare class ExplorerProvider extends ExplorerApi<null> {
7
7
  constructor(baseUrl: string);
8
8
  }
9
9
  export * as node from './api-alephium';
10
10
  export * as explorer from './api-explorer';
11
+ export * from './types';
@@ -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];
@@ -35,13 +39,27 @@ var __importStar = (this && this.__importStar) || function (mod) {
35
39
  __setModuleDefault(result, mod);
36
40
  return result;
37
41
  };
42
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
43
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
44
+ };
38
45
  Object.defineProperty(exports, "__esModule", { value: true });
39
46
  exports.explorer = exports.node = exports.ExplorerProvider = exports.NodeProvider = void 0;
40
47
  const api_alephium_1 = require("./api-alephium");
41
48
  const api_explorer_1 = require("./api-explorer");
42
49
  class NodeProvider extends api_alephium_1.Api {
43
- constructor(baseUrl) {
44
- super({ baseUrl: baseUrl });
50
+ constructor(baseUrl, apiKey) {
51
+ // eslint-disable-next-line security/detect-possible-timing-attacks
52
+ if (apiKey === undefined) {
53
+ super({ baseUrl: baseUrl });
54
+ }
55
+ else {
56
+ super({
57
+ baseUrl: baseUrl,
58
+ baseApiParams: { secure: true },
59
+ securityWorker: (accessToken) => (accessToken !== null ? { headers: { 'X-API-KEY': `${accessToken}` } } : {})
60
+ });
61
+ this.setSecurityData(apiKey);
62
+ }
45
63
  }
46
64
  }
47
65
  exports.NodeProvider = NodeProvider;
@@ -53,3 +71,4 @@ class ExplorerProvider extends api_explorer_1.Api {
53
71
  exports.ExplorerProvider = ExplorerProvider;
54
72
  exports.node = __importStar(require("./api-alephium"));
55
73
  exports.explorer = __importStar(require("./api-explorer"));
74
+ __exportStar(require("./types"), exports);
@@ -0,0 +1,23 @@
1
+ import * as node from './api-alephium';
2
+ export declare type Number256 = number | bigint | string;
3
+ export declare type Val = Number256 | boolean | string | Val[];
4
+ export declare type NamedVals = Record<string, Val>;
5
+ export interface Token {
6
+ id: string;
7
+ amount: Number256;
8
+ }
9
+ export declare function toApiToken(token: Token): node.Token;
10
+ export declare function toApiTokens(tokens?: Token[]): node.Token[] | undefined;
11
+ export declare function fromApiToken(token: node.Token): Token;
12
+ export declare function fromApiTokens(tokens?: node.Token[]): Token[] | undefined;
13
+ export declare function toApiBoolean(v: Val): boolean;
14
+ export declare function toApiNumber256(v: Val): string;
15
+ export declare function toApiNumber256Optional(v?: Val): string | undefined;
16
+ export declare function fromApiNumber256(n: string): Number256;
17
+ export declare function toApiByteVec(v: Val): string;
18
+ export declare function toApiAddress(v: Val): string;
19
+ export declare function toApiArray(tpe: string, v: Val): node.Val;
20
+ export declare function toApiVal(v: Val, tpe: string): node.Val;
21
+ export declare function fromApiVals(vals: node.Val[], names: string[], types: string[]): NamedVals;
22
+ export declare function fromApiArray(vals: node.Val[], types: string[]): Val[];
23
+ export declare function fromApiVal(v: node.Val, tpe: string): Val;
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ /*
3
+ Copyright 2018 - 2022 The Alephium Authors
4
+ This file is part of the alephium project.
5
+
6
+ The library is free software: you can redistribute it and/or modify
7
+ it under the terms of the GNU Lesser General Public License as published by
8
+ the Free Software Foundation, either version 3 of the License, or
9
+ (at your option) any later version.
10
+
11
+ The library is distributed in the hope that it will be useful,
12
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ GNU Lesser General Public License for more details.
15
+
16
+ You should have received a copy of the GNU Lesser General Public License
17
+ along with the library. If not, see <http://www.gnu.org/licenses/>.
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.fromApiVal = exports.fromApiArray = exports.fromApiVals = exports.toApiVal = exports.toApiArray = exports.toApiAddress = exports.toApiByteVec = exports.fromApiNumber256 = exports.toApiNumber256Optional = exports.toApiNumber256 = exports.toApiBoolean = exports.fromApiTokens = exports.fromApiToken = exports.toApiTokens = exports.toApiToken = void 0;
21
+ const utils_1 = require("../utils");
22
+ utils_1.assertType;
23
+ function toApiToken(token) {
24
+ return { id: token.id, amount: toApiNumber256(token.amount) };
25
+ }
26
+ exports.toApiToken = toApiToken;
27
+ function toApiTokens(tokens) {
28
+ return tokens?.map(toApiToken);
29
+ }
30
+ exports.toApiTokens = toApiTokens;
31
+ function fromApiToken(token) {
32
+ return { id: token.id, amount: fromApiNumber256(token.amount) };
33
+ }
34
+ exports.fromApiToken = fromApiToken;
35
+ function fromApiTokens(tokens) {
36
+ return tokens?.map(fromApiToken);
37
+ }
38
+ exports.fromApiTokens = fromApiTokens;
39
+ function toApiBoolean(v) {
40
+ if (typeof v === 'boolean') {
41
+ return v;
42
+ }
43
+ else {
44
+ throw new Error(`Invalid boolean value: ${v}`);
45
+ }
46
+ }
47
+ exports.toApiBoolean = toApiBoolean;
48
+ // TODO: check integer bounds
49
+ function toApiNumber256(v) {
50
+ if ((typeof v === 'number' && Number.isInteger(v)) || typeof v === 'bigint') {
51
+ return v.toString();
52
+ }
53
+ else if (typeof v === 'string') {
54
+ return v;
55
+ }
56
+ else {
57
+ throw new Error(`Invalid 256 bit number: ${v}`);
58
+ }
59
+ }
60
+ exports.toApiNumber256 = toApiNumber256;
61
+ function toApiNumber256Optional(v) {
62
+ return v === undefined ? undefined : toApiNumber256(v);
63
+ }
64
+ exports.toApiNumber256Optional = toApiNumber256Optional;
65
+ function fromApiNumber256(n) {
66
+ if (Number.isSafeInteger(Number.parseInt(n))) {
67
+ return Number(n);
68
+ }
69
+ else {
70
+ return BigInt(n);
71
+ }
72
+ }
73
+ exports.fromApiNumber256 = fromApiNumber256;
74
+ // TODO: check hex string
75
+ function toApiByteVec(v) {
76
+ if (typeof v === 'string') {
77
+ // try to convert from address to contract id
78
+ try {
79
+ const address = utils_1.bs58.decode(v);
80
+ if (address.length == 33 && address[0] == 3) {
81
+ return Buffer.from(address.slice(1)).toString('hex');
82
+ }
83
+ }
84
+ catch (_) {
85
+ return v;
86
+ }
87
+ return v;
88
+ }
89
+ else {
90
+ throw new Error(`Invalid string: ${v}`);
91
+ }
92
+ }
93
+ exports.toApiByteVec = toApiByteVec;
94
+ function toApiAddress(v) {
95
+ if (typeof v === 'string') {
96
+ try {
97
+ utils_1.bs58.decode(v);
98
+ return v;
99
+ }
100
+ catch (error) {
101
+ throw new Error(`Invalid base58 string: ${v}`);
102
+ }
103
+ }
104
+ else {
105
+ throw new Error(`Invalid string: ${v}`);
106
+ }
107
+ }
108
+ exports.toApiAddress = toApiAddress;
109
+ function toApiArray(tpe, v) {
110
+ if (!Array.isArray(v)) {
111
+ throw new Error(`Expected array, got ${v}`);
112
+ }
113
+ const semiColonIndex = tpe.lastIndexOf(';');
114
+ if (semiColonIndex == -1) {
115
+ throw new Error(`Invalid Val type: ${tpe}`);
116
+ }
117
+ const subType = tpe.slice(1, semiColonIndex);
118
+ const dim = parseInt(tpe.slice(semiColonIndex + 1, -1));
119
+ if (v.length != dim) {
120
+ throw new Error(`Invalid val dimension: ${v}`);
121
+ }
122
+ else {
123
+ return { value: v.map((v) => toApiVal(v, subType)), type: 'Array' };
124
+ }
125
+ }
126
+ exports.toApiArray = toApiArray;
127
+ function toApiVal(v, tpe) {
128
+ if (tpe === 'Bool') {
129
+ return { value: toApiBoolean(v), type: tpe };
130
+ }
131
+ else if (tpe === 'U256' || tpe === 'I256') {
132
+ return { value: toApiNumber256(v), type: tpe };
133
+ }
134
+ else if (tpe === 'ByteVec') {
135
+ return { value: toApiByteVec(v), type: tpe };
136
+ }
137
+ else if (tpe === 'Address') {
138
+ return { value: toApiAddress(v), type: tpe };
139
+ }
140
+ else {
141
+ return toApiArray(tpe, v);
142
+ }
143
+ }
144
+ exports.toApiVal = toApiVal;
145
+ function _fromApiVal(vals, valIndex, tpe) {
146
+ if (vals.length === 0) {
147
+ throw new Error('Not enough Vals');
148
+ }
149
+ const firstVal = vals[`${valIndex}`];
150
+ if (tpe === 'Bool' && firstVal.type === tpe) {
151
+ return [firstVal.value, valIndex + 1];
152
+ }
153
+ else if ((tpe === 'U256' || tpe === 'I256') && firstVal.type === tpe) {
154
+ return [fromApiNumber256(firstVal.value), valIndex + 1];
155
+ }
156
+ else if ((tpe === 'ByteVec' || tpe === 'Address') && firstVal.type === tpe) {
157
+ return [firstVal.value, valIndex + 1];
158
+ }
159
+ else {
160
+ const [baseType, dims] = decodeArrayType(tpe);
161
+ const arraySize = dims.reduce((a, b) => a * b);
162
+ const nextIndex = valIndex + arraySize;
163
+ const valsToUse = vals.slice(valIndex, nextIndex);
164
+ if (valsToUse.length == arraySize && valsToUse.every((val) => val.type === baseType)) {
165
+ const localVals = valsToUse.map((val) => fromApiVal(val, baseType));
166
+ return [foldVals(localVals, dims), nextIndex];
167
+ }
168
+ else {
169
+ throw new Error(`Invalid array Val type: ${valsToUse}, ${tpe}`);
170
+ }
171
+ }
172
+ }
173
+ function fromApiVals(vals, names, types) {
174
+ let valIndex = 0;
175
+ const result = {};
176
+ types.forEach((currentType, index) => {
177
+ const currentName = names[`${index}`];
178
+ const [val, nextIndex] = _fromApiVal(vals, valIndex, currentType);
179
+ valIndex = nextIndex;
180
+ result[`${currentName}`] = val;
181
+ });
182
+ return result;
183
+ }
184
+ exports.fromApiVals = fromApiVals;
185
+ function fromApiArray(vals, types) {
186
+ let valIndex = 0;
187
+ const result = [];
188
+ for (const currentType of types) {
189
+ const [val, nextIndex] = _fromApiVal(vals, valIndex, currentType);
190
+ result.push(val);
191
+ valIndex = nextIndex;
192
+ }
193
+ return result;
194
+ }
195
+ exports.fromApiArray = fromApiArray;
196
+ function fromApiVal(v, tpe) {
197
+ if (v.type === 'Bool' && v.type === tpe) {
198
+ return v.value;
199
+ }
200
+ else if ((v.type === 'U256' || v.type === 'I256') && v.type === tpe) {
201
+ return fromApiNumber256(v.value);
202
+ }
203
+ else if ((v.type === 'ByteVec' || v.type === 'Address') && v.type === tpe) {
204
+ return v.value;
205
+ }
206
+ else {
207
+ throw new Error(`Invalid node.Val type: ${v}`);
208
+ }
209
+ }
210
+ exports.fromApiVal = fromApiVal;
211
+ function decodeArrayType(tpe) {
212
+ const semiColonIndex = tpe.lastIndexOf(';');
213
+ if (semiColonIndex === -1) {
214
+ throw new Error(`Invalid Val type: ${tpe}`);
215
+ }
216
+ const subType = tpe.slice(1, semiColonIndex);
217
+ const dim = parseInt(tpe.slice(semiColonIndex + 1, -1));
218
+ if (subType[0] == '[') {
219
+ const [baseType, subDim] = decodeArrayType(subType);
220
+ return [baseType, (subDim.unshift(dim), subDim)];
221
+ }
222
+ else {
223
+ return [subType, [dim]];
224
+ }
225
+ }
226
+ function foldVals(vals, dims) {
227
+ if (dims.length == 1) {
228
+ return vals;
229
+ }
230
+ else {
231
+ const result = [];
232
+ const chunkSize = vals.length / dims[0];
233
+ const chunkDims = dims.slice(1);
234
+ for (let i = 0; i < vals.length; i += chunkSize) {
235
+ const chunk = vals.slice(i, i + chunkSize);
236
+ result.push(foldVals(chunk, chunkDims));
237
+ }
238
+ return result;
239
+ }
240
+ }