@alephium/web3 1.3.0 → 1.5.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 (107) 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/address/address.js +11 -5
  4. package/dist/src/api/api-alephium.d.ts +2 -4
  5. package/dist/src/api/api-alephium.js +1 -1
  6. package/dist/src/codec/array-codec.d.ts +4 -12
  7. package/dist/src/codec/array-codec.js +15 -28
  8. package/dist/src/codec/asset-output-codec.d.ts +6 -11
  9. package/dist/src/codec/asset-output-codec.js +32 -71
  10. package/dist/src/codec/bigint-codec.d.ts +2 -1
  11. package/dist/src/codec/bigint-codec.js +14 -2
  12. package/dist/src/codec/bytestring-codec.d.ts +6 -11
  13. package/dist/src/codec/bytestring-codec.js +9 -23
  14. package/dist/src/codec/codec.d.ts +54 -5
  15. package/dist/src/codec/codec.js +112 -14
  16. package/dist/src/codec/compact-int-codec.d.ts +65 -44
  17. package/dist/src/codec/compact-int-codec.js +222 -204
  18. package/dist/src/codec/contract-codec.d.ts +5 -8
  19. package/dist/src/codec/contract-codec.js +15 -29
  20. package/dist/src/codec/contract-output-codec.d.ts +4 -10
  21. package/dist/src/codec/contract-output-codec.js +20 -40
  22. package/dist/src/codec/contract-output-ref-codec.d.ts +2 -8
  23. package/dist/src/codec/contract-output-ref-codec.js +7 -17
  24. package/dist/src/codec/either-codec.d.ts +8 -15
  25. package/dist/src/codec/either-codec.js +5 -46
  26. package/dist/src/codec/index.d.ts +4 -3
  27. package/dist/src/codec/index.js +7 -4
  28. package/dist/src/codec/input-codec.d.ts +4 -10
  29. package/dist/src/codec/input-codec.js +11 -46
  30. package/dist/src/codec/instr-codec.d.ts +633 -40
  31. package/dist/src/codec/instr-codec.js +1040 -434
  32. package/dist/src/codec/int-as-4bytes-codec.d.ts +7 -0
  33. package/dist/src/codec/{signed-int-codec.js → int-as-4bytes-codec.js} +6 -12
  34. package/dist/src/codec/lockup-script-codec.d.ts +23 -26
  35. package/dist/src/codec/lockup-script-codec.js +12 -58
  36. package/dist/src/codec/method-codec.d.ts +6 -18
  37. package/dist/src/codec/method-codec.js +20 -48
  38. package/dist/src/codec/option-codec.d.ts +8 -13
  39. package/dist/src/codec/option-codec.js +14 -32
  40. package/dist/src/codec/output-codec.d.ts +2 -2
  41. package/dist/src/codec/output-codec.js +1 -1
  42. package/dist/src/codec/reader.d.ts +8 -0
  43. package/dist/src/codec/reader.js +48 -0
  44. package/dist/src/codec/script-codec.d.ts +6 -14
  45. package/dist/src/codec/script-codec.js +6 -22
  46. package/dist/src/codec/signature-codec.d.ts +4 -12
  47. package/dist/src/codec/signature-codec.js +3 -15
  48. package/dist/src/codec/timestamp-codec.d.ts +8 -0
  49. package/dist/src/codec/timestamp-codec.js +39 -0
  50. package/dist/src/codec/token-codec.d.ts +3 -10
  51. package/dist/src/codec/token-codec.js +6 -24
  52. package/dist/src/codec/transaction-codec.d.ts +6 -11
  53. package/dist/src/codec/transaction-codec.js +24 -49
  54. package/dist/src/codec/unlock-script-codec.d.ts +25 -36
  55. package/dist/src/codec/unlock-script-codec.js +26 -147
  56. package/dist/src/codec/unsigned-tx-codec.d.ts +8 -14
  57. package/dist/src/codec/unsigned-tx-codec.js +24 -66
  58. package/dist/src/codec/val.d.ts +27 -0
  59. package/dist/src/codec/val.js +33 -0
  60. package/dist/src/contract/contract.d.ts +1 -0
  61. package/dist/src/contract/contract.js +20 -13
  62. package/dist/src/contract/index.d.ts +1 -0
  63. package/dist/src/contract/index.js +1 -0
  64. package/dist/src/contract/ralph.d.ts +0 -4
  65. package/dist/src/contract/ralph.js +50 -179
  66. package/dist/src/contract/script-simulator.d.ts +27 -0
  67. package/dist/src/contract/script-simulator.js +757 -0
  68. package/dist/src/exchange/exchange.js +1 -1
  69. package/package.json +3 -4
  70. package/src/address/address.ts +15 -9
  71. package/src/api/api-alephium.ts +2 -4
  72. package/src/codec/array-codec.ts +16 -34
  73. package/src/codec/asset-output-codec.ts +38 -83
  74. package/src/codec/bigint-codec.ts +16 -2
  75. package/src/codec/bytestring-codec.ts +10 -28
  76. package/src/codec/codec.ts +121 -15
  77. package/src/codec/compact-int-codec.ts +230 -207
  78. package/src/codec/contract-codec.ts +20 -33
  79. package/src/codec/contract-output-codec.ts +22 -48
  80. package/src/codec/contract-output-ref-codec.ts +6 -17
  81. package/src/codec/either-codec.ts +4 -53
  82. package/src/codec/index.ts +4 -3
  83. package/src/codec/input-codec.ts +14 -36
  84. package/src/codec/instr-codec.ts +1229 -455
  85. package/src/codec/{signed-int-codec.ts → int-as-4bytes-codec.ts} +6 -10
  86. package/src/codec/lockup-script-codec.ts +28 -76
  87. package/src/codec/method-codec.ts +23 -61
  88. package/src/codec/option-codec.ts +13 -36
  89. package/src/codec/output-codec.ts +2 -2
  90. package/src/codec/reader.ts +56 -0
  91. package/src/codec/script-codec.ts +9 -31
  92. package/src/codec/signature-codec.ts +3 -18
  93. package/src/codec/timestamp-codec.ts +42 -0
  94. package/src/codec/token-codec.ts +7 -26
  95. package/src/codec/transaction-codec.ts +29 -58
  96. package/src/codec/unlock-script-codec.ts +44 -171
  97. package/src/codec/unsigned-tx-codec.ts +34 -63
  98. package/src/codec/val.ts +40 -0
  99. package/src/contract/contract.ts +24 -20
  100. package/src/contract/index.ts +1 -0
  101. package/src/contract/ralph.ts +76 -172
  102. package/src/contract/script-simulator.ts +838 -0
  103. package/src/exchange/exchange.ts +1 -1
  104. package/dist/src/codec/long-codec.d.ts +0 -8
  105. package/dist/src/codec/long-codec.js +0 -55
  106. package/dist/src/codec/signed-int-codec.d.ts +0 -8
  107. package/src/codec/long-codec.ts +0 -58
@@ -67,18 +67,18 @@ function decodeAndValidateAddress(address) {
67
67
  if (addressType === AddressType.P2MPKH) {
68
68
  let multisig;
69
69
  try {
70
- multisig = lockup_script_codec_1.lockupScriptCodec.decode(decoded).script;
70
+ multisig = lockup_script_codec_1.lockupScriptCodec.decode(decoded).value;
71
71
  }
72
72
  catch (_) {
73
73
  throw new Error(`Invalid multisig address: ${address}`);
74
74
  }
75
- const n = multisig.publicKeyHashes.value.length;
76
- const m = codec_1.compactSignedIntCodec.toI32(multisig.m);
75
+ const n = multisig.publicKeyHashes.length;
76
+ const m = multisig.m;
77
77
  if (n < m || m <= 0) {
78
78
  throw new Error(`Invalid multisig address, n: ${n}, m: ${m}`);
79
79
  }
80
- const encodedNSize = codec_1.compactSignedIntCodec.encodeI32(n).length;
81
- const encodedMSize = multisig.m.rest.length + 1;
80
+ const encodedNSize = codec_1.i32Codec.encode(n).length;
81
+ const encodedMSize = codec_1.i32Codec.encode(m).length;
82
82
  const size = encodedNSize + PublicKeyHashSize * n + encodedMSize + 1; // 1 for the P2MPKH prefix
83
83
  if (decoded.length === size)
84
84
  return decoded;
@@ -214,6 +214,12 @@ function subContractId(parentContractId, pathInHex, group) {
214
214
  if (group < 0 || group >= constants_1.TOTAL_NUMBER_OF_GROUPS) {
215
215
  throw new Error(`Invalid group ${group}`);
216
216
  }
217
+ if (!(0, utils_1.isHexString)(parentContractId)) {
218
+ throw new Error(`Invalid parent contract ID: ${parentContractId}, expected hex string`);
219
+ }
220
+ if (!(0, utils_1.isHexString)(pathInHex)) {
221
+ throw new Error(`Invalid path: ${pathInHex}, expected hex string`);
222
+ }
217
223
  const data = (0, utils_1.concatBytes)([(0, utils_1.hexToBinUnsafe)(parentContractId), (0, utils_1.hexToBinUnsafe)(pathInHex)]);
218
224
  const bytes = new Uint8Array([
219
225
  ...blakejs_1.default.blake2b(blakejs_1.default.blake2b(data, undefined, 32), undefined, 32).slice(0, -1),
@@ -10,7 +10,6 @@ export interface AddressBalance {
10
10
  lockedBalance: string;
11
11
  /** @format x.x ALPH */
12
12
  lockedBalanceHint: string;
13
- warning?: string;
14
13
  }
15
14
  /** AddressInfo */
16
15
  export interface AddressInfo {
@@ -75,7 +74,6 @@ export interface Balance {
75
74
  lockedTokenBalances?: Token[];
76
75
  /** @format int32 */
77
76
  utxoNum: number;
78
- warning?: string;
79
77
  }
80
78
  /** Balances */
81
79
  export interface Balances {
@@ -473,6 +471,7 @@ export interface CompilerOptions {
473
471
  ignoreUnusedPrivateFunctionsWarnings?: boolean;
474
472
  ignoreUpdateFieldsCheckWarnings?: boolean;
475
473
  ignoreCheckExternalCallerWarnings?: boolean;
474
+ ignoreUnusedFunctionReturnWarnings?: boolean;
476
475
  }
477
476
  /** Confirmed */
478
477
  export interface Confirmed {
@@ -1015,7 +1014,6 @@ export interface UTXO {
1015
1014
  /** UTXOs */
1016
1015
  export interface UTXOs {
1017
1016
  utxos: UTXO[];
1018
- warning?: string;
1019
1017
  }
1020
1018
  /** Unauthorized */
1021
1019
  export interface Unauthorized {
@@ -1191,7 +1189,7 @@ export declare class HttpClient<SecurityDataType = unknown> {
1191
1189
  }
1192
1190
  /**
1193
1191
  * @title Alephium API
1194
- * @version 3.4.0
1192
+ * @version 3.5.2
1195
1193
  * @baseUrl ../
1196
1194
  */
1197
1195
  export declare class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> {
@@ -151,7 +151,7 @@ class HttpClient {
151
151
  exports.HttpClient = HttpClient;
152
152
  /**
153
153
  * @title Alephium API
154
- * @version 3.4.0
154
+ * @version 3.5.2
155
155
  * @baseUrl ../
156
156
  */
157
157
  class Api extends HttpClient {
@@ -1,16 +1,8 @@
1
- import { Parser } from 'binary-parser';
2
- import { DecodedCompactInt } from './compact-int-codec';
3
1
  import { Codec } from './codec';
4
- export interface DecodedArray<T> {
5
- length: DecodedCompactInt;
6
- value: T[];
7
- }
8
- export declare class ArrayCodec<T> implements Codec<T[]> {
2
+ import { Reader } from './reader';
3
+ export declare class ArrayCodec<T> extends Codec<T[]> {
9
4
  private childCodec;
10
- parser: Parser;
11
- constructor(childCodec: Codec<T>, parser?: Parser);
5
+ constructor(childCodec: Codec<T>);
12
6
  encode(input: T[]): Uint8Array;
13
- decode(input: Uint8Array): T[];
14
- static arrayParser(parser: Parser): Parser;
15
- fromArray(inputs: T[]): DecodedArray<T>;
7
+ _decode(input: Reader): T[];
16
8
  }
@@ -18,41 +18,28 @@ GNU Lesser General Public License for more details.
18
18
  You should have received a copy of the GNU Lesser General Public License
19
19
  along with the library. If not, see <http://www.gnu.org/licenses/>.
20
20
  */
21
- const binary_parser_1 = require("binary-parser");
22
21
  const compact_int_codec_1 = require("./compact-int-codec");
23
- class ArrayCodec {
24
- constructor(childCodec, parser = ArrayCodec.arrayParser(childCodec.parser)) {
22
+ const codec_1 = require("./codec");
23
+ const utils_1 = require("../utils");
24
+ class ArrayCodec extends codec_1.Codec {
25
+ constructor(childCodec) {
26
+ super();
25
27
  this.childCodec = childCodec;
26
- this.parser = parser;
27
28
  }
28
29
  encode(input) {
29
- const result = [...compact_int_codec_1.compactSignedIntCodec.encodeI256(BigInt(input.length))];
30
+ const bytes = [compact_int_codec_1.i32Codec.encode(input.length)];
30
31
  for (const element of input) {
31
- result.push(...this.childCodec.encode(element));
32
+ bytes.push(this.childCodec.encode(element));
32
33
  }
33
- return new Uint8Array(result);
34
+ return (0, utils_1.concatBytes)(bytes);
34
35
  }
35
- decode(input) {
36
- const result = this.parser.parse(input);
37
- return result.value.map((v) => this.childCodec.decode(v.value));
38
- }
39
- static arrayParser(parser) {
40
- return new binary_parser_1.Parser()
41
- .nest('length', {
42
- type: compact_int_codec_1.compactSignedIntCodec.parser
43
- })
44
- .array('value', {
45
- length: function (ctx) {
46
- return compact_int_codec_1.compactSignedIntCodec.toI32(this['length']);
47
- },
48
- type: parser
49
- });
50
- }
51
- fromArray(inputs) {
52
- return {
53
- length: compact_int_codec_1.compactSignedIntCodec.fromI32(inputs.length),
54
- value: inputs
55
- };
36
+ _decode(input) {
37
+ const length = compact_int_codec_1.i32Codec._decode(input);
38
+ const array = [];
39
+ for (let index = 0; index < length; index += 1) {
40
+ array.push(this.childCodec._decode(input));
41
+ }
42
+ return array;
56
43
  }
57
44
  }
58
45
  exports.ArrayCodec = ArrayCodec;
@@ -1,22 +1,17 @@
1
- import { Parser } from 'binary-parser';
2
- import { ArrayCodec, DecodedArray } from './array-codec';
3
- import { DecodedCompactInt } from './compact-int-codec';
1
+ import { ArrayCodec } from './array-codec';
4
2
  import { ByteString } from './bytestring-codec';
5
3
  import { LockupScript } from './lockup-script-codec';
6
4
  import { FixedAssetOutput } from '../api/api-alephium';
7
- import { Codec } from './codec';
5
+ import { ObjectCodec } from './codec';
8
6
  import { Token } from './token-codec';
9
7
  export interface AssetOutput {
10
- amount: DecodedCompactInt;
8
+ amount: bigint;
11
9
  lockupScript: LockupScript;
12
- lockTime: Uint8Array;
13
- tokens: DecodedArray<Token>;
10
+ lockTime: bigint;
11
+ tokens: Token[];
14
12
  additionalData: ByteString;
15
13
  }
16
- export declare class AssetOutputCodec implements Codec<AssetOutput> {
17
- parser: Parser;
18
- encode(input: AssetOutput): Uint8Array;
19
- decode(input: Uint8Array): AssetOutput;
14
+ export declare class AssetOutputCodec extends ObjectCodec<AssetOutput> {
20
15
  static toFixedAssetOutputs(txIdBytes: Uint8Array, outputs: AssetOutput[]): FixedAssetOutput[];
21
16
  static toFixedAssetOutput(txIdBytes: Uint8Array, output: AssetOutput, index: number): FixedAssetOutput;
22
17
  static fromFixedAssetOutputs(fixedOutputs: FixedAssetOutput[]): AssetOutput[];
@@ -18,76 +18,45 @@ GNU Lesser General Public License for more details.
18
18
  You should have received a copy of the GNU Lesser General Public License
19
19
  along with the library. If not, see <http://www.gnu.org/licenses/>.
20
20
  */
21
- const binary_parser_1 = require("binary-parser");
22
21
  const array_codec_1 = require("./array-codec");
23
22
  const compact_int_codec_1 = require("./compact-int-codec");
24
- const signed_int_codec_1 = require("./signed-int-codec");
25
- const long_codec_1 = require("./long-codec");
23
+ const int_as_4bytes_codec_1 = require("./int-as-4bytes-codec");
24
+ const timestamp_codec_1 = require("./timestamp-codec");
26
25
  const bytestring_codec_1 = require("./bytestring-codec");
27
26
  const lockup_script_codec_1 = require("./lockup-script-codec");
28
27
  const hash_1 = require("./hash");
29
28
  const utils_1 = require("../utils");
29
+ const codec_1 = require("./codec");
30
30
  const token_codec_1 = require("./token-codec");
31
- class AssetOutputCodec {
32
- constructor() {
33
- this.parser = binary_parser_1.Parser.start()
34
- .nest('amount', {
35
- type: compact_int_codec_1.compactSignedIntCodec.parser
36
- })
37
- .nest('lockupScript', {
38
- type: lockup_script_codec_1.lockupScriptCodec.parser
39
- })
40
- .buffer('lockTime', {
41
- length: 8
42
- })
43
- .nest('tokens', {
44
- type: token_codec_1.tokensCodec.parser
45
- })
46
- .nest('additionalData', {
47
- type: bytestring_codec_1.byteStringCodec.parser
48
- });
49
- }
50
- encode(input) {
51
- const amount = compact_int_codec_1.compactUnsignedIntCodec.encode(input.amount);
52
- const lockupScript = lockup_script_codec_1.lockupScriptCodec.encode(input.lockupScript);
53
- const tokens = token_codec_1.tokensCodec.encode(input.tokens.value);
54
- const additionalData = bytestring_codec_1.byteStringCodec.encode(input.additionalData);
55
- return (0, utils_1.concatBytes)([amount, lockupScript, input.lockTime, tokens, additionalData]);
56
- }
57
- decode(input) {
58
- return this.parser.parse(input);
59
- }
31
+ class AssetOutputCodec extends codec_1.ObjectCodec {
60
32
  static toFixedAssetOutputs(txIdBytes, outputs) {
61
33
  return outputs.map((output, index) => AssetOutputCodec.toFixedAssetOutput(txIdBytes, output, index));
62
34
  }
63
35
  static toFixedAssetOutput(txIdBytes, output, index) {
64
- const attoAlphAmount = compact_int_codec_1.compactUnsignedIntCodec.toU256(output.amount).toString();
65
- const lockTime = Number(long_codec_1.longCodec.decode(output.lockTime));
66
- const tokens = output.tokens.value.map((token) => {
36
+ const attoAlphAmount = output.amount.toString();
37
+ const lockTime = Number(output.lockTime);
38
+ const tokens = output.tokens.map((token) => {
67
39
  return {
68
40
  id: (0, utils_1.binToHex)(token.tokenId),
69
- amount: compact_int_codec_1.compactUnsignedIntCodec.toU256(token.amount).toString()
41
+ amount: token.amount.toString()
70
42
  };
71
43
  });
72
- const message = (0, utils_1.binToHex)(output.additionalData.value);
73
- const scriptType = output.lockupScript.scriptType;
74
- const key = (0, utils_1.binToHex)((0, hash_1.blakeHash)((0, utils_1.concatBytes)([txIdBytes, signed_int_codec_1.signedIntCodec.encode(index)])));
75
- const outputLockupScript = output.lockupScript.script;
44
+ const message = (0, utils_1.binToHex)(output.additionalData);
45
+ const scriptType = output.lockupScript.kind;
46
+ const key = (0, utils_1.binToHex)((0, hash_1.blakeHash)((0, utils_1.concatBytes)([txIdBytes, int_as_4bytes_codec_1.intAs4BytesCodec.encode(index)])));
47
+ const outputLockupScript = output.lockupScript.value;
76
48
  const address = utils_1.bs58.encode(lockup_script_codec_1.lockupScriptCodec.encode(output.lockupScript));
77
49
  let hint = undefined;
78
- if (scriptType === 0) {
79
- // P2PKH
80
- hint = (0, hash_1.createHint)(outputLockupScript.publicKeyHash);
50
+ if (scriptType === 'P2PKH') {
51
+ hint = (0, hash_1.createHint)(outputLockupScript);
81
52
  }
82
- else if (scriptType === 1) {
83
- // P2MPKH
84
- hint = (0, hash_1.createHint)(outputLockupScript.publicKeyHashes.value[0].publicKeyHash);
53
+ else if (scriptType === 'P2MPKH') {
54
+ hint = (0, hash_1.createHint)(outputLockupScript.publicKeyHashes[0]);
85
55
  }
86
- else if (scriptType === 2) {
87
- // P2SH
88
- hint = (0, hash_1.createHint)(outputLockupScript.scriptHash);
56
+ else if (scriptType === 'P2SH') {
57
+ hint = (0, hash_1.createHint)(outputLockupScript);
89
58
  }
90
- else if (scriptType === 3) {
59
+ else if (scriptType === 'P2C') {
91
60
  throw new Error(`P2C script type not allowed for asset output`);
92
61
  }
93
62
  else {
@@ -101,33 +70,25 @@ class AssetOutputCodec {
101
70
  });
102
71
  }
103
72
  static fromFixedAssetOutput(fixedOutput) {
104
- const amount = compact_int_codec_1.compactUnsignedIntCodec.fromU256(BigInt(fixedOutput.attoAlphAmount));
105
- const lockTime = long_codec_1.longCodec.encode(BigInt(fixedOutput.lockTime));
73
+ const amount = BigInt(fixedOutput.attoAlphAmount);
74
+ const lockTime = BigInt(fixedOutput.lockTime);
106
75
  const lockupScript = lockup_script_codec_1.lockupScriptCodec.decode(utils_1.bs58.decode(fixedOutput.address));
107
- const tokensValue = fixedOutput.tokens.map((token) => {
76
+ const tokens = fixedOutput.tokens.map((token) => {
108
77
  return {
109
78
  tokenId: (0, utils_1.hexToBinUnsafe)(token.id),
110
- amount: compact_int_codec_1.compactUnsignedIntCodec.fromU256(BigInt(token.amount))
79
+ amount: BigInt(token.amount)
111
80
  };
112
81
  });
113
- const tokens = {
114
- length: compact_int_codec_1.compactSignedIntCodec.fromI32(tokensValue.length),
115
- value: tokensValue
116
- };
117
- const additionalDataValue = (0, utils_1.hexToBinUnsafe)(fixedOutput.message);
118
- const additionalData = {
119
- length: compact_int_codec_1.compactSignedIntCodec.fromI32(additionalDataValue.length),
120
- value: additionalDataValue
121
- };
122
- return {
123
- amount,
124
- lockupScript,
125
- lockTime,
126
- tokens,
127
- additionalData
128
- };
82
+ const additionalData = (0, utils_1.hexToBinUnsafe)(fixedOutput.message);
83
+ return { amount, lockupScript, lockTime, tokens, additionalData };
129
84
  }
130
85
  }
131
86
  exports.AssetOutputCodec = AssetOutputCodec;
132
- exports.assetOutputCodec = new AssetOutputCodec();
87
+ exports.assetOutputCodec = new AssetOutputCodec({
88
+ amount: compact_int_codec_1.u256Codec,
89
+ lockupScript: lockup_script_codec_1.lockupScriptCodec,
90
+ lockTime: timestamp_codec_1.timestampCodec,
91
+ tokens: token_codec_1.tokensCodec,
92
+ additionalData: bytestring_codec_1.byteStringCodec
93
+ });
133
94
  exports.assetOutputsCodec = new array_codec_1.ArrayCodec(exports.assetOutputCodec);
@@ -1,4 +1,5 @@
1
1
  export declare class BigIntCodec {
2
2
  static encode(value: bigint): Uint8Array;
3
- static decode(encoded: Uint8Array, signed: boolean): bigint;
3
+ static decodeUnsigned(encoded: Uint8Array): bigint;
4
+ static decodeSigned(encoded: Uint8Array): bigint;
4
5
  }
@@ -61,13 +61,25 @@ class BigIntCodec {
61
61
  // The byte array needs to be reversed since we've constructed it in little-endian order.
62
62
  return new Uint8Array(bytes.reverse());
63
63
  }
64
- static decode(encoded, signed) {
64
+ static decodeUnsigned(encoded) {
65
+ // Special case for zero.
66
+ if (encoded.length === 1 && encoded[0] === 0) {
67
+ return 0n;
68
+ }
69
+ // Convert the byte array to a bigint
70
+ let value = 0n;
71
+ for (const byte of encoded) {
72
+ value = (value << 8n) | BigInt(byte);
73
+ }
74
+ return value;
75
+ }
76
+ static decodeSigned(encoded) {
65
77
  // Special case for zero.
66
78
  if (encoded.length === 1 && encoded[0] === 0) {
67
79
  return 0n;
68
80
  }
69
81
  // Determine if the number is negative by checking the most significant byte (MSB)
70
- const isNegative = signed ? encoded[0] === 0xff : signed;
82
+ const isNegative = (encoded[0] & 0x80) !== 0;
71
83
  // Convert the byte array to a bigint
72
84
  let value = 0n;
73
85
  for (const byte of encoded) {
@@ -1,15 +1,10 @@
1
- import { Parser } from 'binary-parser';
2
- import { DecodedCompactInt } from './compact-int-codec';
3
1
  import { Codec } from './codec';
4
- export interface ByteString {
5
- length: DecodedCompactInt;
6
- value: Uint8Array;
7
- }
8
- export declare class ByteStringCodec implements Codec<ByteString> {
9
- parser: Parser;
2
+ import { Reader } from './reader';
3
+ import { ArrayCodec } from './array-codec';
4
+ export type ByteString = Uint8Array;
5
+ export declare class ByteStringCodec extends Codec<ByteString> {
10
6
  encode(input: ByteString): Uint8Array;
11
- decode(input: Uint8Array): ByteString;
12
- encodeBytes(input: Uint8Array): Uint8Array;
13
- decodeBytes(input: Uint8Array): Uint8Array;
7
+ _decode(input: Reader): ByteString;
14
8
  }
15
9
  export declare const byteStringCodec: ByteStringCodec;
10
+ export declare const byteStringsCodec: ArrayCodec<Uint8Array>;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.byteStringCodec = exports.ByteStringCodec = void 0;
3
+ exports.byteStringsCodec = exports.byteStringCodec = exports.ByteStringCodec = void 0;
4
4
  /*
5
5
  Copyright 2018 - 2022 The Alephium Authors
6
6
  This file is part of the alephium project.
@@ -18,33 +18,19 @@ GNU Lesser General Public License for more details.
18
18
  You should have received a copy of the GNU Lesser General Public License
19
19
  along with the library. If not, see <http://www.gnu.org/licenses/>.
20
20
  */
21
- const binary_parser_1 = require("binary-parser");
22
21
  const compact_int_codec_1 = require("./compact-int-codec");
22
+ const codec_1 = require("./codec");
23
23
  const utils_1 = require("../utils");
24
- class ByteStringCodec {
25
- constructor() {
26
- this.parser = new binary_parser_1.Parser()
27
- .nest('length', {
28
- type: compact_int_codec_1.compactSignedIntCodec.parser
29
- })
30
- .buffer('value', {
31
- length: function (ctx) {
32
- return compact_int_codec_1.compactSignedIntCodec.toI32(this['length']);
33
- }
34
- });
35
- }
24
+ const array_codec_1 = require("./array-codec");
25
+ class ByteStringCodec extends codec_1.Codec {
36
26
  encode(input) {
37
- return (0, utils_1.concatBytes)([compact_int_codec_1.compactSignedIntCodec.encode(input.length), input.value]);
38
- }
39
- decode(input) {
40
- return this.parser.parse(input);
41
- }
42
- encodeBytes(input) {
43
- return (0, utils_1.concatBytes)([compact_int_codec_1.compactSignedIntCodec.encodeI32(input.length), input]);
27
+ return (0, utils_1.concatBytes)([compact_int_codec_1.i32Codec.encode(input.length), input]);
44
28
  }
45
- decodeBytes(input) {
46
- return this.decode(input).value;
29
+ _decode(input) {
30
+ const length = compact_int_codec_1.i32Codec._decode(input);
31
+ return input.consumeBytes(length);
47
32
  }
48
33
  }
49
34
  exports.ByteStringCodec = ByteStringCodec;
50
35
  exports.byteStringCodec = new ByteStringCodec();
36
+ exports.byteStringsCodec = new array_codec_1.ArrayCodec(exports.byteStringCodec);
@@ -1,8 +1,57 @@
1
- import { Parser } from 'binary-parser';
2
- export interface Codec<T> {
3
- parser: Parser;
4
- encode(input: T): Uint8Array;
1
+ import { Reader } from './reader';
2
+ export declare abstract class Codec<T> {
3
+ abstract encode(input: T): Uint8Array;
5
4
  decode(input: Uint8Array): T;
5
+ abstract _decode(input: Reader): T;
6
+ bimap<R>(from: (v: T) => R, to: (v: R) => T): Codec<R>;
6
7
  }
7
8
  export declare function assert(value: boolean, message: string): void;
8
- export declare function fixedSizeBytes(name: string, length: number): Parser;
9
+ export declare class FixedSizeCodec extends Codec<Uint8Array> {
10
+ private readonly size;
11
+ constructor(size: number);
12
+ encode(input: Uint8Array): Uint8Array;
13
+ _decode(input: Reader): Uint8Array;
14
+ }
15
+ export declare class ObjectCodec<T> extends Codec<T> {
16
+ private codecs;
17
+ private keys;
18
+ constructor(codecs: {
19
+ [K in keyof T]: Codec<T[K]>;
20
+ });
21
+ encode(value: T): Uint8Array;
22
+ _decode(input: Reader): T;
23
+ }
24
+ type ExtractKind<T> = T extends {
25
+ kind: infer U extends string;
26
+ } ? U : never;
27
+ type ExtractValue<T, K> = T extends {
28
+ kind: K;
29
+ value: infer V;
30
+ } ? V : never;
31
+ export declare class EnumCodec<T extends {
32
+ kind: ExtractKind<T>;
33
+ value: ExtractValue<T, ExtractKind<T>>;
34
+ }> extends Codec<T> {
35
+ private name;
36
+ private codecs;
37
+ private kinds;
38
+ constructor(name: string, codecs: {
39
+ [K in ExtractKind<T>]: Codec<ExtractValue<T, K>>;
40
+ });
41
+ encode(value: T): Uint8Array;
42
+ _decode(input: Reader): T;
43
+ }
44
+ export declare const byte32Codec: FixedSizeCodec;
45
+ export declare const byteCodec: {
46
+ encode(input: number): Uint8Array;
47
+ _decode(input: Reader): number;
48
+ decode(input: Uint8Array): number;
49
+ bimap<R>(from: (v: number) => R, to: (v: R) => number): Codec<R>;
50
+ };
51
+ export declare const boolCodec: {
52
+ encode(input: boolean): Uint8Array;
53
+ _decode(input: Reader): boolean;
54
+ decode(input: Uint8Array): boolean;
55
+ bimap<R>(from: (v: boolean) => R, to: (v: R) => boolean): Codec<R>;
56
+ };
57
+ export {};
@@ -1,6 +1,4 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fixedSizeBytes = exports.assert = void 0;
4
2
  /*
5
3
  Copyright 2018 - 2022 The Alephium Authors
6
4
  This file is part of the alephium project.
@@ -18,23 +16,123 @@ GNU Lesser General Public License for more details.
18
16
  You should have received a copy of the GNU Lesser General Public License
19
17
  along with the library. If not, see <http://www.gnu.org/licenses/>.
20
18
  */
21
- const binary_parser_1 = require("binary-parser");
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.boolCodec = exports.byteCodec = exports.byte32Codec = exports.EnumCodec = exports.ObjectCodec = exports.FixedSizeCodec = exports.assert = exports.Codec = void 0;
21
+ const utils_1 = require("../utils");
22
+ const reader_1 = require("./reader");
23
+ class Codec {
24
+ decode(input) {
25
+ const reader = new reader_1.Reader(input);
26
+ return this._decode(reader);
27
+ }
28
+ bimap(from, to) {
29
+ return new (class extends Codec {
30
+ constructor(codecT) {
31
+ super();
32
+ this.codecT = codecT;
33
+ }
34
+ encode(input) {
35
+ return this.codecT.encode(to(input));
36
+ }
37
+ _decode(input) {
38
+ return from(this.codecT._decode(input));
39
+ }
40
+ })(this);
41
+ }
42
+ }
43
+ exports.Codec = Codec;
22
44
  function assert(value, message) {
23
45
  if (!value) {
24
46
  throw new Error(message);
25
47
  }
26
48
  }
27
49
  exports.assert = assert;
28
- function fixedSizeBytes(name, length) {
29
- return binary_parser_1.Parser.start().wrapped({
30
- length,
31
- type: binary_parser_1.Parser.start().buffer(name, { length }),
32
- wrapper: function (result) {
33
- if (result.length === length) {
34
- return result;
35
- }
36
- throw new Error(`Too few bytes when parsing ${name}, expected ${length}, got ${result.length}`);
50
+ class FixedSizeCodec extends Codec {
51
+ constructor(size) {
52
+ super();
53
+ this.size = size;
54
+ }
55
+ encode(input) {
56
+ assert(input.length === this.size, `Invalid length, expected ${this.size}, got ${input.length}`);
57
+ return input;
58
+ }
59
+ _decode(input) {
60
+ return input.consumeBytes(this.size);
61
+ }
62
+ }
63
+ exports.FixedSizeCodec = FixedSizeCodec;
64
+ class ObjectCodec extends Codec {
65
+ constructor(codecs) {
66
+ super();
67
+ this.codecs = codecs;
68
+ this.keys = Object.keys(codecs);
69
+ }
70
+ encode(value) {
71
+ const bytes = [];
72
+ for (const key of this.keys) {
73
+ bytes.push(this.codecs[key].encode(value[key]));
74
+ }
75
+ return (0, utils_1.concatBytes)(bytes);
76
+ }
77
+ _decode(input) {
78
+ const result = {};
79
+ for (const key of this.keys) {
80
+ result[key] = this.codecs[key]._decode(input);
81
+ }
82
+ return result;
83
+ }
84
+ }
85
+ exports.ObjectCodec = ObjectCodec;
86
+ class EnumCodec extends Codec {
87
+ constructor(name, codecs) {
88
+ super();
89
+ this.name = name;
90
+ this.codecs = codecs;
91
+ this.kinds = Object.keys(codecs);
92
+ }
93
+ encode(value) {
94
+ const index = this.kinds.findIndex((t) => t === value.kind);
95
+ if (index === -1) {
96
+ throw new Error(`Invalid ${this.name} kind ${value.kind}, expected one of ${this.kinds}`);
97
+ }
98
+ const codec = this.codecs[value.kind];
99
+ return new Uint8Array([index, ...codec.encode(value.value)]);
100
+ }
101
+ _decode(input) {
102
+ const index = input.consumeByte();
103
+ if (index >= 0 && index < this.kinds.length) {
104
+ const kind = this.kinds[`${index}`];
105
+ const codec = this.codecs[kind];
106
+ return { kind, value: codec._decode(input) };
37
107
  }
38
- });
108
+ throw new Error(`Invalid encoded ${this.name} kind: ${index}`);
109
+ }
39
110
  }
40
- exports.fixedSizeBytes = fixedSizeBytes;
111
+ exports.EnumCodec = EnumCodec;
112
+ exports.byte32Codec = new FixedSizeCodec(32);
113
+ exports.byteCodec = new (class extends Codec {
114
+ encode(input) {
115
+ assert(input >= 0 && input < 256, `Invalid byte: ${input}`);
116
+ return new Uint8Array([input]);
117
+ }
118
+ _decode(input) {
119
+ return input.consumeByte();
120
+ }
121
+ })();
122
+ exports.boolCodec = new (class extends Codec {
123
+ encode(input) {
124
+ return new Uint8Array([input ? 1 : 0]);
125
+ }
126
+ _decode(input) {
127
+ const byte = input.consumeByte();
128
+ if (byte === 1) {
129
+ return true;
130
+ }
131
+ else if (byte === 0) {
132
+ return false;
133
+ }
134
+ else {
135
+ throw new Error(`Invalid encoded bool value ${byte}, expected 0 or 1`);
136
+ }
137
+ }
138
+ })();