@alephium/web3 1.8.0 → 1.8.2

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.
@@ -16,6 +16,29 @@ 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
  var __importDefault = (this && this.__importDefault) || function (mod) {
20
43
  return (mod && mod.__esModule) ? mod : { "default": mod };
21
44
  };
@@ -25,11 +48,12 @@ const elliptic_1 = require("elliptic");
25
48
  const bn_js_1 = __importDefault(require("bn.js"));
26
49
  const constants_1 = require("../constants");
27
50
  const blakejs_1 = __importDefault(require("blakejs"));
28
- const bs58_1 = __importDefault(require("../utils/bs58"));
51
+ const bs58_1 = __importStar(require("../utils/bs58"));
29
52
  const utils_1 = require("../utils");
30
53
  const lockup_script_codec_1 = require("../codec/lockup-script-codec");
31
54
  const codec_1 = require("../codec");
32
55
  const djb2_1 = __importDefault(require("../utils/djb2"));
56
+ const error_1 = require("../error");
33
57
  const ec = new elliptic_1.ec('secp256k1');
34
58
  const PublicKeyHashSize = 32;
35
59
  var AddressType;
@@ -54,13 +78,7 @@ function isValidAddress(address) {
54
78
  }
55
79
  exports.isValidAddress = isValidAddress;
56
80
  function decodeAndValidateAddress(address) {
57
- let decoded;
58
- try {
59
- decoded = bs58_1.default.decode(address);
60
- }
61
- catch (_) {
62
- throw new Error('Invalid base58 string');
63
- }
81
+ const decoded = (0, bs58_1.base58ToBytes)(address);
64
82
  if (decoded.length === 0)
65
83
  throw new Error('Address is empty');
66
84
  const addressType = decoded[0];
@@ -69,8 +87,8 @@ function decodeAndValidateAddress(address) {
69
87
  try {
70
88
  multisig = lockup_script_codec_1.lockupScriptCodec.decode(decoded).value;
71
89
  }
72
- catch (_) {
73
- throw new Error(`Invalid multisig address: ${address}`);
90
+ catch (error) {
91
+ throw new error_1.TraceableError(`Invalid multisig address: ${address}`, error);
74
92
  }
75
93
  const n = multisig.publicKeyHashes.length;
76
94
  const m = multisig.m;
@@ -141,7 +159,7 @@ function tokenIdFromAddress(address) {
141
159
  }
142
160
  exports.tokenIdFromAddress = tokenIdFromAddress;
143
161
  function idFromAddress(address) {
144
- const decoded = bs58_1.default.decode(address);
162
+ const decoded = (0, bs58_1.base58ToBytes)(address);
145
163
  if (decoded.length == 0)
146
164
  throw new Error('Address string is empty');
147
165
  const addressType = decoded[0];
@@ -20,6 +20,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
20
20
  exports.StdInterfaceIds = exports.request = exports.requestWithLog = exports.forwardRequests = exports.getDefaultPrimitiveValue = exports.decodeArrayType = exports.fromApiPrimitiveVal = exports.toApiVal = exports.toApiArray = exports.toApiAddress = exports.toApiByteVec = exports.fromApiNumber256 = exports.toApiNumber256Optional = exports.toApiNumber256 = exports.toApiBoolean = exports.fromApiTokens = exports.fromApiToken = exports.toApiTokens = exports.toApiToken = exports.PrimitiveTypes = void 0;
21
21
  const constants_1 = require("../constants");
22
22
  const debug_1 = require("../debug");
23
+ const error_1 = require("../error");
23
24
  const utils_1 = require("../utils");
24
25
  exports.PrimitiveTypes = ['U256', 'I256', 'Bool', 'ByteVec', 'Address'];
25
26
  utils_1.assertType;
@@ -59,8 +60,8 @@ function toApiNumber256(v) {
59
60
  return v;
60
61
  }
61
62
  }
62
- catch (_) {
63
- throw new Error(`Invalid value: ${v}, expected a 256 bit number`);
63
+ catch (error) {
64
+ throw new error_1.TraceableError(`Invalid value: ${v}, expected a 256 bit number`, error);
64
65
  }
65
66
  }
66
67
  throw new Error(`Invalid value: ${v}, expected a 256 bit number`);
@@ -82,14 +83,9 @@ function toApiByteVec(v) {
82
83
  return v;
83
84
  if ((0, utils_1.isBase58)(v)) {
84
85
  // try to convert from address to contract id
85
- try {
86
- const address = utils_1.bs58.decode(v);
87
- if (address.length == 33 && address[0] == 3) {
88
- return (0, utils_1.binToHex)(address.slice(1));
89
- }
90
- }
91
- catch (_) {
92
- throw new Error(`Invalid hex-string: ${v}`);
86
+ const address = (0, utils_1.base58ToBytes)(v);
87
+ if (address.length === 33 && address[0] === 3) {
88
+ return (0, utils_1.binToHex)(address.slice(1));
93
89
  }
94
90
  }
95
91
  throw new Error(`Invalid hex-string: ${v}`);
@@ -97,13 +93,10 @@ function toApiByteVec(v) {
97
93
  exports.toApiByteVec = toApiByteVec;
98
94
  function toApiAddress(v) {
99
95
  if (typeof v === 'string') {
100
- try {
101
- utils_1.bs58.decode(v);
96
+ if ((0, utils_1.isBase58)(v)) {
102
97
  return v;
103
98
  }
104
- catch (error) {
105
- throw new Error(`Invalid base58 string: ${v}`);
106
- }
99
+ throw new Error(`Invalid base58 string: ${v}`);
107
100
  }
108
101
  else {
109
102
  throw new Error(`Invalid value: ${v}, expected a base58 string`);
@@ -200,7 +193,7 @@ async function call(args, handler) {
200
193
  if (debugModeEnabled) {
201
194
  console.error(`[ERROR] ${path} ${method} `, error);
202
195
  }
203
- throw error;
196
+ throw new error_1.TraceableError(`Failed to request ${method}`, error);
204
197
  }
205
198
  }
206
199
  function forwardRequests(api, handler) {
@@ -78,6 +78,7 @@ export declare class Contract extends Artifact {
78
78
  static ContractCreatedEvent: EventSig;
79
79
  static ContractDestroyedEventIndex: number;
80
80
  static ContractDestroyedEvent: EventSig;
81
+ static DebugEventIndex: number;
81
82
  static fromApiEvent(event: node.ContractEventByTxId, codeHash: string | undefined, txId: string, getContractByCodeHash: (codeHash: string) => Contract): ContractEvent;
82
83
  fromApiTestContractResult(methodName: string, result: node.TestContractResult, txId: string, getContractByCodeHash: (codeHash: string) => Contract): TestContractResult<unknown>;
83
84
  txParamsForDeployment<P extends Fields>(signer: SignerProvider, params: DeployContractParams<P>): Promise<SignDeployContractTxParams>;
@@ -274,6 +275,11 @@ export declare function extractMapsFromApiResult(selfAddress: string, params: Op
274
275
  maps: Record<string, Map<Val, Val>>;
275
276
  }[];
276
277
  export declare function testMethod<I extends ContractInstance, F extends Fields, A extends Arguments, R, M extends Record<string, Map<Val, Val>> = Record<string, Map<Val, Val>>>(factory: ContractFactory<I, F>, methodName: string, params: Optional<TestContractParams<F, A, M>, 'testArgs' | 'initialFields'>, getContractByCodeHash: (codeHash: string) => Contract): Promise<TestContractResult<R, M>>;
278
+ export declare function getDebugMessagesFromTx(txId: HexString, provider?: NodeProvider): Promise<{
279
+ contractAddress: string;
280
+ message: string;
281
+ }[]>;
282
+ export declare function printDebugMessagesFromTx(txId: HexString, provider?: NodeProvider): Promise<void>;
277
283
  export declare class RalphMap<K extends Val, V extends Val> {
278
284
  private readonly parentContract;
279
285
  private readonly parentContractId;
@@ -40,7 +40,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
40
40
  return result;
41
41
  };
42
42
  Object.defineProperty(exports, "__esModule", { value: true });
43
- exports.getTokenIdFromUnsignedTx = exports.getContractIdFromUnsignedTx = exports.getContractEventsCurrentCount = exports.multicallMethods = exports.signExecuteMethod = exports.callMethod = exports.subscribeContractEvents = exports.subscribeContractEvent = exports.decodeEvent = exports.subscribeContractDestroyedEvent = exports.subscribeContractCreatedEvent = exports.fetchContractState = exports.ContractInstance = exports.getMapItem = exports.RalphMap = exports.testMethod = exports.extractMapsFromApiResult = 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.Struct = exports.DEFAULT_COMPILER_OPTIONS = exports.DEFAULT_NODE_COMPILER_OPTIONS = exports.StdIdFieldName = void 0;
43
+ exports.getTokenIdFromUnsignedTx = exports.getContractIdFromUnsignedTx = exports.getContractEventsCurrentCount = exports.multicallMethods = exports.signExecuteMethod = exports.callMethod = exports.subscribeContractEvents = exports.subscribeContractEvent = exports.decodeEvent = exports.subscribeContractDestroyedEvent = exports.subscribeContractCreatedEvent = exports.fetchContractState = exports.ContractInstance = exports.getMapItem = exports.RalphMap = exports.printDebugMessagesFromTx = exports.getDebugMessagesFromTx = exports.testMethod = exports.extractMapsFromApiResult = 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.Struct = exports.DEFAULT_COMPILER_OPTIONS = exports.DEFAULT_NODE_COMPILER_OPTIONS = exports.StdIdFieldName = void 0;
44
44
  const fs_1 = require("fs");
45
45
  const api_1 = require("../api");
46
46
  const ralph = __importStar(require("./ralph"));
@@ -52,6 +52,7 @@ const constants_1 = require("../constants");
52
52
  const blake = __importStar(require("blakejs"));
53
53
  const debug_1 = require("../debug");
54
54
  const codec_1 = require("../codec");
55
+ const error_1 = require("../error");
55
56
  const crypto = new utils_1.WebCrypto();
56
57
  exports.StdIdFieldName = '__stdInterfaceId';
57
58
  exports.DEFAULT_NODE_COMPILER_OPTIONS = {
@@ -247,7 +248,7 @@ class Contract extends Artifact {
247
248
  printDebugMessages(funcName, messages) {
248
249
  if ((0, debug_1.isContractDebugMessageEnabled)() && messages.length != 0) {
249
250
  console.log(`Testing ${this.name}.${funcName}:`);
250
- messages.forEach((m) => console.log(`> Contract @ ${m.contractAddress} - ${m.message}`));
251
+ messages.forEach((m) => printDebugMessage(m));
251
252
  }
252
253
  }
253
254
  toApiFields(fields) {
@@ -391,7 +392,7 @@ class Contract extends Artifact {
391
392
  return ralph.buildContractByteCode(bytecode, initialFields, this.fieldsSig, this.structs);
392
393
  }
393
394
  catch (error) {
394
- throw new Error(`Failed to build bytecode for contract ${this.name}, error: ${error}`);
395
+ throw new error_1.TraceableError(`Failed to build bytecode for contract ${this.name}`, error);
395
396
  }
396
397
  }
397
398
  static fromApiEvents(events, addressToCodeHash, txId, getContractByCodeHash) {
@@ -437,6 +438,7 @@ Contract.ContractDestroyedEvent = {
437
438
  fieldNames: ['address'],
438
439
  fieldTypes: ['Address']
439
440
  };
441
+ Contract.DebugEventIndex = -3;
440
442
  function fromCallResult(callResult, txId, returnTypes, structs, getContractByCodeHash) {
441
443
  const rawReturn = fromApiArray(callResult.returns, returnTypes, structs);
442
444
  const returns = rawReturn.length === 0 ? null : rawReturn.length === 1 ? rawReturn[0] : rawReturn;
@@ -507,7 +509,7 @@ class Script extends Artifact {
507
509
  return ralph.buildScriptByteCode(this.bytecodeTemplate, initialFields, this.fieldsSig, this.structs);
508
510
  }
509
511
  catch (error) {
510
- throw new Error(`Failed to build bytecode for script ${this.name}, error: ${error}`);
512
+ throw new error_1.TraceableError(`Failed to build bytecode for script ${this.name}`, error);
511
513
  }
512
514
  }
513
515
  }
@@ -943,6 +945,39 @@ async function testMethod(factory, methodName, params, getContractByCodeHash) {
943
945
  };
944
946
  }
945
947
  exports.testMethod = testMethod;
948
+ function printDebugMessage(m) {
949
+ console.log(`> Contract @ ${m.contractAddress} - ${m.message}`);
950
+ }
951
+ async function getDebugMessagesFromTx(txId, provider) {
952
+ if ((0, utils_1.isHexString)(txId) && txId.length === 64) {
953
+ const nodeProvider = provider ?? (0, global_1.getCurrentNodeProvider)();
954
+ const events = await nodeProvider.events.getEventsTxIdTxid(txId);
955
+ return events.events
956
+ .filter((e) => e.eventIndex === Contract.DebugEventIndex)
957
+ .map((e) => {
958
+ if (e.fields.length === 1 && e.fields[0].type === 'ByteVec') {
959
+ return {
960
+ contractAddress: e.contractAddress,
961
+ message: (0, utils_1.hexToString)(e.fields[0].value)
962
+ };
963
+ }
964
+ else {
965
+ throw new Error(`Invalid debug log: ${JSON.stringify(e.fields)}`);
966
+ }
967
+ });
968
+ }
969
+ else {
970
+ throw new Error(`Invalid tx id: ${txId}`);
971
+ }
972
+ }
973
+ exports.getDebugMessagesFromTx = getDebugMessagesFromTx;
974
+ async function printDebugMessagesFromTx(txId, provider) {
975
+ const messages = await getDebugMessagesFromTx(txId, provider);
976
+ if (messages.length > 0) {
977
+ messages.forEach((m) => printDebugMessage(m));
978
+ }
979
+ }
980
+ exports.printDebugMessagesFromTx = printDebugMessagesFromTx;
946
981
  class RalphMap {
947
982
  constructor(parentContract, parentContractId, mapName) {
948
983
  this.parentContract = parentContract;
@@ -985,7 +1020,7 @@ async function getMapItem(parentContract, parentContractId, groupIndex, mapName,
985
1020
  // the map item contract does not exist
986
1021
  return undefined;
987
1022
  }
988
- throw error;
1023
+ throw new error_1.TraceableError(`Failed to get value from map ${mapName}, key: ${key}, parent contract id: ${parentContractId}`, error);
989
1024
  }
990
1025
  }
991
1026
  exports.getMapItem = getMapItem;
@@ -1169,7 +1204,11 @@ async function signExecuteMethod(contract, instance, methodName, params) {
1169
1204
  gasAmount: params.gasAmount,
1170
1205
  gasPrice: params.gasPrice
1171
1206
  };
1172
- return await signer.signAndSubmitExecuteScriptTx(signerParams);
1207
+ const result = await signer.signAndSubmitExecuteScriptTx(signerParams);
1208
+ if ((0, debug_1.isContractDebugMessageEnabled)() && (await contract.contract.isDevnet(signer))) {
1209
+ await printDebugMessagesFromTx(result.txId, signer.nodeProvider);
1210
+ }
1211
+ return result;
1173
1212
  }
1174
1213
  exports.signExecuteMethod = signExecuteMethod;
1175
1214
  function getBytecodeTemplate(methodIndex, methodUsePreapprovedAssets, functionSig, structs, attoAlphAmount, tokens) {
@@ -1363,7 +1402,7 @@ async function getContractEventsCurrentCount(contractAddress) {
1363
1402
  if (error instanceof Error && error.message.includes(`${contractAddress} not found`)) {
1364
1403
  return 0;
1365
1404
  }
1366
- throw error;
1405
+ throw new error_1.TraceableError(`Failed to get the event count for the contract ${contractAddress}`, error);
1367
1406
  });
1368
1407
  }
1369
1408
  exports.getContractEventsCurrentCount = getContractEventsCurrentCount;
@@ -22,6 +22,7 @@ const api_1 = require("../api");
22
22
  const utils_1 = require("../utils");
23
23
  const codec_1 = require("../codec");
24
24
  const codec_2 = require("../codec/codec");
25
+ const error_1 = require("../error");
25
26
  function encodeByteVec(hex) {
26
27
  if (!(0, utils_1.isHexString)(hex)) {
27
28
  throw Error(`Given value ${hex} is not a valid hex string`);
@@ -357,10 +358,7 @@ function _encodeField(fieldName, encodeFunc) {
357
358
  return encodeFunc();
358
359
  }
359
360
  catch (error) {
360
- if (error instanceof Error) {
361
- throw new Error(`Invalid ${fieldName}, error: ${error.message}`);
362
- }
363
- throw error;
361
+ throw new error_1.TraceableError(`Failed to encode the field ${fieldName}`, error);
364
362
  }
365
363
  }
366
364
  function encodeFields(fields) {
@@ -0,0 +1,4 @@
1
+ export declare class TraceableError extends Error {
2
+ trace: any | undefined;
3
+ constructor(message?: string, innerError?: any);
4
+ }
@@ -0,0 +1,36 @@
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.TraceableError = void 0;
21
+ class TraceableError extends Error {
22
+ constructor(message, innerError) {
23
+ const innerErrorMessage = innerError === undefined ? undefined : innerError instanceof Error ? innerError.message : `${innerError}`;
24
+ super(innerErrorMessage ? `${message}, error: ${innerErrorMessage}` : message);
25
+ this.trace = innerError;
26
+ const actualProto = new.target.prototype;
27
+ if (Object.setPrototypeOf) {
28
+ Object.setPrototypeOf(this, actualProto);
29
+ }
30
+ else {
31
+ const object = this;
32
+ object.__proto__ = actualProto;
33
+ }
34
+ }
35
+ }
36
+ exports.TraceableError = TraceableError;
@@ -22,14 +22,9 @@ const address_1 = require("../address");
22
22
  const utils_1 = require("../utils");
23
23
  const unlock_script_codec_1 = require("../codec/unlock-script-codec");
24
24
  const script_codec_1 = require("../codec/script-codec");
25
+ const error_1 = require("../error");
25
26
  function validateExchangeAddress(address) {
26
- let decoded;
27
- try {
28
- decoded = utils_1.bs58.decode(address);
29
- }
30
- catch (_) {
31
- throw new Error('Invalid base58 string');
32
- }
27
+ const decoded = (0, utils_1.base58ToBytes)(address);
33
28
  if (decoded.length === 0)
34
29
  throw new Error('Address is empty');
35
30
  const addressType = decoded[0];
@@ -108,8 +103,8 @@ function getAddressFromUnlockScript(unlockScript) {
108
103
  try {
109
104
  p2sh = unlock_script_codec_1.unlockScriptCodec.decode(decoded).value;
110
105
  }
111
- catch (_) {
112
- throw new Error(`Invalid p2sh unlock script: ${unlockScript}`);
106
+ catch (e) {
107
+ throw new error_1.TraceableError(`Invalid p2sh unlock script: ${unlockScript}`, e);
113
108
  }
114
109
  return (0, address_1.addressFromScript)(script_codec_1.scriptCodec.encode(p2sh.script));
115
110
  }
@@ -12,3 +12,4 @@ export * from './debug';
12
12
  export * from './block';
13
13
  export * from './address';
14
14
  export * from './exchange';
15
+ export * from './error';
package/dist/src/index.js CHANGED
@@ -61,3 +61,4 @@ __exportStar(require("./debug"), exports);
61
61
  __exportStar(require("./block"), exports);
62
62
  __exportStar(require("./address"), exports);
63
63
  __exportStar(require("./exchange"), exports);
64
+ __exportStar(require("./error"), exports);
@@ -21,6 +21,7 @@ exports.validateNFTBaseUri = exports.validateNFTCollectionUriMetaData = exports.
21
21
  // JSON Schema for the NFT metadata, which is pointed to by the value
22
22
  // returned from the `getTokenUri` method of the NFT contract
23
23
  require("cross-fetch/polyfill");
24
+ const error_1 = require("../error");
24
25
  exports.validNFTTokenUriMetaDataFields = ['name', 'description', 'image', 'attributes'];
25
26
  exports.validNFTTokenUriMetaDataAttributesFields = ['trait_type', 'value'];
26
27
  exports.validNFTUriMetaDataAttributeTypes = ['string', 'number', 'boolean'];
@@ -111,7 +112,7 @@ async function fetchNFTMetadata(nftBaseUri, index) {
111
112
  return await (await fetch(`${nftBaseUri}${index}`)).json();
112
113
  }
113
114
  catch (e) {
114
- throw new Error(`Error fetching NFT metadata from ${nftBaseUri}${index}: ${e}`);
115
+ throw new error_1.TraceableError(`Error fetching NFT metadata from ${nftBaseUri}${index}`, e);
115
116
  }
116
117
  }
117
118
  function isInteger(num) {
@@ -2,4 +2,5 @@
2
2
  import basex from 'base-x';
3
3
  export declare const bs58: basex.BaseConverter;
4
4
  export declare function isBase58(s: string): boolean;
5
+ export declare function base58ToBytes(s: string): Uint8Array;
5
6
  export default bs58;
@@ -20,9 +20,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
20
20
  return (mod && mod.__esModule) ? mod : { "default": mod };
21
21
  };
22
22
  Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.isBase58 = exports.bs58 = void 0;
23
+ exports.base58ToBytes = exports.isBase58 = exports.bs58 = void 0;
24
24
  /** This source is under MIT License and come originally from https://github.com/cryptocoinjs/bs58 **/
25
25
  const base_x_1 = __importDefault(require("base-x"));
26
+ const error_1 = require("../error");
26
27
  const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
27
28
  exports.bs58 = (0, base_x_1.default)(ALPHABET);
28
29
  function isBase58(s) {
@@ -37,4 +38,13 @@ function isBase58(s) {
37
38
  }
38
39
  }
39
40
  exports.isBase58 = isBase58;
41
+ function base58ToBytes(s) {
42
+ try {
43
+ return exports.bs58.decode(s);
44
+ }
45
+ catch (e) {
46
+ throw new error_1.TraceableError(`Invalid base58 string ${s}`, e);
47
+ }
48
+ }
49
+ exports.base58ToBytes = base58ToBytes;
40
50
  exports.default = exports.bs58;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alephium/web3",
3
- "version": "1.8.0",
3
+ "version": "1.8.2",
4
4
  "description": "A JS/TS library to interact with the Alephium platform",
5
5
  "license": "GPL",
6
6
  "main": "dist/src/index.js",
@@ -20,13 +20,14 @@ import { ec as EC } from 'elliptic'
20
20
  import BN from 'bn.js'
21
21
  import { TOTAL_NUMBER_OF_GROUPS } from '../constants'
22
22
  import blake from 'blakejs'
23
- import bs58 from '../utils/bs58'
23
+ import bs58, { base58ToBytes } from '../utils/bs58'
24
24
  import { binToHex, concatBytes, hexToBinUnsafe, isHexString, xorByte } from '../utils'
25
25
  import { KeyType } from '../signer'
26
26
  import { P2MPKH, lockupScriptCodec } from '../codec/lockup-script-codec'
27
27
  import { i32Codec } from '../codec'
28
28
  import { LockupScript } from '../codec/lockup-script-codec'
29
29
  import djb2 from '../utils/djb2'
30
+ import { TraceableError } from '../error'
30
31
 
31
32
  const ec = new EC('secp256k1')
32
33
  const PublicKeyHashSize = 32
@@ -52,21 +53,15 @@ export function isValidAddress(address: string): boolean {
52
53
  }
53
54
 
54
55
  function decodeAndValidateAddress(address: string): Uint8Array {
55
- let decoded: Uint8Array
56
- try {
57
- decoded = bs58.decode(address)
58
- } catch (_) {
59
- throw new Error('Invalid base58 string')
60
- }
61
-
56
+ const decoded = base58ToBytes(address)
62
57
  if (decoded.length === 0) throw new Error('Address is empty')
63
58
  const addressType = decoded[0]
64
59
  if (addressType === AddressType.P2MPKH) {
65
60
  let multisig: P2MPKH
66
61
  try {
67
62
  multisig = lockupScriptCodec.decode(decoded).value as P2MPKH
68
- } catch (_) {
69
- throw new Error(`Invalid multisig address: ${address}`)
63
+ } catch (error) {
64
+ throw new TraceableError(`Invalid multisig address: ${address}`, error)
70
65
  }
71
66
  const n = multisig.publicKeyHashes.length
72
67
  const m = multisig.m
@@ -137,8 +132,7 @@ export function tokenIdFromAddress(address: string): Uint8Array {
137
132
  }
138
133
 
139
134
  function idFromAddress(address: string): Uint8Array {
140
- const decoded = bs58.decode(address)
141
-
135
+ const decoded = base58ToBytes(address)
142
136
  if (decoded.length == 0) throw new Error('Address string is empty')
143
137
  const addressType = decoded[0]
144
138
  const addressBody = decoded.slice(1)
package/src/api/types.ts CHANGED
@@ -18,7 +18,8 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.
18
18
 
19
19
  import { ZERO_ADDRESS } from '../constants'
20
20
  import { isDebugModeEnabled } from '../debug'
21
- import { assertType, binToHex, bs58, Eq, isBase58, isHexString } from '../utils'
21
+ import { TraceableError } from '../error'
22
+ import { assertType, base58ToBytes, binToHex, bs58, Eq, isBase58, isHexString } from '../utils'
22
23
  import * as node from './api-alephium'
23
24
 
24
25
  export type Number256 = bigint | string
@@ -68,8 +69,8 @@ export function toApiNumber256(v: Val): string {
68
69
  if (BigInt(v).toString() === v) {
69
70
  return v
70
71
  }
71
- } catch (_) {
72
- throw new Error(`Invalid value: ${v}, expected a 256 bit number`)
72
+ } catch (error) {
73
+ throw new TraceableError(`Invalid value: ${v}, expected a 256 bit number`, error)
73
74
  }
74
75
  }
75
76
  throw new Error(`Invalid value: ${v}, expected a 256 bit number`)
@@ -90,13 +91,9 @@ export function toApiByteVec(v: Val): string {
90
91
  if (isHexString(v)) return v
91
92
  if (isBase58(v)) {
92
93
  // try to convert from address to contract id
93
- try {
94
- const address = bs58.decode(v)
95
- if (address.length == 33 && address[0] == 3) {
96
- return binToHex(address.slice(1))
97
- }
98
- } catch (_) {
99
- throw new Error(`Invalid hex-string: ${v}`)
94
+ const address = base58ToBytes(v)
95
+ if (address.length === 33 && address[0] === 3) {
96
+ return binToHex(address.slice(1))
100
97
  }
101
98
  }
102
99
  throw new Error(`Invalid hex-string: ${v}`)
@@ -104,12 +101,10 @@ export function toApiByteVec(v: Val): string {
104
101
 
105
102
  export function toApiAddress(v: Val): string {
106
103
  if (typeof v === 'string') {
107
- try {
108
- bs58.decode(v)
109
- return v as string
110
- } catch (error) {
111
- throw new Error(`Invalid base58 string: ${v}`)
104
+ if (isBase58(v)) {
105
+ return v
112
106
  }
107
+ throw new Error(`Invalid base58 string: ${v}`)
113
108
  } else {
114
109
  throw new Error(`Invalid value: ${v}, expected a base58 string`)
115
110
  }
@@ -201,7 +196,7 @@ async function call(args: ApiRequestArguments, handler: ApiRequestHandler): Prom
201
196
  if (debugModeEnabled) {
202
197
  console.error(`[ERROR] ${path} ${method} `, error)
203
198
  }
204
- throw error
199
+ throw new TraceableError(`Failed to request ${method}`, error)
205
200
  }
206
201
  }
207
202
 
@@ -26,7 +26,7 @@ import { FixedAssetOutput, Transaction as ApiTransaction } from '../api/api-alep
26
26
  import { binToHex, hexToBinUnsafe } from '../utils'
27
27
  import { ContractOutput as ApiContractOutput } from '../api/api-alephium'
28
28
  import { byteCodec, ObjectCodec } from './codec'
29
- import { Output, outputCodec, outputsCodec } from './output-codec'
29
+ import { Output, outputsCodec } from './output-codec'
30
30
 
31
31
  export interface Transaction {
32
32
  unsigned: UnsignedTx