@alephium/web3 0.40.0 → 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 (58) 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/node-provider.d.ts +2 -0
  4. package/dist/src/api/node-provider.js +12 -6
  5. package/dist/src/api/utils.d.ts +1 -1
  6. package/dist/src/block/block.d.ts +28 -0
  7. package/dist/src/block/block.js +131 -0
  8. package/dist/src/block/index.d.ts +1 -0
  9. package/dist/src/block/index.js +22 -0
  10. package/dist/src/codec/contract-output-codec.js +4 -4
  11. package/dist/src/codec/lockup-script-codec.js +2 -2
  12. package/dist/src/codec/method-codec.d.ts +3 -1
  13. package/dist/src/codec/method-codec.js +27 -2
  14. package/dist/src/codec/script-codec.d.ts +11 -6
  15. package/dist/src/codec/script-codec.js +13 -2
  16. package/dist/src/codec/transaction-codec.js +2 -2
  17. package/dist/src/codec/unlock-script-codec.d.ts +2 -2
  18. package/dist/src/codec/unsigned-tx-codec.d.ts +2 -2
  19. package/dist/src/contract/contract.d.ts +19 -10
  20. package/dist/src/contract/contract.js +103 -56
  21. package/dist/src/contract/events.d.ts +1 -2
  22. package/dist/src/contract/events.js +28 -14
  23. package/dist/src/index.d.ts +1 -0
  24. package/dist/src/index.js +1 -0
  25. package/dist/src/signer/tx-builder.js +4 -4
  26. package/dist/src/transaction/status.js +28 -4
  27. package/dist/src/utils/address.js +29 -16
  28. package/dist/src/utils/exchange.js +25 -15
  29. package/dist/src/utils/number.d.ts +1 -1
  30. package/dist/src/utils/sign.js +6 -6
  31. package/dist/src/utils/subscription.d.ts +4 -4
  32. package/dist/src/utils/subscription.js +1 -1
  33. package/package.json +3 -3
  34. package/src/api/node-provider.ts +8 -1
  35. package/src/api/utils.ts +1 -1
  36. package/src/block/block.ts +139 -0
  37. package/src/block/index.ts +19 -0
  38. package/src/codec/contract-output-codec.ts +1 -1
  39. package/src/codec/lockup-script-codec.ts +3 -3
  40. package/src/codec/method-codec.ts +41 -3
  41. package/src/codec/script-codec.ts +23 -5
  42. package/src/codec/transaction-codec.ts +1 -1
  43. package/src/codec/unlock-script-codec.ts +2 -2
  44. package/src/codec/unsigned-tx-codec.ts +2 -2
  45. package/src/contract/contract.ts +139 -78
  46. package/src/contract/events.ts +6 -18
  47. package/src/index.ts +1 -0
  48. package/src/signer/tx-builder.ts +2 -2
  49. package/src/transaction/status.ts +4 -4
  50. package/src/utils/address.ts +15 -2
  51. package/src/utils/exchange.ts +32 -10
  52. package/src/utils/number.ts +1 -1
  53. package/src/utils/sign.ts +1 -1
  54. package/src/utils/subscription.ts +4 -4
  55. package/std/fungible_token_interface.ral +1 -0
  56. package/std/nft_collection_interface.ral +1 -0
  57. package/std/nft_collection_with_royalty_interface.ral +1 -0
  58. package/std/nft_interface.ral +1 -0
@@ -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.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;
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,
@@ -1322,27 +1368,35 @@ async function testMethod(factory, methodName, params) {
1322
1368
  }
1323
1369
  exports.testMethod = testMethod;
1324
1370
  class RalphMap {
1325
- constructor(parentContract, parentInstance, mapName) {
1371
+ constructor(parentContract, parentContractId, mapName) {
1326
1372
  this.parentContract = parentContract;
1327
- this.parentInstance = parentInstance;
1373
+ this.parentContractId = parentContractId;
1328
1374
  this.mapName = mapName;
1375
+ this.groupIndex = (0, utils_1.groupOfAddress)((0, utils_1.addressFromContractId)(parentContractId));
1329
1376
  }
1330
1377
  async get(key) {
1331
- return getMapItem(this.parentContract, this.parentInstance, this.mapName, key);
1378
+ return getMapItem(this.parentContract, this.parentContractId, this.groupIndex, this.mapName, key);
1332
1379
  }
1333
1380
  async contains(key) {
1334
1381
  return this.get(key).then((v) => v !== undefined);
1335
1382
  }
1383
+ toJSON() {
1384
+ return {
1385
+ parentContractId: this.parentContractId,
1386
+ mapName: this.mapName,
1387
+ groupIndex: this.groupIndex
1388
+ };
1389
+ }
1336
1390
  }
1337
1391
  exports.RalphMap = RalphMap;
1338
- async function getMapItem(parentContract, parentInstance, mapName, key) {
1392
+ async function getMapItem(parentContract, parentContractId, groupIndex, mapName, key) {
1339
1393
  const index = parentContract.mapsSig?.names.findIndex((name) => name === mapName);
1340
1394
  const mapType = index === undefined ? undefined : parentContract.mapsSig?.types[`${index}`];
1341
1395
  if (mapType === undefined) {
1342
1396
  throw new Error(`Map ${mapName} does not exist in contract ${parentContract.name}`);
1343
1397
  }
1344
1398
  const [keyType, valueType] = ralph.parseMapType(mapType);
1345
- const mapItemContractId = calcWrapperContractId(parentInstance.contractId, index, key, keyType, parentInstance.groupIndex);
1399
+ const mapItemContractId = calcWrapperContractId(parentContractId, index, key, keyType, groupIndex);
1346
1400
  const mapItemAddress = (0, utils_1.addressFromContractId)(mapItemContractId);
1347
1401
  try {
1348
1402
  const state = await (0, global_1.getCurrentNodeProvider)().contracts.getContractsAddressState(mapItemAddress);
@@ -1562,10 +1616,3 @@ const getContractIdFromUnsignedTx = async (nodeProvider, unsignedTx) => {
1562
1616
  exports.getContractIdFromUnsignedTx = getContractIdFromUnsignedTx;
1563
1617
  // This function only works in the simple case where a single non-subcontract is created in the tx
1564
1618
  exports.getTokenIdFromUnsignedTx = exports.getContractIdFromUnsignedTx;
1565
- function tryGetCallResult(result) {
1566
- if (result.type === 'CallContractFailed') {
1567
- throw new Error(`Failed to call contract, error: ${result.error}`);
1568
- }
1569
- return result;
1570
- }
1571
- 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;
@@ -28,6 +28,9 @@ const blakejs_1 = __importDefault(require("blakejs"));
28
28
  const bs58_1 = __importDefault(require("./bs58"));
29
29
  const djb2_1 = __importDefault(require("./djb2"));
30
30
  const utils_1 = require("./utils");
31
+ const lockup_script_codec_1 = require("../codec/lockup-script-codec");
32
+ const buffer_1 = require("buffer/");
33
+ const codec_1 = require("../codec");
31
34
  const ec = new elliptic_1.ec('secp256k1');
32
35
  var AddressType;
33
36
  (function (AddressType) {
@@ -52,9 +55,19 @@ function decodeAndValidateAddress(address) {
52
55
  throw new Error('Address is empty');
53
56
  const addressType = decoded[0];
54
57
  if (addressType === AddressType.P2MPKH) {
55
- // [1, n, ...hashes, m]
56
- if ((decoded.length - 3) % 32 === 0)
57
- return decoded;
58
+ let multisig;
59
+ try {
60
+ multisig = lockup_script_codec_1.lockupScriptCodec.decode(buffer_1.Buffer.from(decoded)).script;
61
+ }
62
+ catch (_) {
63
+ throw new Error(`Invalid multisig address: ${address}`);
64
+ }
65
+ const n = multisig.publicKeyHashes.value.length;
66
+ const m = codec_1.compactSignedIntCodec.toI32(multisig.m);
67
+ if (n < m) {
68
+ throw new Error(`Invalid multisig address, n: ${n}, m: ${m}`);
69
+ }
70
+ return decoded;
58
71
  }
59
72
  else if (addressType === AddressType.P2PKH || addressType === AddressType.P2SH || addressType === AddressType.P2C) {
60
73
  // [type, ...hash]
@@ -150,27 +163,27 @@ exports.publicKeyFromPrivateKey = publicKeyFromPrivateKey;
150
163
  function addressFromPublicKey(publicKey, _keyType) {
151
164
  const keyType = _keyType ?? 'default';
152
165
  if (keyType === 'default') {
153
- const addressType = Buffer.from([AddressType.P2PKH]);
154
- const hash = Buffer.from(blakejs_1.default.blake2b(Buffer.from(publicKey, 'hex'), undefined, 32));
155
- const bytes = Buffer.concat([addressType, hash]);
166
+ const addressType = buffer_1.Buffer.from([AddressType.P2PKH]);
167
+ const hash = buffer_1.Buffer.from(blakejs_1.default.blake2b(buffer_1.Buffer.from(publicKey, 'hex'), undefined, 32));
168
+ const bytes = buffer_1.Buffer.concat([addressType, hash]);
156
169
  return bs58_1.default.encode(bytes);
157
170
  }
158
171
  else {
159
- const lockupScript = Buffer.from(`0101000000000458144020${publicKey}8685`, 'hex');
172
+ const lockupScript = buffer_1.Buffer.from(`0101000000000458144020${publicKey}8685`, 'hex');
160
173
  return addressFromScript(lockupScript);
161
174
  }
162
175
  }
163
176
  exports.addressFromPublicKey = addressFromPublicKey;
164
177
  function addressFromScript(script) {
165
178
  const scriptHash = blakejs_1.default.blake2b(script, undefined, 32);
166
- const addressType = Buffer.from([AddressType.P2SH]);
167
- return bs58_1.default.encode(Buffer.concat([addressType, scriptHash]));
179
+ const addressType = buffer_1.Buffer.from([AddressType.P2SH]);
180
+ return bs58_1.default.encode(buffer_1.Buffer.concat([addressType, scriptHash]));
168
181
  }
169
182
  exports.addressFromScript = addressFromScript;
170
183
  function addressFromContractId(contractId) {
171
- const addressType = Buffer.from([AddressType.P2C]);
172
- const hash = Buffer.from((0, utils_1.hexToBinUnsafe)(contractId));
173
- const bytes = Buffer.concat([addressType, hash]);
184
+ const addressType = buffer_1.Buffer.from([AddressType.P2C]);
185
+ const hash = buffer_1.Buffer.from((0, utils_1.hexToBinUnsafe)(contractId));
186
+ const bytes = buffer_1.Buffer.concat([addressType, hash]);
174
187
  return bs58_1.default.encode(bytes);
175
188
  }
176
189
  exports.addressFromContractId = addressFromContractId;
@@ -181,7 +194,7 @@ function addressFromTokenId(tokenId) {
181
194
  exports.addressFromTokenId = addressFromTokenId;
182
195
  function contractIdFromTx(txId, outputIndex) {
183
196
  const txIdBin = (0, utils_1.hexToBinUnsafe)(txId);
184
- const data = Buffer.concat([txIdBin, Buffer.from([outputIndex])]);
197
+ const data = buffer_1.Buffer.concat([txIdBin, buffer_1.Buffer.from([outputIndex])]);
185
198
  const hash = blakejs_1.default.blake2b(data, undefined, 32);
186
199
  return (0, utils_1.binToHex)(hash);
187
200
  }
@@ -190,10 +203,10 @@ function subContractId(parentContractId, pathInHex, group) {
190
203
  if (group < 0 || group >= constants_1.TOTAL_NUMBER_OF_GROUPS) {
191
204
  throw new Error(`Invalid group ${group}`);
192
205
  }
193
- const data = Buffer.concat([(0, utils_1.hexToBinUnsafe)(parentContractId), (0, utils_1.hexToBinUnsafe)(pathInHex)]);
194
- const bytes = Buffer.concat([
206
+ const data = buffer_1.Buffer.concat([(0, utils_1.hexToBinUnsafe)(parentContractId), (0, utils_1.hexToBinUnsafe)(pathInHex)]);
207
+ const bytes = buffer_1.Buffer.concat([
195
208
  blakejs_1.default.blake2b(blakejs_1.default.blake2b(data, undefined, 32), undefined, 32).slice(0, -1),
196
- Buffer.from([group])
209
+ buffer_1.Buffer.from([group])
197
210
  ]);
198
211
  return (0, utils_1.binToHex)(bytes);
199
212
  }