@alephium/web3 0.39.3 → 0.41.0

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 (64) 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 +1 -1
  4. package/dist/src/api/api-alephium.js +1 -1
  5. package/dist/src/api/node-provider.d.ts +2 -0
  6. package/dist/src/api/node-provider.js +12 -6
  7. package/dist/src/api/utils.d.ts +1 -1
  8. package/dist/src/block/block.d.ts +28 -0
  9. package/dist/src/block/block.js +131 -0
  10. package/dist/src/block/index.d.ts +1 -0
  11. package/dist/src/block/index.js +22 -0
  12. package/dist/src/codec/contract-output-codec.js +4 -4
  13. package/dist/src/codec/instr-codec.d.ts +3 -0
  14. package/dist/src/codec/instr-codec.js +19 -3
  15. package/dist/src/codec/lockup-script-codec.js +2 -2
  16. package/dist/src/codec/method-codec.d.ts +3 -1
  17. package/dist/src/codec/method-codec.js +27 -2
  18. package/dist/src/codec/script-codec.d.ts +11 -6
  19. package/dist/src/codec/script-codec.js +13 -2
  20. package/dist/src/codec/transaction-codec.js +2 -2
  21. package/dist/src/codec/unlock-script-codec.d.ts +2 -2
  22. package/dist/src/codec/unsigned-tx-codec.d.ts +2 -2
  23. package/dist/src/contract/contract.d.ts +25 -7
  24. package/dist/src/contract/contract.js +136 -51
  25. package/dist/src/contract/events.d.ts +1 -2
  26. package/dist/src/contract/events.js +28 -14
  27. package/dist/src/index.d.ts +1 -0
  28. package/dist/src/index.js +1 -0
  29. package/dist/src/signer/tx-builder.js +4 -4
  30. package/dist/src/transaction/status.js +28 -4
  31. package/dist/src/utils/address.js +29 -16
  32. package/dist/src/utils/exchange.js +25 -15
  33. package/dist/src/utils/number.d.ts +1 -1
  34. package/dist/src/utils/sign.js +6 -6
  35. package/dist/src/utils/subscription.d.ts +4 -4
  36. package/dist/src/utils/subscription.js +1 -1
  37. package/package.json +5 -5
  38. package/src/api/api-alephium.ts +1 -1
  39. package/src/api/node-provider.ts +8 -1
  40. package/src/api/utils.ts +1 -1
  41. package/src/block/block.ts +139 -0
  42. package/src/block/index.ts +19 -0
  43. package/src/codec/contract-output-codec.ts +1 -1
  44. package/src/codec/instr-codec.ts +14 -1
  45. package/src/codec/lockup-script-codec.ts +3 -3
  46. package/src/codec/method-codec.ts +41 -3
  47. package/src/codec/script-codec.ts +23 -5
  48. package/src/codec/transaction-codec.ts +1 -1
  49. package/src/codec/unlock-script-codec.ts +2 -2
  50. package/src/codec/unsigned-tx-codec.ts +2 -2
  51. package/src/contract/contract.ts +178 -67
  52. package/src/contract/events.ts +6 -18
  53. package/src/index.ts +1 -0
  54. package/src/signer/tx-builder.ts +2 -2
  55. package/src/transaction/status.ts +4 -4
  56. package/src/utils/address.ts +15 -2
  57. package/src/utils/exchange.ts +32 -10
  58. package/src/utils/number.ts +1 -1
  59. package/src/utils/sign.ts +1 -1
  60. package/src/utils/subscription.ts +4 -4
  61. package/std/fungible_token_interface.ral +1 -0
  62. package/std/nft_collection_interface.ral +1 -0
  63. package/std/nft_collection_with_royalty_interface.ral +1 -0
  64. package/std/nft_interface.ral +1 -0
@@ -2,10 +2,11 @@ import { NamedVals, node, NodeProvider, Number256, Token, Val } from '../api';
2
2
  import { SignDeployContractTxParams, SignDeployContractTxResult, SignExecuteScriptTxParams, SignerProvider, Address } from '../signer';
3
3
  import { Optional, HexString } from '../utils';
4
4
  import { EventSubscribeOptions, EventSubscription } from './events';
5
+ import { Method } from '../codec';
5
6
  export type FieldsSig = node.FieldsSig;
6
7
  export type MapsSig = node.MapsSig;
7
8
  export type EventSig = node.EventSig;
8
- export type FunctionSig = node.FunctionSig;
9
+ export type FunctionSig = Omit<node.FunctionSig, 'isPublic' | 'usePreapprovedAssets' | 'useAssetsInContract'>;
9
10
  export type Fields = NamedVals;
10
11
  export type Arguments = NamedVals;
11
12
  export type Constant = node.Constant;
@@ -61,7 +62,8 @@ export declare class ProjectArtifact {
61
62
  constructor(fullNodeVersion: string, compilerOptionsUsed: node.CompilerOptions, infos: Map<string, CodeInfo>);
62
63
  static isCodeChanged(current: ProjectArtifact, previous: ProjectArtifact): boolean;
63
64
  saveToFile(rootPath: string): Promise<void>;
64
- needToReCompile(compilerOptions: node.CompilerOptions, sourceInfos: SourceInfo[], fullNodeVersion: string): boolean;
65
+ getChangedSources(sourceInfos: SourceInfo[]): SourceInfo[];
66
+ needToReCompile(compilerOptions: node.CompilerOptions, fullNodeVersion: string): boolean;
65
67
  static from(rootPath: string): Promise<ProjectArtifact | undefined>;
66
68
  }
67
69
  export declare class Struct {
@@ -98,6 +100,7 @@ export declare class Project {
98
100
  private static loadStructs;
99
101
  private saveStructsToFile;
100
102
  private saveArtifactsToFile;
103
+ private saveProjectArtifact;
101
104
  contractByCodeHash(codeHash: string): Contract;
102
105
  private static getCompileResult;
103
106
  private static compile;
@@ -108,7 +111,7 @@ export declare class Project {
108
111
  private static loadSourceFiles;
109
112
  static readonly DEFAULT_CONTRACTS_DIR = "contracts";
110
113
  static readonly DEFAULT_ARTIFACTS_DIR = "artifacts";
111
- static build(compilerOptionsPartial?: Partial<CompilerOptions>, projectRootDir?: string, contractsRootDir?: string, artifactsRootDir?: string, defaultFullNodeVersion?: string | undefined): Promise<void>;
114
+ static build(compilerOptionsPartial?: Partial<CompilerOptions>, projectRootDir?: string, contractsRootDir?: string, artifactsRootDir?: string, defaultFullNodeVersion?: string | undefined, skipSaveArtifacts?: boolean): Promise<void>;
112
115
  }
113
116
  export declare abstract class Artifact {
114
117
  readonly version: string;
@@ -116,9 +119,6 @@ export declare abstract class Artifact {
116
119
  readonly functions: FunctionSig[];
117
120
  constructor(version: string, name: string, functions: FunctionSig[]);
118
121
  abstract buildByteCodeToDeploy(initialFields: Fields, isDevnet: boolean): string;
119
- publicFunctions(): string[];
120
- usingPreapprovedAssetsFunctions(): string[];
121
- usingAssetsInContractFunctions(): string[];
122
122
  isDevnet(signer: SignerProvider): Promise<boolean>;
123
123
  }
124
124
  export declare class Contract extends Artifact {
@@ -134,7 +134,11 @@ export declare class Contract extends Artifact {
134
134
  readonly stdInterfaceId?: HexString;
135
135
  readonly bytecodeDebug: string;
136
136
  readonly codeHashDebug: string;
137
+ readonly decodedMethods: Method[];
137
138
  constructor(version: string, name: string, bytecode: string, bytecodeDebugPatch: string, codeHash: string, codeHashDebug: string, fieldsSig: FieldsSig, eventsSig: EventSig[], functions: FunctionSig[], constants: Constant[], enums: Enum[], structs: Struct[], mapsSig?: MapsSig, stdInterfaceId?: HexString);
139
+ publicFunctions(): FunctionSig[];
140
+ usingPreapprovedAssetsFunctions(): FunctionSig[];
141
+ usingAssetsInContractFunctions(): FunctionSig[];
138
142
  static fromJson(artifact: any, bytecodeDebugPatch?: string, codeHashDebug?: string, structs?: Struct[]): Contract;
139
143
  static fromCompileResult(result: node.CompileContractResult, structs?: Struct[]): Contract;
140
144
  static fromArtifactFile(path: string, bytecodeDebugPatch: string, codeHashDebug: string, structs?: Struct[]): Promise<Contract>;
@@ -321,6 +325,21 @@ export declare function addStdIdToFields<F extends Fields>(contract: Contract, f
321
325
  __stdInterfaceId: HexString;
322
326
  });
323
327
  export declare function testMethod<I extends ContractInstance, F extends Fields, A extends Arguments, R, M extends Record<string, Map<Val, Val>> = Record<string, Map<Val, Val>>>(factory: ContractFactory<I, F>, methodName: string, params: Optional<TestContractParams<F, A, M>, 'testArgs' | 'initialFields'>): Promise<TestContractResult<R, M>>;
328
+ export declare class RalphMap<K extends Val, V extends Val> {
329
+ private readonly parentContract;
330
+ private readonly parentContractId;
331
+ private readonly mapName;
332
+ private readonly groupIndex;
333
+ constructor(parentContract: Contract, parentContractId: HexString, mapName: string);
334
+ get(key: K): Promise<V | undefined>;
335
+ contains(key: K): Promise<boolean>;
336
+ toJSON(): {
337
+ parentContractId: string;
338
+ mapName: string;
339
+ groupIndex: number;
340
+ };
341
+ }
342
+ export declare function getMapItem<R extends Val>(parentContract: Contract, parentContractId: HexString, groupIndex: number, mapName: string, key: Val): Promise<R | undefined>;
324
343
  export declare abstract class ContractInstance {
325
344
  readonly address: Address;
326
345
  readonly contractId: string;
@@ -338,5 +357,4 @@ export declare function multicallMethods<I extends ContractInstance, F extends F
338
357
  export declare function getContractEventsCurrentCount(contractAddress: Address): Promise<number>;
339
358
  export declare const getContractIdFromUnsignedTx: (nodeProvider: NodeProvider, unsignedTx: string) => Promise<HexString>;
340
359
  export declare const getTokenIdFromUnsignedTx: (nodeProvider: NodeProvider, unsignedTx: string) => Promise<HexString>;
341
- export declare function tryGetCallResult(result: node.CallContractResult): node.CallContractSucceeded;
342
360
  export {};
@@ -43,7 +43,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
43
43
  return (mod && mod.__esModule) ? mod : { "default": mod };
44
44
  };
45
45
  Object.defineProperty(exports, "__esModule", { value: true });
46
- exports.tryGetCallResult = exports.getTokenIdFromUnsignedTx = exports.getContractIdFromUnsignedTx = exports.getContractEventsCurrentCount = exports.multicallMethods = exports.callMethod = exports.subscribeContractEvents = exports.subscribeContractEvent = exports.decodeEvent = exports.subscribeContractDestroyedEvent = exports.subscribeContractCreatedEvent = exports.fetchContractState = exports.ContractInstance = exports.testMethod = exports.addStdIdToFields = exports.subscribeEventsFromContract = exports.decodeContractDestroyedEvent = exports.decodeContractCreatedEvent = exports.DestroyContractEventAddresses = exports.CreateContractEventAddresses = exports.ExecutableScript = exports.ContractFactory = exports.randomTxId = exports.fromApiEventFields = exports.fromApiArray = exports.getDefaultValue = exports.fromApiFields = exports.Script = exports.Contract = exports.Artifact = exports.Project = exports.Struct = exports.ProjectArtifact = exports.DEFAULT_COMPILER_OPTIONS = exports.DEFAULT_NODE_COMPILER_OPTIONS = exports.StdIdFieldName = void 0;
46
+ exports.getTokenIdFromUnsignedTx = exports.getContractIdFromUnsignedTx = exports.getContractEventsCurrentCount = exports.multicallMethods = exports.callMethod = exports.subscribeContractEvents = exports.subscribeContractEvent = exports.decodeEvent = exports.subscribeContractDestroyedEvent = exports.subscribeContractCreatedEvent = exports.fetchContractState = exports.ContractInstance = exports.getMapItem = exports.RalphMap = exports.testMethod = exports.addStdIdToFields = exports.subscribeEventsFromContract = exports.decodeContractDestroyedEvent = exports.decodeContractCreatedEvent = exports.DestroyContractEventAddresses = exports.CreateContractEventAddresses = exports.ExecutableScript = exports.ContractFactory = exports.randomTxId = exports.fromApiEventFields = exports.fromApiArray = exports.getDefaultValue = exports.fromApiFields = exports.Script = exports.Contract = exports.Artifact = exports.Project = exports.Struct = exports.ProjectArtifact = exports.DEFAULT_COMPILER_OPTIONS = exports.DEFAULT_NODE_COMPILER_OPTIONS = exports.StdIdFieldName = void 0;
47
47
  const buffer_1 = require("buffer/");
48
48
  const fs_1 = __importDefault(require("fs"));
49
49
  const fs_2 = require("fs");
@@ -180,7 +180,17 @@ class ProjectArtifact {
180
180
  const content = JSON.stringify(artifact, null, 2);
181
181
  return fs_2.promises.writeFile(filepath, content);
182
182
  }
183
- needToReCompile(compilerOptions, sourceInfos, fullNodeVersion) {
183
+ getChangedSources(sourceInfos) {
184
+ const result = [];
185
+ for (const sourceInfo of sourceInfos) {
186
+ const info = this.infos.get(sourceInfo.name);
187
+ if (typeof info === 'undefined' || info.sourceCodeHash !== sourceInfo.sourceCodeHash) {
188
+ result.push(sourceInfo);
189
+ }
190
+ }
191
+ return result;
192
+ }
193
+ needToReCompile(compilerOptions, fullNodeVersion) {
184
194
  ProjectArtifact.checkCompilerOptionsParameter(compilerOptions);
185
195
  if (this.fullNodeVersion !== fullNodeVersion) {
186
196
  return true;
@@ -192,15 +202,6 @@ class ProjectArtifact {
192
202
  if (!optionsMatched) {
193
203
  return true;
194
204
  }
195
- if (sourceInfos.length !== this.infos.size) {
196
- return true;
197
- }
198
- for (const sourceInfo of sourceInfos) {
199
- const info = this.infos.get(sourceInfo.name);
200
- if (typeof info === 'undefined' || info.sourceCodeHash !== sourceInfo.sourceCodeHash) {
201
- return true;
202
- }
203
- }
204
205
  return false;
205
206
  }
206
207
  static async from(rootPath) {
@@ -224,16 +225,21 @@ class ProjectArtifact {
224
225
  }
225
226
  exports.ProjectArtifact = ProjectArtifact;
226
227
  ProjectArtifact.artifactFileName = '.project.json';
227
- function removeOldArtifacts(dir) {
228
+ function removeOldArtifacts(dir, sourceFiles) {
228
229
  const files = fs_1.default.readdirSync(dir);
229
230
  files.forEach((file) => {
230
231
  const filePath = path.join(dir, file);
231
232
  const stat = fs_1.default.statSync(filePath);
232
233
  if (stat.isDirectory()) {
233
- removeOldArtifacts(filePath);
234
+ removeOldArtifacts(filePath, sourceFiles);
234
235
  }
235
236
  else if (filePath.endsWith('.ral.json') || filePath.endsWith('.ral')) {
236
- fs_1.default.unlinkSync(filePath);
237
+ const filename = path.basename(filePath);
238
+ const artifactName = filename.slice(0, filename.indexOf('.'));
239
+ const sourceFile = sourceFiles.find((s) => s.name === artifactName && (s.type === SourceKind.Contract || s.type === SourceKind.Script));
240
+ if (sourceFile === undefined) {
241
+ fs_1.default.unlinkSync(filePath);
242
+ }
237
243
  }
238
244
  });
239
245
  if (fs_1.default.readdirSync(dir).length === 0) {
@@ -359,7 +365,7 @@ class Project {
359
365
  const filePath = path.join(this.artifactsRootDir, 'structs.ral.json');
360
366
  return fs_2.promises.writeFile(filePath, JSON.stringify(structs, null, 2));
361
367
  }
362
- async saveArtifactsToFile(projectRootDir) {
368
+ async saveArtifactsToFile(projectRootDir, skipSaveArtifacts, changedSources) {
363
369
  const artifactsRootDir = this.artifactsRootDir;
364
370
  const saveToFile = async function (compiled) {
365
371
  const artifactPath = compiled.sourceInfo.getArtifactPath(artifactsRootDir);
@@ -369,9 +375,31 @@ class Project {
369
375
  }
370
376
  return fs_2.promises.writeFile(artifactPath, compiled.artifact.toString());
371
377
  };
372
- this.contracts.forEach((contract) => saveToFile(contract));
373
- this.scripts.forEach((script) => saveToFile(script));
374
- this.saveStructsToFile();
378
+ for (const [_, contract] of this.contracts) {
379
+ if (!skipSaveArtifacts || changedSources.find((s) => s.name === contract.sourceInfo.name) !== undefined) {
380
+ await saveToFile(contract);
381
+ }
382
+ }
383
+ for (const [_, script] of this.scripts) {
384
+ await saveToFile(script);
385
+ }
386
+ await this.saveStructsToFile();
387
+ await this.saveProjectArtifact(projectRootDir, skipSaveArtifacts, changedSources);
388
+ }
389
+ async saveProjectArtifact(projectRootDir, skipSaveArtifacts, changedSources) {
390
+ if (skipSaveArtifacts) {
391
+ // we should not update the `codeHashDebug` if the `skipSaveArtifacts` is enabled
392
+ const prevProjectArtifact = await ProjectArtifact.from(projectRootDir);
393
+ if (prevProjectArtifact !== undefined) {
394
+ for (const [name, info] of this.projectArtifact.infos) {
395
+ if (changedSources.find((s) => s.name === name) === undefined) {
396
+ const prevInfo = prevProjectArtifact.infos.get(name);
397
+ info.bytecodeDebugPatch = prevInfo?.bytecodeDebugPatch ?? info.bytecodeDebugPatch;
398
+ info.codeHashDebug = prevInfo?.codeHashDebug ?? info.codeHashDebug;
399
+ }
400
+ }
401
+ }
402
+ }
375
403
  await this.projectArtifact.saveToFile(projectRootDir);
376
404
  }
377
405
  contractByCodeHash(codeHash) {
@@ -406,7 +434,7 @@ class Project {
406
434
  throw new Error(newError);
407
435
  }
408
436
  }
409
- static async compile(fullNodeVersion, provider, sourceInfos, projectRootDir, contractsRootDir, artifactsRootDir, errorOnWarnings, compilerOptions) {
437
+ static async compile(fullNodeVersion, provider, sourceInfos, projectRootDir, contractsRootDir, artifactsRootDir, errorOnWarnings, compilerOptions, changedSources, skipSaveArtifacts = false) {
410
438
  const removeDuplicates = sourceInfos.reduce((acc, sourceInfo) => {
411
439
  if (acc.find((info) => info.sourceCodeHash === sourceInfo.sourceCodeHash) === undefined) {
412
440
  acc.push(sourceInfo);
@@ -437,10 +465,14 @@ class Project {
437
465
  });
438
466
  const projectArtifact = Project.buildProjectArtifact(fullNodeVersion, sourceInfos, contracts, scripts, compilerOptions);
439
467
  const project = new Project(contractsRootDir, artifactsRootDir, sourceInfos, contracts, scripts, structs, errorOnWarnings, projectArtifact);
440
- await project.saveArtifactsToFile(projectRootDir);
468
+ await project.saveArtifactsToFile(projectRootDir, skipSaveArtifacts, changedSources);
441
469
  return project;
442
470
  }
443
- static async loadArtifacts(provider, sourceInfos, projectArtifact, projectRootDir, contractsRootDir, artifactsRootDir, errorOnWarnings, compilerOptions) {
471
+ static async loadArtifacts(provider, sourceInfos, projectRootDir, contractsRootDir, artifactsRootDir, errorOnWarnings, compilerOptions) {
472
+ const projectArtifact = await ProjectArtifact.from(projectRootDir);
473
+ if (projectArtifact === undefined) {
474
+ throw Error('Failed to load project artifact');
475
+ }
444
476
  try {
445
477
  const contracts = new Map();
446
478
  const scripts = new Map();
@@ -465,7 +497,7 @@ class Project {
465
497
  }
466
498
  catch (error) {
467
499
  console.log(`Failed to load artifacts, error: ${error}, try to re-compile contracts...`);
468
- return Project.compile(projectArtifact.fullNodeVersion, provider, sourceInfos, projectRootDir, contractsRootDir, artifactsRootDir, errorOnWarnings, compilerOptions);
500
+ return Project.compile(projectArtifact.fullNodeVersion, provider, sourceInfos, projectRootDir, contractsRootDir, artifactsRootDir, errorOnWarnings, compilerOptions, sourceInfos);
469
501
  }
470
502
  }
471
503
  static getImportSourcePath(projectRootDir, importPath) {
@@ -550,24 +582,24 @@ class Project {
550
582
  }
551
583
  return sourceInfos.sort((a, b) => a.type - b.type);
552
584
  }
553
- static async build(compilerOptionsPartial = {}, projectRootDir = '.', contractsRootDir = Project.DEFAULT_CONTRACTS_DIR, artifactsRootDir = Project.DEFAULT_ARTIFACTS_DIR, defaultFullNodeVersion = undefined) {
585
+ static async build(compilerOptionsPartial = {}, projectRootDir = '.', contractsRootDir = Project.DEFAULT_CONTRACTS_DIR, artifactsRootDir = Project.DEFAULT_ARTIFACTS_DIR, defaultFullNodeVersion = undefined, skipSaveArtifacts = false) {
554
586
  const provider = (0, global_1.getCurrentNodeProvider)();
555
587
  const fullNodeVersion = defaultFullNodeVersion ?? (await provider.infos.getInfosVersion()).version;
556
588
  const sourceFiles = await Project.loadSourceFiles(projectRootDir, contractsRootDir);
557
589
  const { errorOnWarnings, ...nodeCompilerOptions } = { ...exports.DEFAULT_COMPILER_OPTIONS, ...compilerOptionsPartial };
558
590
  const projectArtifact = await ProjectArtifact.from(projectRootDir);
591
+ const changedSources = projectArtifact?.getChangedSources(sourceFiles) ?? sourceFiles;
559
592
  if (projectArtifact === undefined ||
560
- projectArtifact.needToReCompile(nodeCompilerOptions, sourceFiles, fullNodeVersion)) {
593
+ projectArtifact.needToReCompile(nodeCompilerOptions, fullNodeVersion) ||
594
+ changedSources.length > 0) {
561
595
  if (fs_1.default.existsSync(artifactsRootDir)) {
562
- removeOldArtifacts(artifactsRootDir);
596
+ removeOldArtifacts(artifactsRootDir, sourceFiles);
563
597
  }
564
598
  console.log(`Compiling contracts in folder "${contractsRootDir}"`);
565
- Project.currentProject = await Project.compile(fullNodeVersion, provider, sourceFiles, projectRootDir, contractsRootDir, artifactsRootDir, errorOnWarnings, nodeCompilerOptions);
566
- }
567
- else {
568
- console.log(`Contracts are compiled already. Loading them from folder "${artifactsRootDir}"`);
569
- Project.currentProject = await Project.loadArtifacts(provider, sourceFiles, projectArtifact, projectRootDir, contractsRootDir, artifactsRootDir, errorOnWarnings, nodeCompilerOptions);
599
+ Project.currentProject = await Project.compile(fullNodeVersion, provider, sourceFiles, projectRootDir, contractsRootDir, artifactsRootDir, errorOnWarnings, nodeCompilerOptions, changedSources, skipSaveArtifacts);
570
600
  }
601
+ // we need to reload those contracts that did not regenerate bytecode
602
+ Project.currentProject = await Project.loadArtifacts(provider, sourceFiles, projectRootDir, contractsRootDir, artifactsRootDir, errorOnWarnings, nodeCompilerOptions);
571
603
  }
572
604
  }
573
605
  exports.Project = Project;
@@ -592,15 +624,6 @@ class Artifact {
592
624
  this.name = name;
593
625
  this.functions = functions;
594
626
  }
595
- publicFunctions() {
596
- return this.functions.filter((func) => func.isPublic).map((func) => func.name);
597
- }
598
- usingPreapprovedAssetsFunctions() {
599
- return this.functions.filter((func) => func.usePreapprovedAssets).map((func) => func.name);
600
- }
601
- usingAssetsInContractFunctions() {
602
- return this.functions.filter((func) => func.useAssetsInContract).map((func) => func.name);
603
- }
604
627
  async isDevnet(signer) {
605
628
  if (!signer.nodeProvider) {
606
629
  return false;
@@ -610,6 +633,15 @@ class Artifact {
610
633
  }
611
634
  }
612
635
  exports.Artifact = Artifact;
636
+ function fromFunctionSig(sig) {
637
+ return {
638
+ name: sig.name,
639
+ paramNames: sig.paramNames,
640
+ paramTypes: sig.paramTypes,
641
+ paramIsMutable: sig.paramIsMutable,
642
+ returnTypes: sig.returnTypes
643
+ };
644
+ }
613
645
  class Contract extends Artifact {
614
646
  constructor(version, name, bytecode, bytecodeDebugPatch, codeHash, codeHashDebug, fieldsSig, eventsSig, functions, constants, enums, structs, mapsSig, stdInterfaceId) {
615
647
  super(version, name, functions);
@@ -625,6 +657,16 @@ class Contract extends Artifact {
625
657
  this.stdInterfaceId = stdInterfaceId;
626
658
  this.bytecodeDebug = ralph.buildDebugBytecode(this.bytecode, this.bytecodeDebugPatch);
627
659
  this.codeHashDebug = codeHashDebug;
660
+ this.decodedMethods = codec_1.contract.contractCodec.decodeContract(buffer_1.Buffer.from(bytecode, 'hex')).methods;
661
+ }
662
+ publicFunctions() {
663
+ return this.functions.filter((_, index) => this.decodedMethods[`${index}`].isPublic);
664
+ }
665
+ usingPreapprovedAssetsFunctions() {
666
+ return this.functions.filter((_, index) => this.decodedMethods[`${index}`].usePreapprovedAssets);
667
+ }
668
+ usingAssetsInContractFunctions() {
669
+ return this.functions.filter((_, index) => this.decodedMethods[`${index}`].useContractAssets);
628
670
  }
629
671
  // TODO: safely parse json
630
672
  static fromJson(artifact, bytecodeDebugPatch = '', codeHashDebug = '', structs = []) {
@@ -643,7 +685,7 @@ class Contract extends Artifact {
643
685
  return contract;
644
686
  }
645
687
  static fromCompileResult(result, structs = []) {
646
- return new Contract(result.version, result.name, result.bytecode, result.bytecodeDebugPatch, result.codeHash, result.codeHashDebug, result.fields, result.events, result.functions, result.constants, result.enums, structs, result.maps, result.stdInterfaceId);
688
+ return new Contract(result.version, result.name, result.bytecode, result.bytecodeDebugPatch, result.codeHash, result.codeHashDebug, result.fields, result.events, result.functions.map(fromFunctionSig), result.constants, result.enums, structs, result.maps, result.stdInterfaceId);
647
689
  }
648
690
  // support both 'code.ral' and 'code.ral.json'
649
691
  static async fromArtifactFile(path, bytecodeDebugPatch, codeHashDebug, structs = []) {
@@ -871,7 +913,7 @@ class Contract extends Artifact {
871
913
  }
872
914
  fromApiCallContractResult(result, txId, methodIndex, getContractByCodeHash) {
873
915
  const returnTypes = this.functions[`${methodIndex}`].returnTypes;
874
- const callResult = tryGetCallResult(result);
916
+ const callResult = (0, api_1.tryGetCallResult)(result);
875
917
  const rawReturn = fromApiArray(callResult.returns, returnTypes, this.structs);
876
918
  const returns = rawReturn.length === 0 ? null : rawReturn.length === 1 ? rawReturn[0] : rawReturn;
877
919
  const addressToCodeHash = new Map();
@@ -909,7 +951,7 @@ class Script extends Artifact {
909
951
  this.structs = structs;
910
952
  }
911
953
  static fromCompileResult(result, structs = []) {
912
- return new Script(result.version, result.name, result.bytecodeTemplate, result.bytecodeDebugPatch, result.fields, result.functions, structs);
954
+ return new Script(result.version, result.name, result.bytecodeTemplate, result.bytecodeDebugPatch, result.fields, result.functions.map(fromFunctionSig), structs);
913
955
  }
914
956
  // TODO: safely parse json
915
957
  static fromJson(artifact, bytecodeDebugPatch = '', structs = []) {
@@ -1215,7 +1257,9 @@ function genCodeForType(type, structs) {
1215
1257
  const { immFields, mutFields } = ralph.calcFieldSize(type, true, structs);
1216
1258
  const loadImmFieldByIndex = {
1217
1259
  isPublic: true,
1218
- assetModifier: 0,
1260
+ usePreapprovedAssets: false,
1261
+ useContractAssets: false,
1262
+ usePayToContractOnly: false,
1219
1263
  argsLength: 1,
1220
1264
  localsLength: 1,
1221
1265
  returnLength: 1,
@@ -1243,7 +1287,9 @@ function genCodeForType(type, structs) {
1243
1287
  };
1244
1288
  const destroy = {
1245
1289
  isPublic: true,
1246
- assetModifier: 2,
1290
+ usePreapprovedAssets: false,
1291
+ useContractAssets: true,
1292
+ usePayToContractOnly: false,
1247
1293
  argsLength: 1,
1248
1294
  localsLength: 1,
1249
1295
  returnLength: 0,
@@ -1321,6 +1367,52 @@ async function testMethod(factory, methodName, params) {
1321
1367
  };
1322
1368
  }
1323
1369
  exports.testMethod = testMethod;
1370
+ class RalphMap {
1371
+ constructor(parentContract, parentContractId, mapName) {
1372
+ this.parentContract = parentContract;
1373
+ this.parentContractId = parentContractId;
1374
+ this.mapName = mapName;
1375
+ this.groupIndex = (0, utils_1.groupOfAddress)((0, utils_1.addressFromContractId)(parentContractId));
1376
+ }
1377
+ async get(key) {
1378
+ return getMapItem(this.parentContract, this.parentContractId, this.groupIndex, this.mapName, key);
1379
+ }
1380
+ async contains(key) {
1381
+ return this.get(key).then((v) => v !== undefined);
1382
+ }
1383
+ toJSON() {
1384
+ return {
1385
+ parentContractId: this.parentContractId,
1386
+ mapName: this.mapName,
1387
+ groupIndex: this.groupIndex
1388
+ };
1389
+ }
1390
+ }
1391
+ exports.RalphMap = RalphMap;
1392
+ async function getMapItem(parentContract, parentContractId, groupIndex, mapName, key) {
1393
+ const index = parentContract.mapsSig?.names.findIndex((name) => name === mapName);
1394
+ const mapType = index === undefined ? undefined : parentContract.mapsSig?.types[`${index}`];
1395
+ if (mapType === undefined) {
1396
+ throw new Error(`Map ${mapName} does not exist in contract ${parentContract.name}`);
1397
+ }
1398
+ const [keyType, valueType] = ralph.parseMapType(mapType);
1399
+ const mapItemContractId = calcWrapperContractId(parentContractId, index, key, keyType, groupIndex);
1400
+ const mapItemAddress = (0, utils_1.addressFromContractId)(mapItemContractId);
1401
+ try {
1402
+ const state = await (0, global_1.getCurrentNodeProvider)().contracts.getContractsAddressState(mapItemAddress);
1403
+ const fieldsSig = getContractFieldsSig(valueType);
1404
+ const fields = fromApiFields(state.immFields, state.mutFields, fieldsSig, parentContract.structs);
1405
+ return fields['value'];
1406
+ }
1407
+ catch (error) {
1408
+ if (error instanceof Error && error.message.includes('KeyNotFound')) {
1409
+ // the map item contract does not exist
1410
+ return undefined;
1411
+ }
1412
+ throw error;
1413
+ }
1414
+ }
1415
+ exports.getMapItem = getMapItem;
1324
1416
  function buildMapInfo(contract, fields) {
1325
1417
  const mapsSig = contract.mapsSig;
1326
1418
  if (mapsSig === undefined)
@@ -1524,10 +1616,3 @@ const getContractIdFromUnsignedTx = async (nodeProvider, unsignedTx) => {
1524
1616
  exports.getContractIdFromUnsignedTx = getContractIdFromUnsignedTx;
1525
1617
  // This function only works in the simple case where a single non-subcontract is created in the tx
1526
1618
  exports.getTokenIdFromUnsignedTx = exports.getContractIdFromUnsignedTx;
1527
- function tryGetCallResult(result) {
1528
- if (result.type === 'CallContractFailed') {
1529
- throw new Error(`Failed to call contract, error: ${result.error}`);
1530
- }
1531
- return result;
1532
- }
1533
- exports.tryGetCallResult = tryGetCallResult;
@@ -1,14 +1,13 @@
1
1
  import { node } from '../api';
2
2
  import { Subscription, SubscribeOptions } from '../utils';
3
3
  export interface EventSubscribeOptions<Message> extends SubscribeOptions<Message> {
4
- onEventCountChanged?: (eventCount: number) => Promise<void>;
4
+ onEventCountChanged?: (eventCount: number) => Promise<void> | void;
5
5
  }
6
6
  export declare class EventSubscription extends Subscription<node.ContractEvent> {
7
7
  readonly contractAddress: string;
8
8
  private fromCount;
9
9
  private onEventCountChanged?;
10
10
  constructor(options: EventSubscribeOptions<node.ContractEvent>, contractAddress: string, fromCount?: number);
11
- startPolling(): void;
12
11
  currentEventCount(): number;
13
12
  polling(): Promise<void>;
14
13
  }
@@ -16,9 +16,32 @@ GNU Lesser General Public License for more details.
16
16
  You should have received a copy of the GNU Lesser General Public License
17
17
  along with the library. If not, see <http://www.gnu.org/licenses/>.
18
18
  */
19
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = 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);
26
+ }) : (function(o, m, k, k2) {
27
+ if (k2 === undefined) k2 = k;
28
+ o[k2] = m[k];
29
+ }));
30
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
31
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
32
+ }) : function(o, v) {
33
+ o["default"] = v;
34
+ });
35
+ var __importStar = (this && this.__importStar) || function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
19
42
  Object.defineProperty(exports, "__esModule", { value: true });
20
43
  exports.subscribeToEvents = exports.EventSubscription = void 0;
21
- const __1 = require("..");
44
+ const web3 = __importStar(require("../global"));
22
45
  const utils_1 = require("../utils");
23
46
  class EventSubscription extends utils_1.Subscription {
24
47
  constructor(options, contractAddress, fromCount) {
@@ -26,27 +49,16 @@ class EventSubscription extends utils_1.Subscription {
26
49
  this.contractAddress = contractAddress;
27
50
  this.fromCount = typeof fromCount === 'undefined' ? 0 : fromCount;
28
51
  this.onEventCountChanged = options.onEventCountChanged;
29
- this.startPolling();
30
- }
31
- startPolling() {
32
- this.eventEmitter.on('tick', async () => {
33
- await this.polling();
34
- });
35
- this.eventEmitter.emit('tick');
36
52
  }
37
53
  currentEventCount() {
38
54
  return this.fromCount;
39
55
  }
40
56
  async polling() {
41
57
  try {
42
- const events = await __1.web3.getCurrentNodeProvider().events.getEventsContractContractaddress(this.contractAddress, {
58
+ const events = await web3.getCurrentNodeProvider().events.getEventsContractContractaddress(this.contractAddress, {
43
59
  start: this.fromCount
44
60
  });
45
- if (this.cancelled) {
46
- return;
47
- }
48
61
  if (this.fromCount === events.nextStart) {
49
- this.task = setTimeout(() => this.eventEmitter.emit('tick'), this.pollingInterval);
50
62
  return;
51
63
  }
52
64
  const promises = events.events.map((event) => this.messageCallback(event));
@@ -64,6 +76,8 @@ class EventSubscription extends utils_1.Subscription {
64
76
  }
65
77
  exports.EventSubscription = EventSubscription;
66
78
  function subscribeToEvents(options, contractAddress, fromCount) {
67
- return new EventSubscription(options, contractAddress, fromCount);
79
+ const subscription = new EventSubscription(options, contractAddress, fromCount);
80
+ subscription.subscribe();
81
+ return subscription;
68
82
  }
69
83
  exports.subscribeToEvents = subscribeToEvents;
@@ -9,3 +9,4 @@ export * as web3 from './global';
9
9
  export * as codec from './codec';
10
10
  export * as utils from './utils';
11
11
  export * from './debug';
12
+ export * from './block';
package/dist/src/index.js CHANGED
@@ -58,3 +58,4 @@ exports.web3 = __importStar(require("./global"));
58
58
  exports.codec = __importStar(require("./codec"));
59
59
  exports.utils = __importStar(require("./utils"));
60
60
  __exportStar(require("./debug"), exports);
61
+ __exportStar(require("./block"), exports);
@@ -18,9 +18,9 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.
18
18
  */
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
20
  exports.TransactionBuilder = void 0;
21
- const __1 = require("..");
22
- const api_1 = require("../api");
23
21
  const utils_1 = require("../utils");
22
+ const api_1 = require("../api");
23
+ const utils_2 = require("../utils");
24
24
  const signer_1 = require("./signer");
25
25
  class TransactionBuilder {
26
26
  static from(param0, param1, customFetch) {
@@ -32,7 +32,7 @@ class TransactionBuilder {
32
32
  })();
33
33
  }
34
34
  static validatePublicKey(params, publicKey, keyType) {
35
- const address = (0, utils_1.addressFromPublicKey)(publicKey, keyType);
35
+ const address = (0, utils_2.addressFromPublicKey)(publicKey, keyType);
36
36
  if (address !== params.signerAddress) {
37
37
  throw new Error('Unmatched public key');
38
38
  }
@@ -63,7 +63,7 @@ class TransactionBuilder {
63
63
  ...rest
64
64
  };
65
65
  const response = await this.nodeProvider.contracts.postContractsUnsignedTxDeployContract(data);
66
- const contractId = __1.utils.binToHex(__1.utils.contractIdFromAddress(response.contractAddress));
66
+ const contractId = (0, utils_1.binToHex)((0, utils_1.contractIdFromAddress)(response.contractAddress));
67
67
  return { ...response, groupIndex: response.fromGroup, contractId, gasPrice: (0, api_1.fromApiNumber256)(response.gasPrice) };
68
68
  }
69
69
  async buildExecuteScriptTx(params, publicKey) {
@@ -16,9 +16,32 @@ GNU Lesser General Public License for more details.
16
16
  You should have received a copy of the GNU Lesser General Public License
17
17
  along with the library. If not, see <http://www.gnu.org/licenses/>.
18
18
  */
19
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = 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);
26
+ }) : (function(o, m, k, k2) {
27
+ if (k2 === undefined) k2 = k;
28
+ o[k2] = m[k];
29
+ }));
30
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
31
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
32
+ }) : function(o, v) {
33
+ o["default"] = v;
34
+ });
35
+ var __importStar = (this && this.__importStar) || function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
19
42
  Object.defineProperty(exports, "__esModule", { value: true });
20
43
  exports.subscribeToTxStatus = exports.TxStatusSubscription = void 0;
21
- const __1 = require("..");
44
+ const web3 = __importStar(require("../global"));
22
45
  const utils_1 = require("../utils");
23
46
  class TxStatusSubscription extends utils_1.Subscription {
24
47
  constructor(options, txId, fromGroup, toGroup, confirmations) {
@@ -27,11 +50,10 @@ class TxStatusSubscription extends utils_1.Subscription {
27
50
  this.fromGroup = fromGroup;
28
51
  this.toGroup = toGroup;
29
52
  this.confirmations = confirmations ?? 1;
30
- this.startPolling();
31
53
  }
32
54
  async polling() {
33
55
  try {
34
- const txStatus = await __1.web3.getCurrentNodeProvider().transactions.getTransactionsStatus({
56
+ const txStatus = await web3.getCurrentNodeProvider().transactions.getTransactionsStatus({
35
57
  txId: this.txId,
36
58
  fromGroup: this.fromGroup,
37
59
  toGroup: this.toGroup
@@ -48,6 +70,8 @@ class TxStatusSubscription extends utils_1.Subscription {
48
70
  }
49
71
  exports.TxStatusSubscription = TxStatusSubscription;
50
72
  function subscribeToTxStatus(options, txId, fromGroup, toGroup, confirmations) {
51
- return new TxStatusSubscription(options, txId, fromGroup, toGroup, confirmations);
73
+ const subscription = new TxStatusSubscription(options, txId, fromGroup, toGroup, confirmations);
74
+ subscription.subscribe();
75
+ return subscription;
52
76
  }
53
77
  exports.subscribeToTxStatus = subscribeToTxStatus;