@alephium/web3 0.40.0 → 0.42.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 (68) 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 +23 -101
  20. package/dist/src/contract/contract.js +52 -538
  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/index.d.ts +1 -0
  27. package/dist/src/transaction/index.js +1 -0
  28. package/dist/src/transaction/status.js +28 -4
  29. package/dist/src/transaction/utils.d.ts +2 -0
  30. package/dist/src/transaction/utils.js +34 -0
  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 +3 -3
  38. package/src/api/node-provider.ts +8 -1
  39. package/src/api/utils.ts +1 -1
  40. package/src/block/block.ts +139 -0
  41. package/src/block/index.ts +19 -0
  42. package/src/codec/contract-output-codec.ts +1 -1
  43. package/src/codec/lockup-script-codec.ts +3 -3
  44. package/src/codec/method-codec.ts +41 -3
  45. package/src/codec/script-codec.ts +23 -5
  46. package/src/codec/transaction-codec.ts +1 -1
  47. package/src/codec/unlock-script-codec.ts +2 -2
  48. package/src/codec/unsigned-tx-codec.ts +2 -2
  49. package/src/contract/contract.ts +72 -779
  50. package/src/contract/events.ts +6 -18
  51. package/src/index.ts +1 -0
  52. package/src/signer/tx-builder.ts +2 -2
  53. package/src/transaction/index.ts +1 -0
  54. package/src/transaction/status.ts +4 -4
  55. package/src/transaction/utils.ts +38 -0
  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
  65. package/webpack.config.js +0 -1
  66. package/dist/src/utils/error.d.ts +0 -15
  67. package/dist/src/utils/error.js +0 -66
  68. package/src/utils/error.ts +0 -77
@@ -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) {
@@ -1,2 +1,3 @@
1
1
  export * from './status';
2
2
  export * from './sign-verify';
3
+ export * from './utils';
@@ -33,3 +33,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
33
33
  Object.defineProperty(exports, "__esModule", { value: true });
34
34
  __exportStar(require("./status"), exports);
35
35
  __exportStar(require("./sign-verify"), exports);
36
+ __exportStar(require("./utils"), exports);
@@ -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;
@@ -0,0 +1,2 @@
1
+ import { node } from '../api';
2
+ export declare function waitForTxConfirmation(txId: string, confirmations: number, requestInterval: number): Promise<node.Confirmed>;
@@ -0,0 +1,34 @@
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.waitForTxConfirmation = void 0;
21
+ const global_1 = require("../global");
22
+ function isConfirmed(txStatus) {
23
+ return txStatus.type === 'Confirmed';
24
+ }
25
+ async function waitForTxConfirmation(txId, confirmations, requestInterval) {
26
+ const provider = (0, global_1.getCurrentNodeProvider)();
27
+ const status = await provider.transactions.getTransactionsStatus({ txId: txId });
28
+ if (isConfirmed(status) && status.chainConfirmations >= confirmations) {
29
+ return status;
30
+ }
31
+ await new Promise((r) => setTimeout(r, requestInterval));
32
+ return waitForTxConfirmation(txId, confirmations, requestInterval);
33
+ }
34
+ exports.waitForTxConfirmation = waitForTxConfirmation;
@@ -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
  }
@@ -18,11 +18,14 @@ 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.getAddressFromUnlockScript = exports.getSenderAddress = exports.getALPHDepositInfo = exports.isALPHTransferTx = exports.validateExchangeAddress = void 0;
21
- const __1 = require("..");
21
+ const utils_1 = require("../utils");
22
+ const unlock_script_codec_1 = require("../codec/unlock-script-codec");
23
+ const buffer_1 = require("buffer/");
24
+ const script_codec_1 = require("../codec/script-codec");
22
25
  function validateExchangeAddress(address) {
23
26
  let decoded;
24
27
  try {
25
- decoded = __1.bs58.decode(address);
28
+ decoded = utils_1.bs58.decode(address);
26
29
  }
27
30
  catch (_) {
28
31
  throw new Error('Invalid base58 string');
@@ -30,7 +33,7 @@ function validateExchangeAddress(address) {
30
33
  if (decoded.length === 0)
31
34
  throw new Error('Address is empty');
32
35
  const addressType = decoded[0];
33
- if (addressType !== __1.AddressType.P2PKH && addressType !== __1.AddressType.P2SH) {
36
+ if (addressType !== utils_1.AddressType.P2PKH && addressType !== utils_1.AddressType.P2SH) {
34
37
  throw new Error('Invalid address type');
35
38
  }
36
39
  if (decoded.length !== 33) {
@@ -83,27 +86,34 @@ var UnlockScriptType;
83
86
  UnlockScriptType[UnlockScriptType["P2SH"] = 2] = "P2SH";
84
87
  })(UnlockScriptType || (UnlockScriptType = {}));
85
88
  function getAddressFromUnlockScript(unlockScript) {
86
- const decoded = (0, __1.hexToBinUnsafe)(unlockScript);
89
+ if (!(0, utils_1.isHexString)(unlockScript)) {
90
+ throw new Error(`Invalid unlock script ${unlockScript}, expected a hex string`);
91
+ }
92
+ const decoded = (0, utils_1.hexToBinUnsafe)(unlockScript);
87
93
  if (decoded.length === 0)
88
94
  throw new Error('UnlockScript is empty');
89
95
  const unlockScriptType = decoded[0];
90
96
  const unlockScriptBody = decoded.slice(1);
91
97
  if (unlockScriptType === UnlockScriptType.P2PKH) {
92
- return (0, __1.addressFromPublicKey)((0, __1.binToHex)(unlockScriptBody));
98
+ if (unlockScriptBody.length !== 33) {
99
+ throw new Error(`Invalid p2pkh unlock script: ${unlockScript}`);
100
+ }
101
+ return (0, utils_1.addressFromPublicKey)((0, utils_1.binToHex)(unlockScriptBody));
93
102
  }
94
- else if (unlockScriptType === UnlockScriptType.P2MPKH) {
103
+ if (unlockScriptType === UnlockScriptType.P2MPKH) {
95
104
  throw new Error('Naive multi-sig address is not supported for exchanges as it will be replaced by P2SH');
96
105
  }
97
- else if (unlockScriptType === UnlockScriptType.P2SH) {
98
- // FIXEME: for now we assume that the params is empty, so we need to
99
- // remove the last byte from the `unlockScriptBody`, we can decode
100
- // the unlock script once the codec PR is merged
101
- const script = unlockScriptBody.slice(0, -1);
102
- return (0, __1.addressFromScript)(script);
103
- }
104
- else {
105
- throw new Error('Invalid unlock script type');
106
+ if (unlockScriptType === UnlockScriptType.P2SH) {
107
+ let p2sh;
108
+ try {
109
+ p2sh = unlock_script_codec_1.unlockScriptCodec.decode(buffer_1.Buffer.from(decoded)).script;
110
+ }
111
+ catch (_) {
112
+ throw new Error(`Invalid p2sh unlock script: ${unlockScript}`);
113
+ }
114
+ return (0, utils_1.addressFromScript)(script_codec_1.scriptCodec.encode(p2sh.script));
106
115
  }
116
+ throw new Error('Invalid unlock script type');
107
117
  }
108
118
  exports.getAddressFromUnlockScript = getAddressFromUnlockScript;
109
119
  function checkALPHOutput(tx) {
@@ -1,4 +1,4 @@
1
- import { Number256 } from '..';
1
+ import { Number256 } from '../api/types';
2
2
  export declare const isNumeric: (numToCheck: any) => boolean;
3
3
  export interface IPrettifyNumberConfig {
4
4
  minDecimalPlaces: number;
@@ -42,7 +42,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
42
42
  Object.defineProperty(exports, "__esModule", { value: true });
43
43
  exports.verifySignature = exports.sign = void 0;
44
44
  const elliptic_1 = require("elliptic");
45
- const __1 = require("..");
45
+ const utils_1 = require("../utils");
46
46
  const necc = __importStar(require("@noble/secp256k1"));
47
47
  const crypto_1 = require("crypto");
48
48
  const ec = new elliptic_1.ec('secp256k1');
@@ -63,11 +63,11 @@ function sign(hash, privateKey, _keyType) {
63
63
  if (keyType === 'default') {
64
64
  const key = ec.keyFromPrivate(privateKey);
65
65
  const signature = key.sign(hash);
66
- return (0, __1.encodeSignature)(signature);
66
+ return (0, utils_1.encodeSignature)(signature);
67
67
  }
68
68
  else {
69
- const signature = necc.schnorr.signSync((0, __1.hexToBinUnsafe)(hash), (0, __1.hexToBinUnsafe)(privateKey));
70
- return (0, __1.binToHex)(signature);
69
+ const signature = necc.schnorr.signSync((0, utils_1.hexToBinUnsafe)(hash), (0, utils_1.hexToBinUnsafe)(privateKey));
70
+ return (0, utils_1.binToHex)(signature);
71
71
  }
72
72
  }
73
73
  exports.sign = sign;
@@ -76,10 +76,10 @@ function verifySignature(hash, publicKey, signature, _keyType) {
76
76
  try {
77
77
  if (keyType === 'default') {
78
78
  const key = ec.keyFromPublic(publicKey, 'hex');
79
- return key.verify(hash, (0, __1.signatureDecode)(ec, signature));
79
+ return key.verify(hash, (0, utils_1.signatureDecode)(ec, signature));
80
80
  }
81
81
  else {
82
- return necc.schnorr.verifySync((0, __1.hexToBinUnsafe)(signature), (0, __1.hexToBinUnsafe)(hash), (0, __1.hexToBinUnsafe)(publicKey));
82
+ return necc.schnorr.verifySync((0, utils_1.hexToBinUnsafe)(signature), (0, utils_1.hexToBinUnsafe)(hash), (0, utils_1.hexToBinUnsafe)(publicKey));
83
83
  }
84
84
  }
85
85
  catch (error) {
@@ -1,6 +1,6 @@
1
1
  import EventEmitter from 'eventemitter3';
2
- type MessageCallback<Message> = (message: Message) => Promise<void>;
3
- type ErrorCallback<Message> = (error: any, subscription: Subscription<Message>) => Promise<void>;
2
+ type MessageCallback<Message> = (message: Message) => Promise<void> | void;
3
+ type ErrorCallback<Message> = (error: any, subscription: Subscription<Message>) => Promise<void> | void;
4
4
  export interface SubscribeOptions<Message> {
5
5
  pollingInterval: number;
6
6
  messageCallback: MessageCallback<Message>;
@@ -14,9 +14,9 @@ export declare abstract class Subscription<Message> {
14
14
  protected eventEmitter: EventEmitter;
15
15
  protected cancelled: boolean;
16
16
  constructor(options: SubscribeOptions<Message>);
17
- startPolling(): void;
17
+ subscribe(): void;
18
18
  unsubscribe(): void;
19
19
  isCancelled(): boolean;
20
- abstract polling(): Promise<void>;
20
+ protected abstract polling(): Promise<void>;
21
21
  }
22
22
  export {};
@@ -31,7 +31,7 @@ class Subscription {
31
31
  this.cancelled = false;
32
32
  this.eventEmitter = new eventemitter3_1.default();
33
33
  }
34
- startPolling() {
34
+ subscribe() {
35
35
  this.eventEmitter.on('tick', async () => {
36
36
  await this.polling();
37
37
  if (!this.cancelled) {
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@alephium/web3",
3
- "version": "0.40.0",
3
+ "version": "0.42.0",
4
4
  "description": "A JS/TS library to interact with the Alephium platform",
5
5
  "license": "GPL",
6
6
  "main": "dist/src/index.js",
7
7
  "browser": "dist/alephium-web3.min.js",
8
8
  "types": "dist/src/index.d.ts",
9
9
  "exports": {
10
- ".": "./dist/src/index.js",
11
- "./test": "./dist/src/test/index.js"
10
+ "node": "./dist/src/index.js",
11
+ "default": "./dist/alephium-web3.min.js"
12
12
  },
13
13
  "typesVersions": {
14
14
  "*": {
@@ -28,7 +28,6 @@ import {
28
28
  requestWithLog
29
29
  } from './types'
30
30
  import { Api as NodeApi, CallContractFailed, CallContractSucceeded } from './api-alephium'
31
- import { tryGetCallResult } from '../contract'
32
31
  import {
33
32
  HexString,
34
33
  addressFromContractId,
@@ -38,6 +37,7 @@ import {
38
37
  isHexString,
39
38
  toNonNegativeBigInt
40
39
  } from '../utils'
40
+ import * as node from '../api/api-alephium'
41
41
 
42
42
  function initializeNodeApi(baseUrl: string, apiKey?: string, customFetch?: typeof fetch): NodeApi<string> {
43
43
  const nodeApi = new NodeApi<string>({
@@ -253,3 +253,10 @@ export class NodeProvider implements NodeProviderApis {
253
253
  }
254
254
  }
255
255
  }
256
+
257
+ export function tryGetCallResult(result: node.CallContractResult): node.CallContractSucceeded {
258
+ if (result.type === 'CallContractFailed') {
259
+ throw new Error(`Failed to call contract, error: ${(result as node.CallContractFailed).error}`)
260
+ }
261
+ return result as node.CallContractSucceeded
262
+ }
package/src/api/utils.ts CHANGED
@@ -17,7 +17,7 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.
17
17
  */
18
18
 
19
19
  import 'cross-fetch/polyfill'
20
- import { node } from '..'
20
+ import * as node from '../api/api-alephium'
21
21
 
22
22
  export function convertHttpResponse<T>(response: { status: number; data: T; error?: { detail: string } }): T {
23
23
  if (response.error) {