@alephium/web3 0.9.0-rc.0 → 0.9.0-rc.1

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 (73) hide show
  1. package/dist/alephium-web3.min.js +3 -0
  2. package/dist/alephium-web3.min.js.LICENSE.txt +12 -0
  3. package/dist/alephium-web3.min.js.map +1 -0
  4. package/dist/scripts/check-versions.d.ts +1 -0
  5. package/dist/scripts/check-versions.js +39 -0
  6. package/dist/scripts/header.d.ts +0 -0
  7. package/dist/scripts/header.js +18 -0
  8. package/dist/src/api/api-alephium.d.ts +1717 -0
  9. package/dist/src/api/api-alephium.js +1284 -0
  10. package/dist/src/api/api-explorer.d.ts +923 -0
  11. package/dist/src/api/api-explorer.js +711 -0
  12. package/dist/src/api/explorer-provider.d.ts +20 -0
  13. package/dist/src/api/explorer-provider.js +69 -0
  14. package/dist/src/api/index.d.ts +6 -0
  15. package/dist/src/api/index.js +52 -0
  16. package/dist/src/api/node-provider.d.ts +38 -0
  17. package/dist/src/api/node-provider.js +99 -0
  18. package/dist/src/api/types.d.ts +38 -0
  19. package/dist/src/api/types.js +259 -0
  20. package/dist/src/api/utils.d.ts +12 -0
  21. package/dist/src/api/utils.js +59 -0
  22. package/dist/src/constants.d.ts +6 -0
  23. package/dist/src/constants.js +26 -0
  24. package/dist/src/contract/contract.d.ts +297 -0
  25. package/dist/src/contract/contract.js +1097 -0
  26. package/dist/src/contract/events.d.ts +11 -0
  27. package/dist/src/contract/events.js +65 -0
  28. package/dist/src/contract/index.d.ts +3 -0
  29. package/dist/src/contract/index.js +36 -0
  30. package/dist/src/contract/ralph.d.ts +13 -0
  31. package/dist/src/contract/ralph.js +397 -0
  32. package/dist/src/global.d.ts +7 -0
  33. package/dist/src/global.js +54 -0
  34. package/dist/src/index.d.ts +9 -0
  35. package/dist/src/index.js +58 -0
  36. package/dist/src/signer/index.d.ts +3 -0
  37. package/dist/src/signer/index.js +36 -0
  38. package/dist/src/signer/signer.d.ts +60 -0
  39. package/dist/src/signer/signer.js +236 -0
  40. package/dist/src/signer/tx-builder.d.ts +12 -0
  41. package/dist/src/signer/tx-builder.js +96 -0
  42. package/dist/src/signer/types.d.ts +115 -0
  43. package/dist/src/signer/types.js +30 -0
  44. package/dist/src/token/index.d.ts +1 -0
  45. package/dist/src/token/index.js +34 -0
  46. package/dist/src/token/nft.d.ts +10 -0
  47. package/dist/src/token/nft.js +19 -0
  48. package/dist/src/transaction/index.d.ts +2 -0
  49. package/dist/src/transaction/index.js +35 -0
  50. package/dist/src/transaction/sign-verify.d.ts +3 -0
  51. package/dist/src/transaction/sign-verify.js +52 -0
  52. package/dist/src/transaction/status.d.ts +11 -0
  53. package/dist/src/transaction/status.js +49 -0
  54. package/dist/src/utils/address.d.ts +1 -0
  55. package/dist/src/utils/address.js +42 -0
  56. package/dist/src/utils/bs58.d.ts +5 -0
  57. package/dist/src/utils/bs58.js +40 -0
  58. package/dist/src/utils/djb2.d.ts +1 -0
  59. package/dist/src/utils/djb2.js +27 -0
  60. package/dist/src/utils/index.d.ts +7 -0
  61. package/dist/src/utils/index.js +40 -0
  62. package/dist/src/utils/number.d.ts +18 -0
  63. package/dist/src/utils/number.fixture.d.ts +12 -0
  64. package/dist/src/utils/number.fixture.js +189 -0
  65. package/dist/src/utils/number.js +149 -0
  66. package/dist/src/utils/sign.d.ts +3 -0
  67. package/dist/src/utils/sign.js +89 -0
  68. package/dist/src/utils/subscription.d.ts +21 -0
  69. package/dist/src/utils/subscription.js +51 -0
  70. package/dist/src/utils/utils.d.ts +40 -0
  71. package/dist/src/utils/utils.js +244 -0
  72. package/package.json +1 -1
  73. package/LICENSE +0 -165
@@ -0,0 +1,149 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
20
+ return (mod && mod.__esModule) ? mod : { "default": mod };
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.number256ToBigint = exports.convertAlphAmountWithDecimals = exports.convertAmountWithDecimals = exports.prettifyNumber = exports.prettifyExactAmount = exports.prettifyTokenAmount = exports.prettifyAttoAlphAmount = exports.prettifyNumberConfig = exports.isNumeric = void 0;
24
+ // Credits:
25
+ // 1. https://github.com/argentlabs/argent-x/blob/e63affa7f28b27333dca4081a3dcd375bb2da40b/packages/extension/src/shared/utils/number.ts
26
+ // 2. https://github.com/ethers-io/ethers.js/blob/724881f34d428406488a1c9f9dbebe54b6edecda/src.ts/utils/fixednumber.ts
27
+ const bignumber_js_1 = __importDefault(require("bignumber.js"));
28
+ const isNumeric = (numToCheck) => !isNaN(parseFloat(numToCheck)) && isFinite(numToCheck);
29
+ exports.isNumeric = isNumeric;
30
+ exports.prettifyNumberConfig = {
31
+ ALPH: {
32
+ minDecimalPlaces: 2,
33
+ maxDecimalPlaces: 10,
34
+ minDecimalSignificantDigits: 2,
35
+ decimalPlacesWhenZero: 2
36
+ },
37
+ TOKEN: {
38
+ minDecimalPlaces: 4,
39
+ maxDecimalPlaces: 16,
40
+ minDecimalSignificantDigits: 2,
41
+ decimalPlacesWhenZero: 1
42
+ },
43
+ Exact: {
44
+ minDecimalPlaces: 18,
45
+ maxDecimalPlaces: 18,
46
+ minDecimalSignificantDigits: 0,
47
+ decimalPlacesWhenZero: 0
48
+ }
49
+ };
50
+ function prettifyAttoAlphAmount(amount) {
51
+ return prettifyNumber(amount, 18, exports.prettifyNumberConfig.ALPH);
52
+ }
53
+ exports.prettifyAttoAlphAmount = prettifyAttoAlphAmount;
54
+ function prettifyTokenAmount(amount, decimals) {
55
+ return prettifyNumber(amount, decimals, exports.prettifyNumberConfig.TOKEN);
56
+ }
57
+ exports.prettifyTokenAmount = prettifyTokenAmount;
58
+ function prettifyExactAmount(amount, decimals) {
59
+ return prettifyNumber(amount, decimals, exports.prettifyNumberConfig.Exact);
60
+ }
61
+ exports.prettifyExactAmount = prettifyExactAmount;
62
+ function prettifyNumber(amount, decimals, config) {
63
+ const number = toFixedNumber(number256ToBigint(amount), decimals);
64
+ if (!(0, exports.isNumeric)(number)) {
65
+ return undefined;
66
+ }
67
+ const numberBN = new bignumber_js_1.default(number);
68
+ let untrimmed;
69
+ if (numberBN.gte(1)) {
70
+ /** simplest case, formatting to minDecimalPlaces will look good */
71
+ untrimmed = numberBN.toFormat(config.minDecimalPlaces);
72
+ }
73
+ else {
74
+ /** now need to interrogate the appearance of decimal number < 1 */
75
+ /** longest case - max decimal places e.g. 0.0008923088123 -> 0.0008923088 */
76
+ const maxDecimalPlacesString = numberBN.toFormat(config.maxDecimalPlaces);
77
+ /** count the zeros, which will then allow us to know the final length with desired significant digits */
78
+ const decimalPart = maxDecimalPlacesString.split('.')[1];
79
+ const zeroMatches = decimalPart?.match(/^0+/);
80
+ const leadingZerosInDecimalPart = zeroMatches && zeroMatches.length ? zeroMatches[0].length : 0;
81
+ /** now we can re-format with leadingZerosInDecimalPart + maxDecimalSignificanDigits to give us the pretty version */
82
+ /** e.g. 0.0008923088123 -> 0.00089 */
83
+ const prettyDecimalPlaces = Math.max(leadingZerosInDecimalPart + config.minDecimalSignificantDigits, config.minDecimalPlaces);
84
+ untrimmed = numberBN.toFormat(prettyDecimalPlaces);
85
+ }
86
+ /** the untrimmed string may have trailing zeros, e.g. 0.0890 */
87
+ /** trim to a minimum specified by the config, e.g. we may want to display $0.00 or 0.0 ETH */
88
+ let trimmed = untrimmed.replace(/0+$/, '');
89
+ const minLength = 1 + untrimmed.indexOf('.') + config.decimalPlacesWhenZero;
90
+ if (trimmed.length < minLength) {
91
+ trimmed = untrimmed.substring(0, minLength);
92
+ }
93
+ if (trimmed[trimmed.length - 1] === '.') {
94
+ trimmed = trimmed.slice(0, -1);
95
+ }
96
+ return trimmed;
97
+ }
98
+ exports.prettifyNumber = prettifyNumber;
99
+ const BN_N1 = BigInt(-1);
100
+ const BN_0 = BigInt(0);
101
+ // Constant to pull zeros from for multipliers
102
+ const Zeros = '0000';
103
+ function toFixedNumber(val, decimals) {
104
+ let negative = '';
105
+ if (val < BN_0) {
106
+ negative = '-';
107
+ val *= BN_N1;
108
+ }
109
+ let str = val.toString();
110
+ // No decimal point for whole values
111
+ if (decimals === 0) {
112
+ return negative + str;
113
+ }
114
+ // Pad out to the whole component (including a whole digit)
115
+ while (str.length <= decimals) {
116
+ str = Zeros + str;
117
+ }
118
+ // Insert the decimal point
119
+ const index = str.length - decimals;
120
+ str = str.substring(0, index) + '.' + str.substring(index);
121
+ // Trim the whole component (leaving at least one 0)
122
+ while (str[0] === '0' && str[1] !== '.') {
123
+ str = str.substring(1);
124
+ }
125
+ // Trim the decimal component (leaving at least one 0)
126
+ while (str[str.length - 1] === '0' && str[str.length - 2] !== '.') {
127
+ str = str.substring(0, str.length - 1);
128
+ }
129
+ return negative + str;
130
+ }
131
+ function convertAmountWithDecimals(amount, decimals) {
132
+ try {
133
+ const result = new bignumber_js_1.default(amount).multipliedBy(Math.pow(10, decimals));
134
+ return BigInt(result.toFormat(0, { groupSeparator: '' }));
135
+ }
136
+ catch (e) {
137
+ return undefined;
138
+ }
139
+ }
140
+ exports.convertAmountWithDecimals = convertAmountWithDecimals;
141
+ // E.g. `1.23 ALPH` will be converted to `1230000000000000000`
142
+ function convertAlphAmountWithDecimals(amount) {
143
+ return convertAmountWithDecimals(amount, 18);
144
+ }
145
+ exports.convertAlphAmountWithDecimals = convertAlphAmountWithDecimals;
146
+ function number256ToBigint(number) {
147
+ return typeof number === 'string' ? BigInt(number) : number;
148
+ }
149
+ exports.number256ToBigint = number256ToBigint;
@@ -0,0 +1,3 @@
1
+ import { KeyType } from '../signer';
2
+ export declare function sign(hash: string, privateKey: string, _keyType?: KeyType): string;
3
+ export declare function verifySignature(hash: string, publicKey: string, signature: string, _keyType?: KeyType): boolean;
@@ -0,0 +1,89 @@
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
+ 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
+ };
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.verifySignature = exports.sign = void 0;
44
+ const elliptic_1 = require("elliptic");
45
+ const __1 = require("..");
46
+ const necc = __importStar(require("@noble/secp256k1"));
47
+ const crypto_1 = require("crypto");
48
+ const ec = new elliptic_1.ec('secp256k1');
49
+ necc.utils.sha256Sync = (...messages) => {
50
+ const sha256 = (0, crypto_1.createHash)('sha256');
51
+ for (const message of messages)
52
+ sha256.update(message);
53
+ return sha256.digest();
54
+ };
55
+ necc.utils.hmacSha256Sync = (key, ...messages) => {
56
+ const hash = (0, crypto_1.createHmac)('sha256', Buffer.from(key));
57
+ messages.forEach((m) => hash.update(m));
58
+ return Uint8Array.from(hash.digest());
59
+ };
60
+ // hash has to be 32 bytes
61
+ function sign(hash, privateKey, _keyType) {
62
+ const keyType = _keyType ?? 'default';
63
+ if (keyType === 'default') {
64
+ const key = ec.keyFromPrivate(privateKey);
65
+ const signature = key.sign(hash);
66
+ return (0, __1.encodeSignature)(signature);
67
+ }
68
+ else {
69
+ const signature = necc.schnorr.signSync((0, __1.hexToBinUnsafe)(hash), (0, __1.hexToBinUnsafe)(privateKey));
70
+ return (0, __1.binToHex)(signature);
71
+ }
72
+ }
73
+ exports.sign = sign;
74
+ function verifySignature(hash, publicKey, signature, _keyType) {
75
+ const keyType = _keyType ?? 'default';
76
+ try {
77
+ if (keyType === 'default') {
78
+ const key = ec.keyFromPublic(publicKey, 'hex');
79
+ return key.verify(hash, (0, __1.signatureDecode)(ec, signature));
80
+ }
81
+ else {
82
+ return necc.schnorr.verifySync((0, __1.hexToBinUnsafe)(signature), (0, __1.hexToBinUnsafe)(hash), (0, __1.hexToBinUnsafe)(publicKey));
83
+ }
84
+ }
85
+ catch (error) {
86
+ return false;
87
+ }
88
+ }
89
+ exports.verifySignature = verifySignature;
@@ -0,0 +1,21 @@
1
+ import EventEmitter from 'eventemitter3';
2
+ type MessageCallback<Message> = (message: Message) => Promise<void>;
3
+ type ErrorCallback<Message> = (error: any, subscription: Subscription<Message>) => Promise<void>;
4
+ export interface SubscribeOptions<Message> {
5
+ pollingInterval: number;
6
+ messageCallback: MessageCallback<Message>;
7
+ errorCallback: ErrorCallback<Message>;
8
+ }
9
+ export declare abstract class Subscription<Message> {
10
+ pollingInterval: number;
11
+ protected messageCallback: MessageCallback<Message>;
12
+ protected errorCallback: ErrorCallback<Message>;
13
+ protected task: ReturnType<typeof setTimeout> | undefined;
14
+ protected eventEmitter: EventEmitter;
15
+ protected cancelled: boolean;
16
+ constructor(options: SubscribeOptions<Message>);
17
+ startPolling(): void;
18
+ unsubscribe(): void;
19
+ abstract polling(): Promise<void>;
20
+ }
21
+ export {};
@@ -0,0 +1,51 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
20
+ return (mod && mod.__esModule) ? mod : { "default": mod };
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.Subscription = void 0;
24
+ const eventemitter3_1 = __importDefault(require("eventemitter3"));
25
+ class Subscription {
26
+ constructor(options) {
27
+ this.pollingInterval = options.pollingInterval;
28
+ this.messageCallback = options.messageCallback;
29
+ this.errorCallback = options.errorCallback;
30
+ this.task = undefined;
31
+ this.cancelled = false;
32
+ this.eventEmitter = new eventemitter3_1.default();
33
+ }
34
+ startPolling() {
35
+ this.eventEmitter.on('tick', async () => {
36
+ await this.polling();
37
+ if (!this.cancelled) {
38
+ this.task = setTimeout(() => this.eventEmitter.emit('tick'), this.pollingInterval);
39
+ }
40
+ });
41
+ this.eventEmitter.emit('tick');
42
+ }
43
+ unsubscribe() {
44
+ this.eventEmitter.removeAllListeners();
45
+ this.cancelled = true;
46
+ if (typeof this.task !== 'undefined') {
47
+ clearTimeout(this.task);
48
+ }
49
+ }
50
+ }
51
+ exports.Subscription = Subscription;
@@ -0,0 +1,40 @@
1
+ import { ec as EC, SignatureInput } from 'elliptic';
2
+ import BN from 'bn.js';
3
+ import { KeyType } from '../signer';
4
+ import { HexString } from '../contract';
5
+ export declare function encodeSignature(signature: EC.Signature | {
6
+ r: BN;
7
+ s: BN;
8
+ }): string;
9
+ export declare function encodeHexSignature(rHex: string, sHex: string): string;
10
+ export declare function signatureDecode(ec: EC, signature: string): SignatureInput;
11
+ export declare function xorByte(intValue: number): number;
12
+ export declare function isHexString(input: string): boolean;
13
+ export declare function groupOfAddress(address: string): number;
14
+ export declare function contractIdFromAddress(address: string): Uint8Array;
15
+ export declare function tokenIdFromAddress(address: string): Uint8Array;
16
+ export declare function hexToBinUnsafe(hex: string): Uint8Array;
17
+ export declare function binToHex(bin: Uint8Array): string;
18
+ export declare function groupOfPrivateKey(privateKey: string, keyType?: KeyType): number;
19
+ export declare function publicKeyFromPrivateKey(privateKey: string, _keyType?: KeyType): string;
20
+ export declare function addressFromPublicKey(publicKey: string, _keyType?: KeyType): string;
21
+ export declare function addressFromContractId(contractId: string): string;
22
+ export declare function addressFromTokenId(tokenId: string): string;
23
+ export declare function contractIdFromTx(txId: string, outputIndex: number): string;
24
+ export declare function subContractId(parentContractId: string, pathInHex: string, group: number): string;
25
+ export declare function blockChainIndex(blockHash: HexString): {
26
+ fromGroup: number;
27
+ toGroup: number;
28
+ };
29
+ export declare function stringToHex(str: string): string;
30
+ export declare function hexToString(str: string): string;
31
+ export declare function sleep(ms: number): Promise<void>;
32
+ type _Eq<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : false;
33
+ export type Eq<X, Y> = _Eq<{
34
+ [P in keyof X]: X[P];
35
+ }, {
36
+ [P in keyof Y]: Y[P];
37
+ }>;
38
+ export declare function assertType<T extends true>(): void;
39
+ export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
40
+ export {};
@@ -0,0 +1,244 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
20
+ return (mod && mod.__esModule) ? mod : { "default": mod };
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.assertType = exports.sleep = exports.hexToString = exports.stringToHex = exports.blockChainIndex = exports.subContractId = exports.contractIdFromTx = exports.addressFromTokenId = exports.addressFromContractId = exports.addressFromPublicKey = exports.publicKeyFromPrivateKey = exports.groupOfPrivateKey = exports.binToHex = exports.hexToBinUnsafe = exports.tokenIdFromAddress = exports.contractIdFromAddress = exports.groupOfAddress = exports.isHexString = exports.xorByte = exports.signatureDecode = exports.encodeHexSignature = exports.encodeSignature = void 0;
24
+ const elliptic_1 = require("elliptic");
25
+ const bn_js_1 = __importDefault(require("bn.js"));
26
+ const blakejs_1 = __importDefault(require("blakejs"));
27
+ const bs58_1 = __importDefault(require("./bs58"));
28
+ const buffer_1 = require("buffer/");
29
+ const constants_1 = require("../constants");
30
+ const djb2_1 = __importDefault(require("./djb2"));
31
+ const ec = new elliptic_1.ec('secp256k1');
32
+ function encodeSignature(signature) {
33
+ let sNormalized = signature.s;
34
+ if (ec.n && signature.s.cmp(ec.nh) === 1) {
35
+ sNormalized = ec.n.sub(signature.s);
36
+ }
37
+ const r = signature.r.toString('hex', 66).slice(2);
38
+ const s = sNormalized.toString('hex', 66).slice(2);
39
+ return r + s;
40
+ }
41
+ exports.encodeSignature = encodeSignature;
42
+ function encodeHexSignature(rHex, sHex) {
43
+ return encodeSignature({ r: new bn_js_1.default(rHex, 'hex'), s: new bn_js_1.default(sHex, 'hex') });
44
+ }
45
+ exports.encodeHexSignature = encodeHexSignature;
46
+ // the signature should be in hex string format for 64 bytes
47
+ function signatureDecode(ec, signature) {
48
+ if (signature.length !== 128) {
49
+ throw new Error('Invalid signature length');
50
+ }
51
+ const sHex = signature.slice(64, 128);
52
+ const s = new bn_js_1.default(sHex, 'hex');
53
+ if (ec.n && s.cmp(ec.nh) < 1) {
54
+ const decoded = { r: signature.slice(0, 64), s: sHex };
55
+ return decoded;
56
+ }
57
+ else {
58
+ throw new Error('The signature is not normalized');
59
+ }
60
+ }
61
+ exports.signatureDecode = signatureDecode;
62
+ function xorByte(intValue) {
63
+ const byte0 = (intValue >> 24) & 0xff;
64
+ const byte1 = (intValue >> 16) & 0xff;
65
+ const byte2 = (intValue >> 8) & 0xff;
66
+ const byte3 = intValue & 0xff;
67
+ return (byte0 ^ byte1 ^ byte2 ^ byte3) & 0xff;
68
+ }
69
+ exports.xorByte = xorByte;
70
+ function isHexString(input) {
71
+ return input.length % 2 === 0 && /^[0-9a-fA-F]*$/.test(input);
72
+ }
73
+ exports.isHexString = isHexString;
74
+ var AddressType;
75
+ (function (AddressType) {
76
+ AddressType[AddressType["P2PKH"] = 0] = "P2PKH";
77
+ AddressType[AddressType["P2MPKH"] = 1] = "P2MPKH";
78
+ AddressType[AddressType["P2SH"] = 2] = "P2SH";
79
+ AddressType[AddressType["P2C"] = 3] = "P2C";
80
+ })(AddressType || (AddressType = {}));
81
+ function groupOfAddress(address) {
82
+ const decoded = bs58_1.default.decode(address);
83
+ if (decoded.length == 0)
84
+ throw new Error('Address string is empty');
85
+ const addressType = decoded[0];
86
+ const addressBody = decoded.slice(1);
87
+ if (addressType == AddressType.P2PKH) {
88
+ return groupOfP2pkhAddress(addressBody);
89
+ }
90
+ else if (addressType == AddressType.P2MPKH) {
91
+ return groupOfP2mpkhAddress(addressBody);
92
+ }
93
+ else if (addressType == AddressType.P2SH) {
94
+ return groupOfP2shAddress(addressBody);
95
+ }
96
+ else {
97
+ // Contract Address
98
+ const id = contractIdFromAddress(address);
99
+ return id[`${id.length - 1}`];
100
+ }
101
+ }
102
+ exports.groupOfAddress = groupOfAddress;
103
+ function groupOfAddressBytes(bytes) {
104
+ const hint = (0, djb2_1.default)(bytes) | 1;
105
+ const hash = xorByte(hint);
106
+ const group = hash % constants_1.TOTAL_NUMBER_OF_GROUPS;
107
+ return group;
108
+ }
109
+ // Pay to public key hash address
110
+ function groupOfP2pkhAddress(address) {
111
+ if (address.length != 32) {
112
+ throw new Error(`Invalid p2pkh address length: ${address.length}`);
113
+ }
114
+ return groupOfAddressBytes(address);
115
+ }
116
+ // Pay to multiple public key hash address
117
+ function groupOfP2mpkhAddress(address) {
118
+ if ((address.length - 2) % 32 != 0) {
119
+ throw new Error(`Invalid p2mpkh address length: ${address.length}`);
120
+ }
121
+ return groupOfAddressBytes(address.slice(1, 33));
122
+ }
123
+ // Pay to script hash address
124
+ function groupOfP2shAddress(address) {
125
+ return groupOfAddressBytes(address);
126
+ }
127
+ function contractIdFromAddress(address) {
128
+ return idFromAddress(address);
129
+ }
130
+ exports.contractIdFromAddress = contractIdFromAddress;
131
+ function tokenIdFromAddress(address) {
132
+ return idFromAddress(address);
133
+ }
134
+ exports.tokenIdFromAddress = tokenIdFromAddress;
135
+ function idFromAddress(address) {
136
+ const decoded = bs58_1.default.decode(address);
137
+ if (decoded.length == 0)
138
+ throw new Error('Address string is empty');
139
+ const addressType = decoded[0];
140
+ const addressBody = decoded.slice(1);
141
+ if (addressType == AddressType.P2C) {
142
+ return addressBody;
143
+ }
144
+ else {
145
+ throw new Error(`Invalid contract address type: ${addressType}`);
146
+ }
147
+ }
148
+ function hexToBinUnsafe(hex) {
149
+ return buffer_1.Buffer.from(hex, 'hex');
150
+ }
151
+ exports.hexToBinUnsafe = hexToBinUnsafe;
152
+ function binToHex(bin) {
153
+ return buffer_1.Buffer.from(bin).toString('hex');
154
+ }
155
+ exports.binToHex = binToHex;
156
+ function groupOfPrivateKey(privateKey, keyType) {
157
+ return groupOfAddress(addressFromPublicKey(publicKeyFromPrivateKey(privateKey, keyType), keyType));
158
+ }
159
+ exports.groupOfPrivateKey = groupOfPrivateKey;
160
+ function publicKeyFromPrivateKey(privateKey, _keyType) {
161
+ const keyType = _keyType ?? 'default';
162
+ if (keyType === 'default') {
163
+ const key = ec.keyFromPrivate(privateKey);
164
+ return key.getPublic(true, 'hex');
165
+ }
166
+ else {
167
+ return ec.g.mul(new bn_js_1.default(privateKey, 16)).encode('hex', true).slice(2);
168
+ }
169
+ }
170
+ exports.publicKeyFromPrivateKey = publicKeyFromPrivateKey;
171
+ function addressFromPublicKey(publicKey, _keyType) {
172
+ const keyType = _keyType ?? 'default';
173
+ if (keyType === 'default') {
174
+ const addressType = buffer_1.Buffer.from([AddressType.P2PKH]);
175
+ const hash = buffer_1.Buffer.from(blakejs_1.default.blake2b(buffer_1.Buffer.from(publicKey, 'hex'), undefined, 32));
176
+ const bytes = buffer_1.Buffer.concat([addressType, hash]);
177
+ return bs58_1.default.encode(bytes);
178
+ }
179
+ else {
180
+ const lockupScript = buffer_1.Buffer.from(`0101000000000458144020${publicKey}8685`, 'hex');
181
+ const lockupScriptHash = blakejs_1.default.blake2b(lockupScript, undefined, 32);
182
+ const addressType = buffer_1.Buffer.from([AddressType.P2SH]);
183
+ return bs58_1.default.encode(buffer_1.Buffer.concat([addressType, lockupScriptHash]));
184
+ }
185
+ }
186
+ exports.addressFromPublicKey = addressFromPublicKey;
187
+ function addressFromContractId(contractId) {
188
+ const addressType = buffer_1.Buffer.from([AddressType.P2C]);
189
+ const hash = buffer_1.Buffer.from(hexToBinUnsafe(contractId));
190
+ const bytes = buffer_1.Buffer.concat([addressType, hash]);
191
+ return bs58_1.default.encode(bytes);
192
+ }
193
+ exports.addressFromContractId = addressFromContractId;
194
+ function addressFromTokenId(tokenId) {
195
+ const contractId = tokenId; // contract ID is the same as token ID
196
+ return addressFromContractId(contractId);
197
+ }
198
+ exports.addressFromTokenId = addressFromTokenId;
199
+ function contractIdFromTx(txId, outputIndex) {
200
+ const txIdBin = hexToBinUnsafe(txId);
201
+ const data = buffer_1.Buffer.concat([txIdBin, buffer_1.Buffer.from([outputIndex])]);
202
+ const hash = blakejs_1.default.blake2b(data, undefined, 32);
203
+ return binToHex(hash);
204
+ }
205
+ exports.contractIdFromTx = contractIdFromTx;
206
+ function subContractId(parentContractId, pathInHex, group) {
207
+ if (group < 0 || group >= constants_1.TOTAL_NUMBER_OF_GROUPS) {
208
+ throw new Error(`Invalid group ${group}`);
209
+ }
210
+ const data = buffer_1.Buffer.concat([hexToBinUnsafe(parentContractId), hexToBinUnsafe(pathInHex)]);
211
+ const bytes = buffer_1.Buffer.concat([
212
+ blakejs_1.default.blake2b(blakejs_1.default.blake2b(data, undefined, 32), undefined, 32).slice(0, -1),
213
+ buffer_1.Buffer.from([group])
214
+ ]);
215
+ return binToHex(bytes);
216
+ }
217
+ exports.subContractId = subContractId;
218
+ function blockChainIndex(blockHash) {
219
+ if (blockHash.length != 64) {
220
+ throw Error(`Invalid block hash: ${blockHash}`);
221
+ }
222
+ const rawIndex = Number('0x' + blockHash.slice(-4)) % constants_1.TOTAL_NUMBER_OF_CHAINS;
223
+ return { fromGroup: Math.floor(rawIndex / constants_1.TOTAL_NUMBER_OF_GROUPS), toGroup: rawIndex % constants_1.TOTAL_NUMBER_OF_GROUPS };
224
+ }
225
+ exports.blockChainIndex = blockChainIndex;
226
+ function stringToHex(str) {
227
+ let hex = '';
228
+ for (let i = 0; i < str.length; i++) {
229
+ hex += '' + str.charCodeAt(i).toString(16);
230
+ }
231
+ return hex;
232
+ }
233
+ exports.stringToHex = stringToHex;
234
+ function hexToString(str) {
235
+ return buffer_1.Buffer.from(str, 'hex').toString();
236
+ }
237
+ exports.hexToString = hexToString;
238
+ function sleep(ms) {
239
+ return new Promise((resolve) => setTimeout(resolve, ms));
240
+ }
241
+ exports.sleep = sleep;
242
+ // eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
243
+ function assertType() { }
244
+ exports.assertType = assertType;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alephium/web3",
3
- "version": "0.9.0-rc.0",
3
+ "version": "0.9.0-rc.1",
4
4
  "description": "A JS/TS library to interact with the Alephium platform",
5
5
  "license": "GPL",
6
6
  "main": "dist/src/index.js",