@alephium/web3 0.1.0 → 0.2.0-test.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 (43) hide show
  1. package/contracts/{add.ral → add/add.ral} +1 -1
  2. package/contracts/{greeter.ral → greeter/greeter.ral} +0 -0
  3. package/contracts/{greeter_interface.ral → greeter/greeter_interface.ral} +0 -0
  4. package/contracts/greeter_main.ral +1 -1
  5. package/contracts/main.ral +1 -1
  6. package/contracts/{sub.ral → sub/sub.ral} +0 -0
  7. package/dist/alephium-web3.min.js +1 -1
  8. package/dist/alephium-web3.min.js.map +1 -1
  9. package/dist/src/api/api-alephium.d.ts +2 -0
  10. package/dist/src/contract/contract.d.ts +18 -10
  11. package/dist/src/contract/contract.js +95 -56
  12. package/dist/src/contract/events.d.ts +7 -25
  13. package/dist/src/contract/events.js +18 -31
  14. package/dist/src/index.d.ts +1 -0
  15. package/dist/src/index.js +1 -0
  16. package/dist/src/transaction/index.d.ts +2 -0
  17. package/dist/src/transaction/index.js +31 -0
  18. package/dist/src/{utils/transaction.d.ts → transaction/sign-verify.d.ts} +0 -0
  19. package/dist/src/{utils/transaction.js → transaction/sign-verify.js} +1 -1
  20. package/dist/src/transaction/status.d.ts +10 -0
  21. package/dist/src/transaction/status.js +48 -0
  22. package/dist/src/utils/index.d.ts +1 -1
  23. package/dist/src/utils/index.js +1 -1
  24. package/dist/src/utils/subscription.d.ts +24 -0
  25. package/dist/src/utils/subscription.js +52 -0
  26. package/dist/src/utils/utils.d.ts +2 -0
  27. package/dist/src/utils/utils.js +9 -1
  28. package/package.json +1 -1
  29. package/src/api/api-alephium.ts +2 -0
  30. package/src/contract/contract.ts +112 -66
  31. package/src/contract/events.ts +21 -48
  32. package/src/index.ts +1 -0
  33. package/src/transaction/index.ts +20 -0
  34. package/src/{utils/transaction.test.ts → transaction/sign-verify.test.ts} +1 -1
  35. package/src/{utils/transaction.ts → transaction/sign-verify.ts} +1 -1
  36. package/src/transaction/status.ts +58 -0
  37. package/src/utils/index.ts +1 -1
  38. package/src/utils/subscription.ts +72 -0
  39. package/src/utils/utils.test.ts +2 -1
  40. package/src/utils/utils.ts +8 -0
  41. package/test/contract.test.ts +24 -7
  42. package/test/events.test.ts +18 -19
  43. package/test/transaction.test.ts +72 -0
@@ -63,6 +63,8 @@ export interface Balance {
63
63
  lockedBalance: string;
64
64
  /** @format x.x ALPH */
65
65
  lockedBalanceHint: string;
66
+ tokenBalances?: Token[];
67
+ lockedTokenBalances?: Token[];
66
68
  /** @format int32 */
67
69
  utxoNum: number;
68
70
  warning?: string;
@@ -1,6 +1,13 @@
1
1
  import { NodeProvider } from '../api';
2
2
  import { node } from '../api';
3
3
  import { SignDeployContractTxParams, SignExecuteScriptTxParams, SignerWithNodeProvider } from '../signer';
4
+ declare class SourceFile {
5
+ readonly dirs: string[];
6
+ readonly dirPath: string;
7
+ readonly contractPath: string;
8
+ readonly artifactPath: string;
9
+ constructor(dirs: string[], fileName: string);
10
+ }
4
11
  export declare abstract class Common {
5
12
  readonly sourceCodeSha256: string;
6
13
  readonly functions: node.FunctionSig[];
@@ -13,16 +20,15 @@ export declare abstract class Common {
13
20
  protected static _getArtifactFromCache(codeHash: string): Contract | Script | undefined;
14
21
  protected static _putArtifactToCache(contract: Contract): void;
15
22
  constructor(sourceCodeSha256: string, functions: node.FunctionSig[]);
16
- protected static _contractPath(fileName: string): string;
17
- protected static _artifactPath(fileName: string): string;
18
23
  protected static _artifactsFolder(): string;
19
- protected static _handleImports(contractStr: string, importsCache: string[]): Promise<string>;
20
- protected static _loadContractStr(fileName: string, importsCache: string[], validate: (fileName: string) => void): Promise<string>;
24
+ static getSourceFile(path: string, _dirs: string[]): SourceFile;
25
+ protected static _handleImports(pathes: string[], contractStr: string, importsCache: string[]): Promise<string>;
26
+ protected static _loadContractStr(sourceFile: SourceFile, importsCache: string[], validate: (code: string) => void): Promise<string>;
21
27
  static checkFileNameExtension(fileName: string): void;
22
28
  protected static _from<T extends {
23
29
  sourceCodeSha256: string;
24
- }>(provider: NodeProvider, fileName: string, loadContractStr: (fileName: string, importsCache: string[]) => Promise<string>, compile: (provider: NodeProvider, fileName: string, contractStr: string, contractHash: string) => Promise<T>): Promise<T>;
25
- protected _saveToFile(fileName: string): Promise<void>;
30
+ }>(provider: NodeProvider, sourceFile: SourceFile, loadContractStr: (sourceFile: SourceFile, importsCache: string[]) => Promise<string>, compile: (provider: NodeProvider, sourceFile: SourceFile, contractStr: string, contractHash: string) => Promise<T>): Promise<T>;
31
+ protected _saveToFile(sourceFile: SourceFile): Promise<void>;
26
32
  abstract buildByteCodeToDeploy(initialFields?: Fields): string;
27
33
  }
28
34
  export declare class Contract extends Common {
@@ -33,10 +39,11 @@ export declare class Contract extends Common {
33
39
  constructor(sourceCodeSha256: string, bytecode: string, codeHash: string, fieldsSig: node.FieldsSig, eventsSig: node.EventSig[], functions: node.FunctionSig[]);
34
40
  static checkCodeType(fileName: string, contractStr: string): void;
35
41
  private static loadContractStr;
36
- static fromSource(provider: NodeProvider, fileName: string): Promise<Contract>;
42
+ static fromSource(provider: NodeProvider, path: string): Promise<Contract>;
37
43
  private static compile;
38
44
  static fromJson(artifact: any): Contract;
39
- static fromArtifactFile(fileName: string): Promise<Contract>;
45
+ static fromArtifactFile(path: string): Promise<Contract>;
46
+ fetchState(provider: NodeProvider, address: string, group: number): Promise<ContractState>;
40
47
  toString(): string;
41
48
  toState(fields: Fields, asset: Asset, address?: string): ContractState;
42
49
  static randomAddress(): string;
@@ -65,10 +72,10 @@ export declare class Script extends Common {
65
72
  constructor(sourceCodeSha256: string, bytecodeTemplate: string, fieldsSig: node.FieldsSig, functions: node.FunctionSig[]);
66
73
  static checkCodeType(fileName: string, contractStr: string): void;
67
74
  private static loadContractStr;
68
- static fromSource(provider: NodeProvider, fileName: string): Promise<Script>;
75
+ static fromSource(provider: NodeProvider, path: string): Promise<Script>;
69
76
  private static compile;
70
77
  static fromJson(artifact: any): Script;
71
- static fromArtifactFile(fileName: string): Promise<Script>;
78
+ static fromArtifactFile(path: string): Promise<Script>;
72
79
  toString(): string;
73
80
  paramsForDeployment(params: BuildExecuteScriptTx): Promise<SignExecuteScriptTxParams>;
74
81
  transactionForDeployment(signer: SignerWithNodeProvider, params: Omit<BuildExecuteScriptTx, 'signerAddress'>): Promise<BuildScriptTxResult>;
@@ -180,3 +187,4 @@ export interface BuildScriptTxResult {
180
187
  unsignedTx: string;
181
188
  txId: string;
182
189
  }
190
+ export {};
@@ -47,6 +47,20 @@ const fs_1 = __importDefault(require("fs"));
47
47
  const fs_2 = require("fs");
48
48
  const ralph = __importStar(require("./ralph"));
49
49
  const utils_1 = require("../utils");
50
+ class SourceFile {
51
+ constructor(dirs, fileName) {
52
+ this.dirs = dirs;
53
+ this.dirPath = dirs.length === 0 ? '' : dirs.join('/') + '/';
54
+ if (fileName.endsWith('.json')) {
55
+ this.contractPath = './contracts/' + this.dirPath + fileName.slice(0, -5);
56
+ this.artifactPath = './artifacts/' + this.dirPath + fileName;
57
+ }
58
+ else {
59
+ this.contractPath = './contracts/' + this.dirPath + fileName;
60
+ this.artifactPath = './artifacts/' + this.dirPath + fileName + '.json';
61
+ }
62
+ }
63
+ }
50
64
  class Common {
51
65
  constructor(sourceCodeSha256, functions) {
52
66
  this.sourceCodeSha256 = sourceCodeSha256;
@@ -64,72 +78,85 @@ class Common {
64
78
  this._artifactCache.set(contract.codeHash, contract);
65
79
  }
66
80
  }
67
- static _contractPath(fileName) {
68
- if (fileName.endsWith('.json')) {
69
- return `./contracts/${fileName.slice(0, -5)}`;
70
- }
71
- else {
72
- return `./contracts/${fileName}`;
73
- }
74
- }
75
- static _artifactPath(fileName) {
76
- if (fileName.endsWith('.json')) {
77
- return `./artifacts/${fileName}`;
78
- }
79
- else {
80
- return `./artifacts/${fileName}.json`;
81
- }
82
- }
83
81
  static _artifactsFolder() {
84
82
  return './artifacts/';
85
83
  }
86
- static async _handleImports(contractStr, importsCache) {
84
+ static getSourceFile(path, _dirs) {
85
+ const parts = path.split('/');
86
+ const dirs = Array.from(_dirs);
87
+ if (parts.length === 1) {
88
+ return new SourceFile(dirs, path);
89
+ }
90
+ parts.slice(0, parts.length - 1).forEach((part) => {
91
+ switch (part) {
92
+ case '.': {
93
+ break;
94
+ }
95
+ case '..': {
96
+ if (dirs.length === 0) {
97
+ throw new Error('Invalid file path: ' + path);
98
+ }
99
+ dirs.pop();
100
+ break;
101
+ }
102
+ default: {
103
+ dirs.push(part);
104
+ }
105
+ }
106
+ });
107
+ return new SourceFile(dirs, parts[parts.length - 1]);
108
+ }
109
+ static async _handleImports(pathes, contractStr, importsCache) {
87
110
  const localImportsCache = [];
88
111
  let result = contractStr.replace(Common.importRegex, (match) => {
89
112
  localImportsCache.push(match);
90
113
  return '';
91
114
  });
92
115
  for (const myImport of localImportsCache) {
93
- const fileName = myImport.slice(8, -1);
94
- if (!importsCache.includes(fileName)) {
95
- importsCache.push(fileName);
96
- const importContractStr = await Common._loadContractStr(fileName, importsCache, (code) => Contract.checkCodeType(fileName, code));
116
+ const relativePath = myImport.slice(8, -1);
117
+ const importSourceFile = this.getSourceFile(relativePath, pathes);
118
+ if (!importsCache.includes(importSourceFile.contractPath)) {
119
+ importsCache.push(importSourceFile.contractPath);
120
+ const importContractStr = await Common._loadContractStr(importSourceFile, importsCache, (code) => Contract.checkCodeType(importSourceFile.contractPath, code));
97
121
  result = result.concat('\n', importContractStr);
98
122
  }
99
123
  }
100
124
  return result;
101
125
  }
102
- static async _loadContractStr(fileName, importsCache, validate) {
103
- const contractPath = this._contractPath(fileName);
126
+ static async _loadContractStr(sourceFile, importsCache, validate) {
127
+ const contractPath = sourceFile.contractPath;
104
128
  const contractBuffer = await fs_2.promises.readFile(contractPath);
105
129
  const contractStr = contractBuffer.toString();
106
130
  validate(contractStr);
107
- return Common._handleImports(contractStr, importsCache);
131
+ return Common._handleImports(sourceFile.dirs, contractStr, importsCache);
108
132
  }
109
133
  static checkFileNameExtension(fileName) {
110
134
  if (!fileName.endsWith('.ral')) {
111
135
  throw new Error('Smart contract file name should end with ".ral"');
112
136
  }
113
137
  }
114
- static async _from(provider, fileName, loadContractStr, compile) {
115
- Common.checkFileNameExtension(fileName);
116
- const contractStr = await loadContractStr(fileName, []);
138
+ static async _from(provider, sourceFile, loadContractStr, compile) {
139
+ Common.checkFileNameExtension(sourceFile.contractPath);
140
+ const contractStr = await loadContractStr(sourceFile, []);
117
141
  const contractHash = cryptojs.SHA256(contractStr).toString();
118
142
  const existingContract = this._getArtifactFromCache(contractHash);
119
143
  if (typeof existingContract !== 'undefined') {
120
144
  return existingContract;
121
145
  }
122
146
  else {
123
- return compile(provider, fileName, contractStr, contractHash);
147
+ return compile(provider, sourceFile, contractStr, contractHash);
124
148
  }
125
149
  }
126
- _saveToFile(fileName) {
127
- const artifactPath = Common._artifactPath(fileName);
128
- return fs_2.promises.writeFile(artifactPath, this.toString());
150
+ _saveToFile(sourceFile) {
151
+ const folder = Common._artifactsFolder() + sourceFile.dirPath;
152
+ if (!fs_1.default.existsSync(folder)) {
153
+ fs_1.default.mkdirSync(folder, { recursive: true });
154
+ }
155
+ return fs_2.promises.writeFile(sourceFile.artifactPath, this.toString());
129
156
  }
130
157
  }
131
158
  exports.Common = Common;
132
- Common.importRegex = new RegExp('^import "[a-z][a-z_0-9]*.ral"', 'mg');
159
+ Common.importRegex = new RegExp('^import "([^"/]+/(([^"]+)/)?)?[a-z][a-z_0-9]*.ral"', 'mg');
133
160
  Common.contractRegex = new RegExp('^TxContract [A-Z][a-zA-Z0-9]*', 'mg');
134
161
  Common.interfaceRegex = new RegExp('^Interface [A-Z][a-zA-Z0-9]* \\{', 'mg');
135
162
  Common.scriptRegex = new RegExp('^TxScript [A-Z][a-zA-Z0-9]*', 'mg');
@@ -145,35 +172,40 @@ class Contract extends Common {
145
172
  }
146
173
  static checkCodeType(fileName, contractStr) {
147
174
  const interfaceMatches = contractStr.match(Contract.interfaceRegex);
148
- if (interfaceMatches) {
149
- return;
150
- }
151
175
  const contractMatches = contractStr.match(Contract.contractRegex);
152
- if (contractMatches === null) {
176
+ if (interfaceMatches === null && contractMatches === null) {
153
177
  throw new Error(`No contract found in: ${fileName}`);
154
178
  }
155
- else if (contractMatches.length > 1) {
156
- throw new Error(`Multiple contracts in: ${fileName}`);
179
+ if (interfaceMatches && contractMatches) {
180
+ throw new Error(`Multiple contracts and interfaces in: ${fileName}`);
157
181
  }
158
- else {
159
- return;
182
+ if (interfaceMatches === null) {
183
+ if (contractMatches !== null && contractMatches.length > 1) {
184
+ throw new Error(`Multiple contracts in: ${fileName}`);
185
+ }
186
+ }
187
+ if (contractMatches === null) {
188
+ if (interfaceMatches !== null && interfaceMatches.length > 1) {
189
+ throw new Error(`Multiple interfaces in: ${fileName}`);
190
+ }
160
191
  }
161
192
  }
162
- static async loadContractStr(fileName, importsCache) {
163
- return Common._loadContractStr(fileName, importsCache, (code) => Contract.checkCodeType(fileName, code));
193
+ static async loadContractStr(sourceFile) {
194
+ return Common._loadContractStr(sourceFile, [], (code) => Contract.checkCodeType(sourceFile.contractPath, code));
164
195
  }
165
- static async fromSource(provider, fileName) {
196
+ static async fromSource(provider, path) {
166
197
  if (!fs_1.default.existsSync(Common._artifactsFolder())) {
167
198
  fs_1.default.mkdirSync(Common._artifactsFolder(), { recursive: true });
168
199
  }
169
- const contract = await Common._from(provider, fileName, (fileName, importCaches) => Contract.loadContractStr(fileName, importCaches), Contract.compile);
200
+ const sourceFile = this.getSourceFile(path, []);
201
+ const contract = await Common._from(provider, sourceFile, (sourceFile) => Contract.loadContractStr(sourceFile), Contract.compile);
170
202
  this._putArtifactToCache(contract);
171
203
  return contract;
172
204
  }
173
- static async compile(provider, fileName, contractStr, contractHash) {
205
+ static async compile(provider, sourceFile, contractStr, contractHash) {
174
206
  const compiled = await provider.contracts.postContractsCompileContract({ code: contractStr });
175
207
  const artifact = new Contract(contractHash, compiled.bytecode, compiled.codeHash, compiled.fields, compiled.events, compiled.functions);
176
- await artifact._saveToFile(fileName);
208
+ await artifact._saveToFile(sourceFile);
177
209
  return artifact;
178
210
  }
179
211
  // TODO: safely parse json
@@ -191,12 +223,17 @@ class Contract extends Common {
191
223
  return contract;
192
224
  }
193
225
  // support both 'code.ral' and 'code.ral.json'
194
- static async fromArtifactFile(fileName) {
195
- const artifactPath = Contract._artifactPath(fileName);
226
+ static async fromArtifactFile(path) {
227
+ const sourceFile = this.getSourceFile(path, []);
228
+ const artifactPath = sourceFile.artifactPath;
196
229
  const content = await fs_2.promises.readFile(artifactPath);
197
230
  const artifact = JSON.parse(content.toString());
198
231
  return Contract.fromJson(artifact);
199
232
  }
233
+ async fetchState(provider, address, group) {
234
+ const state = await provider.contracts.getContractsAddressState(address, { group: group });
235
+ return this.fromApiContractState(state);
236
+ }
200
237
  toString() {
201
238
  return JSON.stringify({
202
239
  sourceCodeSha256: this.sourceCodeSha256,
@@ -415,16 +452,17 @@ class Script extends Common {
415
452
  return;
416
453
  }
417
454
  }
418
- static async loadContractStr(fileName, importsCache) {
419
- return Common._loadContractStr(fileName, importsCache, (code) => Script.checkCodeType(fileName, code));
455
+ static async loadContractStr(sourceFile) {
456
+ return Common._loadContractStr(sourceFile, [], (code) => Script.checkCodeType(sourceFile.contractPath, code));
420
457
  }
421
- static async fromSource(provider, fileName) {
422
- return Common._from(provider, fileName, (fileName, importsCache) => Script.loadContractStr(fileName, importsCache), Script.compile);
458
+ static async fromSource(provider, path) {
459
+ const sourceFile = this.getSourceFile(path, []);
460
+ return Common._from(provider, sourceFile, (sourceFile) => Script.loadContractStr(sourceFile), Script.compile);
423
461
  }
424
- static async compile(provider, fileName, scriptStr, contractHash) {
462
+ static async compile(provider, sourceFile, scriptStr, contractHash) {
425
463
  const compiled = await provider.contracts.postContractsCompileScript({ code: scriptStr });
426
464
  const artifact = new Script(contractHash, compiled.bytecodeTemplate, compiled.fields, compiled.functions);
427
- await artifact._saveToFile(fileName);
465
+ await artifact._saveToFile(sourceFile);
428
466
  return artifact;
429
467
  }
430
468
  // TODO: safely parse json
@@ -437,8 +475,9 @@ class Script extends Common {
437
475
  }
438
476
  return new Script(artifact.sourceCodeSha256, artifact.bytecodeTemplate, artifact.fieldsSig, artifact.functions);
439
477
  }
440
- static async fromArtifactFile(fileName) {
441
- const artifactPath = Common._artifactPath(fileName);
478
+ static async fromArtifactFile(path) {
479
+ const sourceFile = this.getSourceFile(path, []);
480
+ const artifactPath = sourceFile.artifactPath;
442
481
  const content = await fs_2.promises.readFile(artifactPath);
443
482
  const artifact = JSON.parse(content.toString());
444
483
  return this.fromJson(artifact);
@@ -1,29 +1,11 @@
1
- import { node } from '../api';
2
- import { NodeProvider } from '../api';
3
- declare type EventCallback = (event: node.ContractEvent) => Promise<void>;
4
- declare type ErrorCallback = (error: any, subscription: Subscription) => Promise<void>;
5
- export interface SubscribeOptions {
6
- provider: NodeProvider;
7
- contractAddress: string;
8
- fromCount?: number;
9
- pollingInterval: number;
10
- eventCallback: EventCallback;
11
- errorCallback: ErrorCallback;
12
- }
13
- export declare class Subscription {
14
- provider: NodeProvider;
1
+ import { ContractEvent } from '../api/api-alephium';
2
+ import { Subscription, SubscribeOptions } from '../utils';
3
+ export declare class EventSubscription extends Subscription<ContractEvent> {
15
4
  readonly contractAddress: string;
16
- pollingInterval: number;
17
5
  private fromCount;
18
- private eventCallback;
19
- private errorCallback;
20
- private task;
21
- private cancelled;
22
- private eventEmitter;
23
- constructor(options: SubscribeOptions);
24
- unsubscribe(): void;
6
+ constructor(options: SubscribeOptions<ContractEvent>, contractAddress: string, fromCount?: number);
7
+ startPolling(): void;
25
8
  currentEventCount(): number;
26
- private fetchEvents;
9
+ polling(): Promise<void>;
27
10
  }
28
- export declare function subscribe(options: SubscribeOptions): Subscription;
29
- export {};
11
+ export declare function subscribeToEvents(options: SubscribeOptions<ContractEvent>, contractAddress: string, fromCount?: number): EventSubscription;
@@ -16,39 +16,26 @@ 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 __importDefault = (this && this.__importDefault) || function (mod) {
20
- return (mod && mod.__esModule) ? mod : { "default": mod };
21
- };
22
19
  Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.subscribe = exports.Subscription = void 0;
24
- const eventemitter3_1 = __importDefault(require("eventemitter3"));
25
- class Subscription {
26
- constructor(options) {
27
- this.provider = options.provider;
28
- this.contractAddress = options.contractAddress;
29
- this.fromCount = typeof options.fromCount === 'undefined' ? 0 : options.fromCount;
30
- this.pollingInterval = options.pollingInterval;
31
- this.eventCallback = options.eventCallback;
32
- this.errorCallback = options.errorCallback;
33
- this.task = undefined;
34
- this.cancelled = false;
35
- this.eventEmitter = new eventemitter3_1.default();
20
+ exports.subscribeToEvents = exports.EventSubscription = void 0;
21
+ const utils_1 = require("../utils");
22
+ class EventSubscription extends utils_1.Subscription {
23
+ constructor(options, contractAddress, fromCount) {
24
+ super(options);
25
+ this.contractAddress = contractAddress;
26
+ this.fromCount = typeof fromCount === 'undefined' ? 0 : fromCount;
27
+ this.startPolling();
28
+ }
29
+ startPolling() {
36
30
  this.eventEmitter.on('tick', async () => {
37
- await this.fetchEvents();
31
+ await this.polling();
38
32
  });
39
33
  this.eventEmitter.emit('tick');
40
34
  }
41
- unsubscribe() {
42
- this.eventEmitter.removeAllListeners();
43
- this.cancelled = true;
44
- if (typeof this.task !== 'undefined') {
45
- clearTimeout(this.task);
46
- }
47
- }
48
35
  currentEventCount() {
49
36
  return this.fromCount;
50
37
  }
51
- async fetchEvents() {
38
+ async polling() {
52
39
  try {
53
40
  const events = await this.provider.events.getEventsContractContractaddress(this.contractAddress, {
54
41
  start: this.fromCount
@@ -60,18 +47,18 @@ class Subscription {
60
47
  this.task = setTimeout(() => this.eventEmitter.emit('tick'), this.pollingInterval);
61
48
  return;
62
49
  }
63
- const promises = events.events.map((event) => this.eventCallback(event));
50
+ const promises = events.events.map((event) => this.messageCallback(event));
64
51
  await Promise.all(promises);
65
52
  this.fromCount = events.nextStart;
66
- await this.fetchEvents();
53
+ await this.polling();
67
54
  }
68
55
  catch (err) {
69
56
  await this.errorCallback(err, this);
70
57
  }
71
58
  }
72
59
  }
73
- exports.Subscription = Subscription;
74
- function subscribe(options) {
75
- return new Subscription(options);
60
+ exports.EventSubscription = EventSubscription;
61
+ function subscribeToEvents(options, contractAddress, fromCount) {
62
+ return new EventSubscription(options, contractAddress, fromCount);
76
63
  }
77
- exports.subscribe = subscribe;
64
+ exports.subscribeToEvents = subscribeToEvents;
@@ -2,4 +2,5 @@ export * from './api';
2
2
  export * from './contract';
3
3
  export * from './signer';
4
4
  export * from './utils';
5
+ export * from './transaction';
5
6
  export * from './constants';
package/dist/src/index.js CHANGED
@@ -31,4 +31,5 @@ __exportStar(require("./api"), exports);
31
31
  __exportStar(require("./contract"), exports);
32
32
  __exportStar(require("./signer"), exports);
33
33
  __exportStar(require("./utils"), exports);
34
+ __exportStar(require("./transaction"), exports);
34
35
  __exportStar(require("./constants"), exports);
@@ -0,0 +1,2 @@
1
+ export * from './sign-verify';
2
+ export * from './status';
@@ -0,0 +1,31 @@
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
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
22
+ }) : (function(o, m, k, k2) {
23
+ if (k2 === undefined) k2 = k;
24
+ o[k2] = m[k];
25
+ }));
26
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
27
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ __exportStar(require("./sign-verify"), exports);
31
+ __exportStar(require("./status"), exports);
@@ -38,7 +38,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.transactionVerifySignature = exports.transactionSign = void 0;
40
40
  const elliptic_1 = require("elliptic");
41
- const utils = __importStar(require("./utils"));
41
+ const utils = __importStar(require("../utils"));
42
42
  const ec = new elliptic_1.ec('secp256k1');
43
43
  function transactionSign(txHash, privateKey) {
44
44
  const keyPair = ec.keyFromPrivate(privateKey);
@@ -0,0 +1,10 @@
1
+ import { TxStatus } from '../api/api-alephium';
2
+ import { Subscription, SubscribeOptions } from '../utils';
3
+ export declare class TxStatusSubscription extends Subscription<TxStatus> {
4
+ readonly txId: string;
5
+ readonly fromGroup?: number;
6
+ readonly toGroup?: number;
7
+ constructor(options: SubscribeOptions<TxStatus>, txId: string, fromGroup?: number, toGroup?: number);
8
+ polling(): Promise<void>;
9
+ }
10
+ export declare function subscribeToTxStatus(options: SubscribeOptions<TxStatus>, txId: string, fromGroup?: number, toGroup?: number): TxStatusSubscription;
@@ -0,0 +1,48 @@
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.subscribeToTxStatus = exports.TxStatusSubscription = void 0;
21
+ const utils_1 = require("../utils");
22
+ class TxStatusSubscription extends utils_1.Subscription {
23
+ constructor(options, txId, fromGroup, toGroup) {
24
+ super(options);
25
+ this.txId = txId;
26
+ this.fromGroup = fromGroup;
27
+ this.toGroup = toGroup;
28
+ this.startPolling();
29
+ }
30
+ async polling() {
31
+ try {
32
+ const txStatus = await this.provider.transactions.getTransactionsStatus({
33
+ txId: this.txId,
34
+ fromGroup: this.fromGroup,
35
+ toGroup: this.toGroup
36
+ });
37
+ await this.messageCallback(txStatus);
38
+ }
39
+ catch (err) {
40
+ await this.errorCallback(err, this);
41
+ }
42
+ }
43
+ }
44
+ exports.TxStatusSubscription = TxStatusSubscription;
45
+ function subscribeToTxStatus(options, txId, fromGroup, toGroup) {
46
+ return new TxStatusSubscription(options, txId, fromGroup, toGroup);
47
+ }
48
+ exports.subscribeToTxStatus = subscribeToTxStatus;
@@ -2,5 +2,5 @@ export * from './address';
2
2
  export * from './bs58';
3
3
  export * from './djb2';
4
4
  export * from './password-crypto';
5
- export * from './transaction';
6
5
  export * from './utils';
6
+ export * from './subscription';
@@ -31,5 +31,5 @@ __exportStar(require("./address"), exports);
31
31
  __exportStar(require("./bs58"), exports);
32
32
  __exportStar(require("./djb2"), exports);
33
33
  __exportStar(require("./password-crypto"), exports);
34
- __exportStar(require("./transaction"), exports);
35
34
  __exportStar(require("./utils"), exports);
35
+ __exportStar(require("./subscription"), exports);
@@ -0,0 +1,24 @@
1
+ import EventEmitter from 'eventemitter3';
2
+ import { NodeProvider } from '../api';
3
+ declare type MessageCallback<Message> = (message: Message) => Promise<void>;
4
+ declare type ErrorCallback<Message> = (error: any, subscription: Subscription<Message>) => Promise<void>;
5
+ export interface SubscribeOptions<Message> {
6
+ provider: NodeProvider;
7
+ pollingInterval: number;
8
+ messageCallback: MessageCallback<Message>;
9
+ errorCallback: ErrorCallback<Message>;
10
+ }
11
+ export declare abstract class Subscription<Message> {
12
+ provider: NodeProvider;
13
+ pollingInterval: number;
14
+ protected messageCallback: MessageCallback<Message>;
15
+ protected errorCallback: ErrorCallback<Message>;
16
+ protected task: ReturnType<typeof setTimeout> | undefined;
17
+ protected eventEmitter: EventEmitter;
18
+ protected cancelled: boolean;
19
+ constructor(options: SubscribeOptions<Message>);
20
+ startPolling(): void;
21
+ unsubscribe(): void;
22
+ abstract polling(): Promise<void>;
23
+ }
24
+ export {};