@ckb-ccc/core 0.1.0-alpha.6 → 0.1.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 (172) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/barrel.d.ts +1 -0
  3. package/dist/barrel.d.ts.map +1 -1
  4. package/dist/barrel.js +1 -0
  5. package/dist/ckb/transactionLumos.d.ts +2 -1
  6. package/dist/ckb/transactionLumos.d.ts.map +1 -1
  7. package/dist/client/client.js +1 -1
  8. package/dist/molecule/codec.d.ts +118 -0
  9. package/dist/molecule/codec.d.ts.map +1 -0
  10. package/dist/molecule/codec.js +446 -0
  11. package/dist/molecule/index.d.ts +3 -0
  12. package/dist/molecule/index.d.ts.map +1 -0
  13. package/dist/molecule/index.js +2 -0
  14. package/dist/molecule/predefined.d.ts +52 -0
  15. package/dist/molecule/predefined.d.ts.map +1 -0
  16. package/dist/molecule/predefined.js +95 -0
  17. package/dist/signer/btc/signerBtc.d.ts.map +1 -1
  18. package/dist/signer/btc/signerBtc.js +2 -3
  19. package/dist/signer/btc/verify.d.ts +14 -1
  20. package/dist/signer/btc/verify.d.ts.map +1 -1
  21. package/dist/signer/btc/verify.js +22 -1
  22. package/dist/signer/doge/index.d.ts +5 -0
  23. package/dist/signer/doge/index.d.ts.map +1 -0
  24. package/dist/signer/doge/index.js +4 -0
  25. package/dist/signer/doge/signerDoge.d.ts +52 -0
  26. package/dist/signer/doge/signerDoge.d.ts.map +1 -0
  27. package/dist/signer/doge/signerDoge.js +82 -0
  28. package/dist/signer/doge/signerDogeAddressReadonly.d.ts +41 -0
  29. package/dist/signer/doge/signerDogeAddressReadonly.d.ts.map +1 -0
  30. package/dist/signer/doge/signerDogeAddressReadonly.js +45 -0
  31. package/dist/signer/doge/signerDogePrivateKey.d.ts +52 -0
  32. package/dist/signer/doge/signerDogePrivateKey.d.ts.map +1 -0
  33. package/dist/signer/doge/signerDogePrivateKey.js +68 -0
  34. package/dist/signer/doge/verify.d.ts +6 -0
  35. package/dist/signer/doge/verify.d.ts.map +1 -0
  36. package/dist/signer/doge/verify.js +17 -0
  37. package/dist/signer/index.d.ts +1 -0
  38. package/dist/signer/index.d.ts.map +1 -1
  39. package/dist/signer/index.js +1 -0
  40. package/dist/signer/nostr/index.d.ts +1 -0
  41. package/dist/signer/nostr/index.d.ts.map +1 -1
  42. package/dist/signer/nostr/index.js +1 -0
  43. package/dist/signer/signer/index.d.ts +4 -2
  44. package/dist/signer/signer/index.d.ts.map +1 -1
  45. package/dist/signer/signer/index.js +5 -0
  46. package/dist.commonjs/address/address.advanced.js +23 -28
  47. package/dist.commonjs/address/advanced.js +1 -17
  48. package/dist.commonjs/address/index.js +11 -15
  49. package/dist.commonjs/advanced.js +2 -31
  50. package/dist.commonjs/advancedBarrel.js +5 -21
  51. package/dist.commonjs/barrel.d.ts +1 -0
  52. package/dist.commonjs/barrel.d.ts.map +1 -1
  53. package/dist.commonjs/barrel.js +12 -27
  54. package/dist.commonjs/bytes/advanced.js +1 -2
  55. package/dist.commonjs/bytes/index.js +7 -12
  56. package/dist.commonjs/ckb/advanced.js +3 -32
  57. package/dist.commonjs/ckb/index.js +3 -19
  58. package/dist.commonjs/ckb/molecule.advanced/generated.js +64 -131
  59. package/dist.commonjs/ckb/molecule.advanced/index.js +2 -19
  60. package/dist.commonjs/ckb/script.advanced.js +3 -6
  61. package/dist.commonjs/ckb/script.js +23 -53
  62. package/dist.commonjs/ckb/transaction.advanced.js +3 -6
  63. package/dist.commonjs/ckb/transaction.js +122 -163
  64. package/dist.commonjs/ckb/transactionLumos.d.ts +2 -1
  65. package/dist.commonjs/ckb/transactionLumos.d.ts.map +1 -1
  66. package/dist.commonjs/ckb/transactionLumos.js +1 -2
  67. package/dist.commonjs/client/advanced.js +6 -22
  68. package/dist.commonjs/client/cache/advanced.js +1 -17
  69. package/dist.commonjs/client/cache/cache.js +3 -7
  70. package/dist.commonjs/client/cache/index.js +2 -18
  71. package/dist.commonjs/client/cache/memory.advanced.js +21 -28
  72. package/dist.commonjs/client/cache/memory.js +19 -23
  73. package/dist.commonjs/client/client.js +22 -26
  74. package/dist.commonjs/client/clientPublicMainnet.advanced.js +22 -25
  75. package/dist.commonjs/client/clientPublicMainnet.js +8 -15
  76. package/dist.commonjs/client/clientPublicTestnet.advanced.js +22 -25
  77. package/dist.commonjs/client/clientPublicTestnet.js +8 -15
  78. package/dist.commonjs/client/clientTypes.advanced.js +3 -6
  79. package/dist.commonjs/client/clientTypes.js +29 -43
  80. package/dist.commonjs/client/index.js +6 -22
  81. package/dist.commonjs/client/jsonRpc/advanced.js +2 -18
  82. package/dist.commonjs/client/jsonRpc/index.js +37 -41
  83. package/dist.commonjs/client/jsonRpc/transformers.js +57 -61
  84. package/dist.commonjs/client/jsonRpc/types.js +1 -2
  85. package/dist.commonjs/client/transports/advanced.js +8 -25
  86. package/dist.commonjs/client/transports/http.js +1 -5
  87. package/dist.commonjs/client/transports/transport.js +1 -2
  88. package/dist.commonjs/client/transports/webSocket.js +3 -10
  89. package/dist.commonjs/fixedPoint/index.js +4 -9
  90. package/dist.commonjs/hasher/advanced.js +1 -4
  91. package/dist.commonjs/hasher/hasher.js +1 -2
  92. package/dist.commonjs/hasher/hasherCkb.js +14 -20
  93. package/dist.commonjs/hasher/hasherKeecak256.js +7 -11
  94. package/dist.commonjs/hasher/index.js +3 -19
  95. package/dist.commonjs/hex/index.js +3 -6
  96. package/dist.commonjs/index.js +2 -31
  97. package/dist.commonjs/keystore/index.js +21 -25
  98. package/dist.commonjs/molecule/codec.d.ts +118 -0
  99. package/dist.commonjs/molecule/codec.d.ts.map +1 -0
  100. package/dist.commonjs/molecule/codec.js +446 -0
  101. package/dist.commonjs/molecule/index.d.ts +3 -0
  102. package/dist.commonjs/molecule/index.d.ts.map +1 -0
  103. package/dist.commonjs/molecule/index.js +2 -0
  104. package/dist.commonjs/molecule/predefined.d.ts +52 -0
  105. package/dist.commonjs/molecule/predefined.d.ts.map +1 -0
  106. package/dist.commonjs/molecule/predefined.js +95 -0
  107. package/dist.commonjs/num/index.js +17 -29
  108. package/dist.commonjs/signer/btc/index.js +3 -19
  109. package/dist.commonjs/signer/btc/signerBtc.d.ts.map +1 -1
  110. package/dist.commonjs/signer/btc/signerBtc.js +20 -25
  111. package/dist.commonjs/signer/btc/signerBtcPublicKeyReadonly.js +4 -8
  112. package/dist.commonjs/signer/btc/verify.d.ts +14 -1
  113. package/dist.commonjs/signer/btc/verify.d.ts.map +1 -1
  114. package/dist.commonjs/signer/btc/verify.js +29 -11
  115. package/dist.commonjs/signer/ckb/index.js +5 -21
  116. package/dist.commonjs/signer/ckb/signerCkbPrivateKey.js +16 -20
  117. package/dist.commonjs/signer/ckb/signerCkbPublicKey.js +20 -24
  118. package/dist.commonjs/signer/ckb/signerCkbScriptReadonly.js +8 -12
  119. package/dist.commonjs/signer/ckb/verifyCkbSecp256k1.js +12 -16
  120. package/dist.commonjs/signer/ckb/verifyJoyId.js +5 -8
  121. package/dist.commonjs/signer/doge/index.d.ts +5 -0
  122. package/dist.commonjs/signer/doge/index.d.ts.map +1 -0
  123. package/dist.commonjs/signer/doge/index.js +4 -0
  124. package/dist.commonjs/signer/doge/signerDoge.d.ts +52 -0
  125. package/dist.commonjs/signer/doge/signerDoge.d.ts.map +1 -0
  126. package/dist.commonjs/signer/doge/signerDoge.js +82 -0
  127. package/dist.commonjs/signer/doge/signerDogeAddressReadonly.d.ts +41 -0
  128. package/dist.commonjs/signer/doge/signerDogeAddressReadonly.d.ts.map +1 -0
  129. package/dist.commonjs/signer/doge/signerDogeAddressReadonly.js +45 -0
  130. package/dist.commonjs/signer/doge/signerDogePrivateKey.d.ts +52 -0
  131. package/dist.commonjs/signer/doge/signerDogePrivateKey.d.ts.map +1 -0
  132. package/dist.commonjs/signer/doge/signerDogePrivateKey.js +68 -0
  133. package/dist.commonjs/signer/doge/verify.d.ts +6 -0
  134. package/dist.commonjs/signer/doge/verify.d.ts.map +1 -0
  135. package/dist.commonjs/signer/doge/verify.js +17 -0
  136. package/dist.commonjs/signer/dummy/alwaysError.js +2 -6
  137. package/dist.commonjs/signer/dummy/dummy.js +3 -7
  138. package/dist.commonjs/signer/dummy/index.js +3 -19
  139. package/dist.commonjs/signer/dummy/openLink.js +2 -6
  140. package/dist.commonjs/signer/evm/index.js +3 -19
  141. package/dist.commonjs/signer/evm/signerEvm.js +31 -35
  142. package/dist.commonjs/signer/evm/signerEvmAddressReadonly.js +4 -8
  143. package/dist.commonjs/signer/evm/verify.js +4 -7
  144. package/dist.commonjs/signer/index.d.ts +1 -0
  145. package/dist.commonjs/signer/index.d.ts.map +1 -1
  146. package/dist.commonjs/signer/index.js +7 -22
  147. package/dist.commonjs/signer/nostr/index.d.ts +1 -0
  148. package/dist.commonjs/signer/nostr/index.d.ts.map +1 -1
  149. package/dist.commonjs/signer/nostr/index.js +2 -17
  150. package/dist.commonjs/signer/nostr/signerNostr.js +21 -25
  151. package/dist.commonjs/signer/nostr/verify.js +12 -16
  152. package/dist.commonjs/signer/signer/index.d.ts +4 -2
  153. package/dist.commonjs/signer/signer/index.d.ts.map +1 -1
  154. package/dist.commonjs/signer/signer/index.js +22 -23
  155. package/dist.commonjs/utils/index.js +6 -12
  156. package/package.json +3 -1
  157. package/src/barrel.ts +1 -0
  158. package/src/ckb/transactionLumos.ts +2 -1
  159. package/src/client/client.ts +1 -1
  160. package/src/molecule/codec.ts +610 -0
  161. package/src/molecule/index.ts +2 -0
  162. package/src/molecule/predefined.ts +114 -0
  163. package/src/signer/btc/signerBtc.ts +2 -3
  164. package/src/signer/btc/verify.ts +31 -2
  165. package/src/signer/doge/index.ts +4 -0
  166. package/src/signer/doge/signerDoge.ts +116 -0
  167. package/src/signer/doge/signerDogeAddressReadonly.ts +52 -0
  168. package/src/signer/doge/signerDogePrivateKey.ts +97 -0
  169. package/src/signer/doge/verify.ts +38 -0
  170. package/src/signer/index.ts +1 -0
  171. package/src/signer/nostr/index.ts +1 -0
  172. package/src/signer/signer/index.ts +9 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # @ckb-ccc/core
2
2
 
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#74](https://github.com/ckb-devrel/ccc/pull/74) [`f21d7e4`](https://github.com/ckb-devrel/ccc/commit/f21d7e4cf422edab4a836ef6d678b620594fef8d) Thanks [@Hanssen0](https://github.com/Hanssen0)! - add spore package and some known scripts
8
+
9
+ ### Patch Changes
10
+
11
+ - [#72](https://github.com/ckb-devrel/ccc/pull/72) [`a3d5359`](https://github.com/ckb-devrel/ccc/commit/a3d53595f6dd11f2f59cdf0086b3d7ce558a2fdd) Thanks [@Hanssen0](https://github.com/Hanssen0)! - fix(core): reopen websocket
12
+
13
+ - [#69](https://github.com/ckb-devrel/ccc/pull/69) [`8824ff2`](https://github.com/ckb-devrel/ccc/commit/8824ff27af3b76186f1a7d6db8c907cd66f09d6a) Thanks [@Hanssen0](https://github.com/Hanssen0)! - feat(core): Client.waitTransaction
14
+
15
+ - [#88](https://github.com/ckb-devrel/ccc/pull/88) [`f07a506`](https://github.com/ckb-devrel/ccc/commit/f07a506bd6fc27fe659a17d2f7baaeec54716d81) Thanks [@ashuralyk](https://github.com/ashuralyk)! - feat: molecule codec
16
+ feat: spore searcher
17
+
18
+ - [#70](https://github.com/ckb-devrel/ccc/pull/70) [`acfc050`](https://github.com/ckb-devrel/ccc/commit/acfc0502cd6beb48b9310dec8411dcd630507366) Thanks [@Hanssen0](https://github.com/Hanssen0)! - fix(core): websocket transport
19
+
20
+ - [#64](https://github.com/ckb-devrel/ccc/pull/64) [`1720d5a`](https://github.com/ckb-devrel/ccc/commit/1720d5a398543f1c6e24763eeaf15d84cd2214bf) Thanks [@Hanssen0](https://github.com/Hanssen0)! - feat(core): ckb proxy locks
21
+
22
+ - [#96](https://github.com/ckb-devrel/ccc/pull/96) [`e63a06e`](https://github.com/ckb-devrel/ccc/commit/e63a06ee75ac8595208d216dec88a4228c465e23) Thanks [@Hanssen0](https://github.com/Hanssen0)! - feat: support doge signer
23
+
24
+ - [#67](https://github.com/ckb-devrel/ccc/pull/67) [`c092988`](https://github.com/ckb-devrel/ccc/commit/c092988e7765b9ac79498d6bd72a6a2f62859b6f) Thanks [@Hanssen0](https://github.com/Hanssen0)! - feat(core): auto fee rate
25
+
26
+ - [`50f2ce0`](https://github.com/ckb-devrel/ccc/commit/50f2ce08e74cb3fbeae926267d42e28b426fd7f4) Thanks [@Hanssen0](https://github.com/Hanssen0)! - fix(core): missing mol types
27
+
28
+ - [#92](https://github.com/ckb-devrel/ccc/pull/92) [`4709384`](https://github.com/ckb-devrel/ccc/commit/4709384e37188991cb937b16f99f47ca82c912b8) Thanks [@Hanssen0](https://github.com/Hanssen0)! - fix: `epochFromHex` failed if the arg is not 7 bytes
29
+
30
+ ## 0.1.0-alpha.7
31
+
32
+ ### Patch Changes
33
+
34
+ - [#88](https://github.com/ckb-devrel/ccc/pull/88) [`f07a506`](https://github.com/ckb-devrel/ccc/commit/f07a506bd6fc27fe659a17d2f7baaeec54716d81) Thanks [@ashuralyk](https://github.com/ashuralyk)! - feat: molecule codec
35
+ feat: spore searcher
36
+
3
37
  ## 0.1.0-alpha.6
4
38
 
5
39
  ### Patch Changes
package/dist/barrel.d.ts CHANGED
@@ -6,6 +6,7 @@ export * from "./fixedPoint/index.js";
6
6
  export * from "./hasher/index.js";
7
7
  export * from "./hex/index.js";
8
8
  export * from "./keystore/index.js";
9
+ export * as mol from "./molecule/index.js";
9
10
  export * from "./num/index.js";
10
11
  export * from "./signer/index.js";
11
12
  export * from "./utils/index.js";
@@ -1 +1 @@
1
- {"version":3,"file":"barrel.d.ts","sourceRoot":"","sources":["../src/barrel.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC"}
1
+ {"version":3,"file":"barrel.d.ts","sourceRoot":"","sources":["../src/barrel.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,OAAO,KAAK,GAAG,MAAM,qBAAqB,CAAC;AAC3C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC"}
package/dist/barrel.js CHANGED
@@ -6,6 +6,7 @@ export * from "./fixedPoint/index.js";
6
6
  export * from "./hasher/index.js";
7
7
  export * from "./hex/index.js";
8
8
  export * from "./keystore/index.js";
9
+ export * as mol from "./molecule/index.js";
9
10
  export * from "./num/index.js";
10
11
  export * from "./signer/index.js";
11
12
  export * from "./utils/index.js";
@@ -1,4 +1,5 @@
1
- import { CellDepLike, CellOutputLike, HexLike, OutPointLike } from "../barrel";
1
+ import { CellDepLike, CellOutputLike, OutPointLike } from "../ckb/index.js";
2
+ import { HexLike } from "../hex/index.js";
2
3
  export interface LumosTransactionSkeletonType {
3
4
  cellDeps: {
4
5
  toArray(): CellDepLike[];
@@ -1 +1 @@
1
- {"version":3,"file":"transactionLumos.d.ts","sourceRoot":"","sources":["../../src/ckb/transactionLumos.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE/E,MAAM,WAAW,4BAA4B;IAC3C,QAAQ,EAAE;QACR,OAAO,IAAI,WAAW,EAAE,CAAC;K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AAC;YAAC,IAAI,EAAE,OAAO,CAAA;SAAE,EAAE,CAAC;KAC5D,CAAC;IACF,SAAS,EAAE;QACT,OAAO,IAAI,OAAO,EAAE,CAAC;KACtB,CAAC;CACH"}
@@ -197,7 +197,7 @@ export class Client {
197
197
  transaction: tx,
198
198
  };
199
199
  }
200
- async waitTransaction(txHash, confirmations = 0, timeout = 30000, interval = 2000) {
200
+ async waitTransaction(txHash, confirmations = 0, timeout = 60000, interval = 2000) {
201
201
  const startTime = Date.now();
202
202
  let tx;
203
203
  const getTx = async () => {
@@ -0,0 +1,118 @@
1
+ import { Bytes, BytesLike } from "../bytes/index.js";
2
+ import { Num, NumLike } from "../num/index.js";
3
+ export type CodecLike<Encodable, Decoded = Encodable> = {
4
+ readonly encode: (encodable: Encodable) => Bytes;
5
+ readonly decode: (decodable: BytesLike) => Decoded;
6
+ readonly byteLength?: number;
7
+ };
8
+ export declare class Codec<Encodable, Decoded = Encodable> {
9
+ readonly encode: (encodable: Encodable) => Bytes;
10
+ readonly decode: (decodable: BytesLike) => Decoded;
11
+ readonly byteLength?: number | undefined;
12
+ constructor(encode: (encodable: Encodable) => Bytes, decode: (decodable: BytesLike) => Decoded, byteLength?: number | undefined);
13
+ static from<Encodable, Decoded = Encodable>({ encode, decode, byteLength, }: CodecLike<Encodable, Decoded>): Codec<Encodable, Decoded>;
14
+ map<NewEncodable = Encodable, NewDecoded = Decoded>({ inMap, outMap, }: {
15
+ inMap?: (encodable: NewEncodable) => Encodable;
16
+ outMap?: (decoded: Decoded) => NewDecoded;
17
+ }): Codec<NewEncodable, NewDecoded>;
18
+ }
19
+ export type EncodableType<T extends CodecLike<any, any>> = T extends CodecLike<infer Encodable, unknown> ? Encodable : never;
20
+ export type DecodedType<T extends CodecLike<any, any>> = T extends CodecLike<any, infer Decoded> ? Decoded : never;
21
+ /**
22
+ * Vector with fixed size item codec
23
+ * @param itemCodec fixed-size vector item codec
24
+ */
25
+ export declare function fixedItemVec<Encodable, Decoded>(itemCodec: CodecLike<Encodable, Decoded>): Codec<Array<Encodable>, Array<Decoded>>;
26
+ /**
27
+ * Vector with dynamic size item codec, you can create a recursive vector with this function
28
+ * @param itemCodec the vector item codec. It can be fixed-size or dynamic-size.
29
+ */
30
+ export declare function dynItemVec<Encodable, Decoded>(itemCodec: CodecLike<Encodable, Decoded>): Codec<Array<Encodable>, Array<Decoded>>;
31
+ /**
32
+ * General vector codec, if `itemCodec` is fixed size type, it will create a fixvec codec, otherwise a dynvec codec will be created.
33
+ * @param itemCodec
34
+ */
35
+ export declare function vector<Encodable, Decoded>(itemCodec: CodecLike<Encodable, Decoded>): Codec<Array<Encodable>, Array<Decoded>>;
36
+ /**
37
+ * Option is a dynamic-size type.
38
+ * Serializing an option depends on whether it is empty or not:
39
+ * - if it's empty, there is zero bytes (the size is 0).
40
+ * - if it's not empty, just serialize the inner item (the size is same as the inner item's size).
41
+ * @param innerCodec
42
+ */
43
+ export declare function option<Encodable, Decoded>(innerCodec: CodecLike<Encodable, Decoded>): Codec<Encodable | undefined | null, Decoded | undefined>;
44
+ /**
45
+ * Wrap the encoded value with a fixed-length buffer
46
+ * @param codec
47
+ */
48
+ export declare function byteVec<Encodable, Decoded>(codec: CodecLike<Encodable, Decoded>): Codec<Encodable, Decoded>;
49
+ export type EncodableRecordOptionalKeys<T extends Record<string, CodecLike<any, any>>> = {
50
+ [K in keyof T]: Extract<EncodableType<T[K]>, undefined> extends never ? never : K;
51
+ }[keyof T];
52
+ export type EncodableRecord<T extends Record<string, CodecLike<any, any>>> = {
53
+ [key in keyof Pick<T, EncodableRecordOptionalKeys<T>>]+?: EncodableType<T[key]>;
54
+ } & {
55
+ [key in keyof Omit<T, EncodableRecordOptionalKeys<T>>]: EncodableType<T[key]>;
56
+ };
57
+ export type DecodedRecordOptionalKeys<T extends Record<string, CodecLike<any, any>>> = {
58
+ [K in keyof T]: Extract<DecodedType<T[K]>, undefined> extends never ? never : K;
59
+ }[keyof T];
60
+ export type DecodedRecord<T extends Record<string, CodecLike<any, any>>> = {
61
+ [key in keyof Pick<T, DecodedRecordOptionalKeys<T>>]+?: DecodedType<T[key]>;
62
+ } & {
63
+ [key in keyof Omit<T, DecodedRecordOptionalKeys<T>>]: DecodedType<T[key]>;
64
+ };
65
+ /**
66
+ * Table is a dynamic-size type. It can be considered as a dynvec but the length is fixed.
67
+ * @param codecLayout
68
+ */
69
+ export declare function table<T extends Record<string, CodecLike<any, any>>, Encodable extends EncodableRecord<T>, Decoded extends DecodedRecord<T>>(codecLayout: T): Codec<Encodable, Decoded>;
70
+ type UnionEncodable<T extends Record<string, CodecLike<any, any>>, K extends keyof T = keyof T> = K extends unknown ? {
71
+ type: K;
72
+ value: EncodableType<T[K]>;
73
+ } : never;
74
+ type UnionDecoded<T extends Record<string, CodecLike<any, any>>, K extends keyof T = keyof T> = K extends unknown ? {
75
+ type: K;
76
+ value: DecodedType<T[K]>;
77
+ } : never;
78
+ /**
79
+ * Union is a dynamic-size type.
80
+ * Serializing a union has two steps:
81
+ * - Serialize an item type id in bytes as a 32 bit unsigned integer in little-endian. The item type id is the index of the inner items, and it's starting at 0.
82
+ * - Serialize the inner item.
83
+ * @param codecLayout the union item record
84
+ * @param fields the custom item type id record
85
+ * @example
86
+ * // without custom id
87
+ * union({ cafe: Uint8, bee: Uint8 })
88
+ * // with custom id
89
+ * union({ cafe: Uint8, bee: Uint8 }, { cafe: 0xcafe, bee: 0xbee })
90
+ */
91
+ export declare function union<T extends Record<string, CodecLike<any, any>>>(codecLayout: T, fields?: Record<keyof T, number | undefined | null>): Codec<UnionEncodable<T>, UnionDecoded<T>>;
92
+ /**
93
+ * Struct is a fixed-size type: all fields in struct are fixed-size and it has a fixed quantity of fields.
94
+ * The size of a struct is the sum of all fields' size.
95
+ * @param codecLayout a object contains all fields' codec
96
+ */
97
+ export declare function struct<T extends Record<string, CodecLike<any, any>>, Encodable extends EncodableRecord<T>, Decoded extends DecodedRecord<T>>(codecLayout: T): Codec<Encodable, Decoded>;
98
+ /**
99
+ * The array is a fixed-size type: it has a fixed-size inner type and a fixed length.
100
+ * The size of an array is the size of inner type times the length.
101
+ * @param itemCodec the fixed-size array item codec
102
+ * @param itemCount
103
+ */
104
+ export declare function array<Encodable, Decoded>(itemCodec: CodecLike<Encodable, Decoded>, itemCount: number): Codec<Array<Encodable>, Array<Decoded>>;
105
+ /**
106
+ * Create a codec to deal with fixed LE or BE bytes.
107
+ * @param byteLength
108
+ * @param littleEndian
109
+ */
110
+ export declare function uint(byteLength: number, littleEndian?: boolean): Codec<NumLike, Num>;
111
+ /**
112
+ * Create a codec to deal with fixed LE or BE bytes.
113
+ * @param byteLength
114
+ * @param littleEndian
115
+ */
116
+ export declare function uintNumber(byteLength: number, littleEndian?: boolean): Codec<NumLike, number>;
117
+ export {};
118
+ //# sourceMappingURL=codec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codec.d.ts","sourceRoot":"","sources":["../../src/molecule/codec.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAA0B,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC7E,OAAO,EACL,GAAG,EAIH,OAAO,EAER,MAAM,iBAAiB,CAAC;AAEzB,MAAM,MAAM,SAAS,CAAC,SAAS,EAAE,OAAO,GAAG,SAAS,IAAI;IACtD,QAAQ,CAAC,MAAM,EAAE,CAAC,SAAS,EAAE,SAAS,KAAK,KAAK,CAAC;IACjD,QAAQ,CAAC,MAAM,EAAE,CAAC,SAAS,EAAE,SAAS,KAAK,OAAO,CAAC;IACnD,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B,CAAC;AACF,qBAAa,KAAK,CAAC,SAAS,EAAE,OAAO,GAAG,SAAS;aAE7B,MAAM,EAAE,CAAC,SAAS,EAAE,SAAS,KAAK,KAAK;aACvC,MAAM,EAAE,CAAC,SAAS,EAAE,SAAS,KAAK,OAAO;aACzC,UAAU,CAAC,EAAE,MAAM;gBAFnB,MAAM,EAAE,CAAC,SAAS,EAAE,SAA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,SAAS,CAAC,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAsCzC;AAED;;;;GAIG;AACH,wBAAgB,IAAI,CAClB,UAAU,EAAE,MAAM,EAClB,YAAY,UAAQ,GACnB,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAkBrB;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CACxB,UAAU,EAAE,MAAM,EAClB,YAAY,UAAQ,GACnB,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,CAOxB"}
@@ -0,0 +1,446 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { bytesConcat, bytesFrom } from "../bytes/index.js";
3
+ import { numBeFromBytes, numBeToBytes, numFromBytes, numToBytes, } from "../num/index.js";
4
+ export class Codec {
5
+ constructor(encode, decode, byteLength) {
6
+ this.encode = encode;
7
+ this.decode = decode;
8
+ this.byteLength = byteLength;
9
+ }
10
+ static from({ encode, decode, byteLength, }) {
11
+ return new Codec(encode, decode, byteLength);
12
+ }
13
+ map({ inMap, outMap, }) {
14
+ return Codec.from({
15
+ byteLength: this.byteLength,
16
+ encode: (encodable) => this.encode((inMap ? inMap(encodable) : encodable)),
17
+ decode: (buffer) => (outMap
18
+ ? outMap(this.decode(buffer))
19
+ : this.decode(buffer)),
20
+ });
21
+ }
22
+ }
23
+ function uint32To(numLike) {
24
+ return numToBytes(numLike, 4);
25
+ }
26
+ function uint32From(bytesLike) {
27
+ return Number(numFromBytes(bytesLike));
28
+ }
29
+ /**
30
+ * Vector with fixed size item codec
31
+ * @param itemCodec fixed-size vector item codec
32
+ */
33
+ export function fixedItemVec(itemCodec) {
34
+ const itemByteLength = itemCodec.byteLength;
35
+ if (itemByteLength === undefined) {
36
+ throw new Error("fixedItemVec: itemCodec requires a byte length");
37
+ }
38
+ return Codec.from({
39
+ encode(userDefinedItems) {
40
+ try {
41
+ return userDefinedItems.reduce((concatted, item) => bytesConcat(concatted, itemCodec.encode(item)), uint32To(userDefinedItems.length));
42
+ }
43
+ catch (e) {
44
+ throw new Error(`fixedItemVec(${e?.toString()})`);
45
+ }
46
+ },
47
+ decode(buffer) {
48
+ const value = bytesFrom(buffer);
49
+ if (value.byteLength < 4) {
50
+ throw new Error(`fixedItemVec: too short buffer, expected at least 4 bytes, but got ${value.byteLength}`);
51
+ }
52
+ const itemCount = uint32From(value.slice(0, 4));
53
+ const byteLength = 4 + itemCount * itemByteLength;
54
+ if (value.byteLength !== byteLength) {
55
+ throw new Error(`fixedItemVec: invalid buffer size, expected ${byteLength}, but got ${value.byteLength}`);
56
+ }
57
+ try {
58
+ const decodedArray = [];
59
+ for (let offset = 0; offset < byteLength; offset += itemByteLength) {
60
+ decodedArray.push(itemCodec.decode(value.slice(offset, offset + itemByteLength)));
61
+ }
62
+ return decodedArray;
63
+ }
64
+ catch (e) {
65
+ throw new Error(`fixedItemVec(${e?.toString()})`);
66
+ }
67
+ },
68
+ });
69
+ }
70
+ /**
71
+ * Vector with dynamic size item codec, you can create a recursive vector with this function
72
+ * @param itemCodec the vector item codec. It can be fixed-size or dynamic-size.
73
+ */
74
+ export function dynItemVec(itemCodec) {
75
+ return Codec.from({
76
+ encode(userDefinedItems) {
77
+ try {
78
+ const encoded = userDefinedItems.reduce(({ offset, header, body }, item) => {
79
+ const encodedItem = itemCodec.encode(item);
80
+ const packedHeader = uint32To(offset);
81
+ return {
82
+ header: bytesConcat(header, packedHeader),
83
+ body: bytesConcat(body, encodedItem),
84
+ offset: offset + bytesFrom(encodedItem).byteLength,
85
+ };
86
+ }, {
87
+ header: bytesFrom([]),
88
+ body: bytesFrom([]),
89
+ offset: 4 + userDefinedItems.length * 4,
90
+ });
91
+ const packedTotalSize = uint32To(encoded.header.byteLength + encoded.body.byteLength + 4);
92
+ return bytesConcat(packedTotalSize, encoded.header, encoded.body);
93
+ }
94
+ catch (e) {
95
+ throw new Error(`dynItemVec(${e?.toString()})`);
96
+ }
97
+ },
98
+ decode(buffer) {
99
+ const value = bytesFrom(buffer);
100
+ const byteLength = uint32From(value.slice(0, 4));
101
+ if (byteLength !== value.byteLength) {
102
+ throw new Error(`dynItemVec: invalid buffer size, expected ${byteLength}, but got ${value.byteLength}`);
103
+ }
104
+ if (value.byteLength < 4) {
105
+ throw new Error(`fixedItemVec: too short buffer, expected at least 4 bytes, but got ${value.byteLength}`);
106
+ }
107
+ const offset = uint32From(value.slice(4, 8));
108
+ const itemCount = (offset - 4) / 4;
109
+ const offsets = Array.from(new Array(itemCount), (_, index) => uint32From(value.slice(4 + index * 4, 8 + index * 4)));
110
+ offsets.push(byteLength);
111
+ try {
112
+ const decodedArray = [];
113
+ for (let index = 0; index < offsets.length - 1; index++) {
114
+ const start = offsets[index];
115
+ const end = offsets[index + 1];
116
+ const itemBuffer = value.slice(start, end);
117
+ decodedArray.push(itemCodec.decode(itemBuffer));
118
+ }
119
+ return decodedArray;
120
+ }
121
+ catch (e) {
122
+ throw new Error(`dynItemVec(${e?.toString()})`);
123
+ }
124
+ },
125
+ });
126
+ }
127
+ /**
128
+ * General vector codec, if `itemCodec` is fixed size type, it will create a fixvec codec, otherwise a dynvec codec will be created.
129
+ * @param itemCodec
130
+ */
131
+ export function vector(itemCodec) {
132
+ if (itemCodec.byteLength !== undefined) {
133
+ return fixedItemVec(itemCodec);
134
+ }
135
+ return dynItemVec(itemCodec);
136
+ }
137
+ /**
138
+ * Option is a dynamic-size type.
139
+ * Serializing an option depends on whether it is empty or not:
140
+ * - if it's empty, there is zero bytes (the size is 0).
141
+ * - if it's not empty, just serialize the inner item (the size is same as the inner item's size).
142
+ * @param innerCodec
143
+ */
144
+ export function option(innerCodec) {
145
+ return Codec.from({
146
+ encode(userDefinedOrNull) {
147
+ if (!userDefinedOrNull) {
148
+ return bytesFrom([]);
149
+ }
150
+ try {
151
+ return innerCodec.encode(userDefinedOrNull);
152
+ }
153
+ catch (e) {
154
+ throw new Error(`option(${e?.toString()})`);
155
+ }
156
+ },
157
+ decode(buffer) {
158
+ const value = bytesFrom(buffer);
159
+ if (value.byteLength === 0) {
160
+ return undefined;
161
+ }
162
+ try {
163
+ return innerCodec.decode(buffer);
164
+ }
165
+ catch (e) {
166
+ throw new Error(`option(${e?.toString()})`);
167
+ }
168
+ },
169
+ });
170
+ }
171
+ /**
172
+ * Wrap the encoded value with a fixed-length buffer
173
+ * @param codec
174
+ */
175
+ export function byteVec(codec) {
176
+ return Codec.from({
177
+ encode(userDefined) {
178
+ try {
179
+ const payload = bytesFrom(codec.encode(userDefined));
180
+ const byteLength = uint32To(payload.byteLength);
181
+ return bytesConcat(byteLength, payload);
182
+ }
183
+ catch (e) {
184
+ throw new Error(`byteVec(${e?.toString()})`);
185
+ }
186
+ },
187
+ decode(buffer) {
188
+ const value = bytesFrom(buffer);
189
+ if (value.byteLength < 4) {
190
+ throw new Error(`byteVec: too short buffer, expected at least 4 bytes, but got ${value.byteLength}`);
191
+ }
192
+ const byteLength = uint32From(value.slice(0, 4));
193
+ if (byteLength !== value.byteLength - 4) {
194
+ throw new Error(`byteVec: invalid buffer size, expected ${byteLength}, but got ${value.byteLength}`);
195
+ }
196
+ try {
197
+ return codec.decode(value.slice(4));
198
+ }
199
+ catch (e) {
200
+ throw new Error(`byteVec(${e?.toString()})`);
201
+ }
202
+ },
203
+ });
204
+ }
205
+ /**
206
+ * Table is a dynamic-size type. It can be considered as a dynvec but the length is fixed.
207
+ * @param codecLayout
208
+ */
209
+ export function table(codecLayout) {
210
+ const keys = Object.keys(codecLayout);
211
+ return Codec.from({
212
+ encode(object) {
213
+ const headerLength = 4 + keys.length * 4;
214
+ const { header, body } = keys.reduce((result, key) => {
215
+ try {
216
+ const encodedItem = codecLayout[key].encode(object[key]);
217
+ const packedOffset = uint32To(result.offset);
218
+ return {
219
+ header: bytesConcat(result.header, packedOffset),
220
+ body: bytesConcat(result.body, encodedItem),
221
+ offset: result.offset + bytesFrom(encodedItem).byteLength,
222
+ };
223
+ }
224
+ catch (e) {
225
+ throw new Error(`table.${key}(${e?.toString()})`);
226
+ }
227
+ }, {
228
+ header: bytesFrom([]),
229
+ body: bytesFrom([]),
230
+ offset: headerLength,
231
+ });
232
+ const packedTotalSize = uint32To(header.byteLength + body.byteLength + 4);
233
+ return bytesConcat(packedTotalSize, header, body);
234
+ },
235
+ decode(buffer) {
236
+ const value = bytesFrom(buffer);
237
+ const byteLength = uint32From(value.slice(0, 4));
238
+ if (byteLength !== value.byteLength) {
239
+ throw new Error(`table: invalid buffer size, expected ${byteLength}, but got ${value.byteLength}`);
240
+ }
241
+ if (byteLength <= 4) {
242
+ throw new Error("table: empty buffer");
243
+ }
244
+ const offsets = keys.map((_, index) => uint32From(value.slice(4 + index * 4, 8 + index * 4)));
245
+ offsets.push(byteLength);
246
+ const object = {};
247
+ for (let i = 0; i < offsets.length - 1; i++) {
248
+ const start = offsets[i];
249
+ const end = offsets[i + 1];
250
+ const field = keys[i];
251
+ const codec = codecLayout[field];
252
+ const payload = value.slice(start, end);
253
+ try {
254
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
255
+ Object.assign(object, { [field]: codec.decode(payload) });
256
+ }
257
+ catch (e) {
258
+ throw new Error(`table.${field}(${e?.toString()})`);
259
+ }
260
+ }
261
+ return object;
262
+ },
263
+ });
264
+ }
265
+ /**
266
+ * Union is a dynamic-size type.
267
+ * Serializing a union has two steps:
268
+ * - Serialize an item type id in bytes as a 32 bit unsigned integer in little-endian. The item type id is the index of the inner items, and it's starting at 0.
269
+ * - Serialize the inner item.
270
+ * @param codecLayout the union item record
271
+ * @param fields the custom item type id record
272
+ * @example
273
+ * // without custom id
274
+ * union({ cafe: Uint8, bee: Uint8 })
275
+ * // with custom id
276
+ * union({ cafe: Uint8, bee: Uint8 }, { cafe: 0xcafe, bee: 0xbee })
277
+ */
278
+ export function union(codecLayout, fields) {
279
+ const keys = Object.keys(codecLayout);
280
+ return Codec.from({
281
+ encode({ type, value }) {
282
+ const typeStr = type.toString();
283
+ const codec = codecLayout[typeStr];
284
+ if (!codec) {
285
+ throw new Error(`union: invalid type, expected ${keys.toString()}, but got ${typeStr}`);
286
+ }
287
+ const fieldId = fields ? (fields[typeStr] ?? -1) : keys.indexOf(typeStr);
288
+ if (fieldId < 0) {
289
+ throw new Error(`union: invalid field id ${fieldId} of ${typeStr}`);
290
+ }
291
+ const header = uint32To(fieldId);
292
+ try {
293
+ const body = codec.encode(value);
294
+ return bytesConcat(header, body);
295
+ }
296
+ catch (e) {
297
+ throw new Error(`union.(${typeStr})(${e?.toString()})`);
298
+ }
299
+ },
300
+ decode(buffer) {
301
+ const value = bytesFrom(buffer);
302
+ const fieldIndex = uint32From(value.slice(0, 4));
303
+ const keys = Object.keys(codecLayout);
304
+ const field = (() => {
305
+ if (!fields) {
306
+ return keys[fieldIndex];
307
+ }
308
+ const entry = Object.entries(fields).find(([, id]) => id === fieldIndex);
309
+ return entry?.[0];
310
+ })();
311
+ if (!field) {
312
+ if (!fields) {
313
+ throw new Error(`union: unknown union field index ${fieldIndex}, only ${keys.toString()} are allowed`);
314
+ }
315
+ const fieldKeys = Object.keys(fields);
316
+ throw new Error(`union: unknown union field index ${fieldIndex}, only ${fieldKeys.toString()} and ${keys.toString()} are allowed`);
317
+ }
318
+ return {
319
+ type: field,
320
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
321
+ value: codecLayout[field].decode(value.slice(4)),
322
+ };
323
+ },
324
+ });
325
+ }
326
+ /**
327
+ * Struct is a fixed-size type: all fields in struct are fixed-size and it has a fixed quantity of fields.
328
+ * The size of a struct is the sum of all fields' size.
329
+ * @param codecLayout a object contains all fields' codec
330
+ */
331
+ export function struct(codecLayout) {
332
+ const codecArray = Object.values(codecLayout);
333
+ if (codecArray.some((codec) => codec.byteLength === undefined)) {
334
+ throw new Error("struct: all fields must be fixed-size");
335
+ }
336
+ const keys = Object.keys(codecLayout);
337
+ return Codec.from({
338
+ byteLength: codecArray.reduce((sum, codec) => sum + codec.byteLength, 0),
339
+ encode(object) {
340
+ return keys.reduce((result, key) => {
341
+ try {
342
+ const encodedItem = codecLayout[key].encode(object[key]);
343
+ return bytesConcat(result, encodedItem);
344
+ }
345
+ catch (e) {
346
+ throw new Error(`struct.${key}(${e?.toString()})`);
347
+ }
348
+ }, bytesFrom([]));
349
+ },
350
+ decode(buffer) {
351
+ const value = bytesFrom(buffer);
352
+ const object = {};
353
+ let offset = 0;
354
+ Object.entries(codecLayout).forEach(([key, codec]) => {
355
+ const payload = value.slice(offset, offset + codec.byteLength);
356
+ try {
357
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
358
+ Object.assign(object, { [key]: codec.decode(payload) });
359
+ }
360
+ catch (e) {
361
+ throw new Error(`struct.${key}(${e.toString()})`);
362
+ }
363
+ offset = offset + codec.byteLength;
364
+ });
365
+ return object;
366
+ },
367
+ });
368
+ }
369
+ /**
370
+ * The array is a fixed-size type: it has a fixed-size inner type and a fixed length.
371
+ * The size of an array is the size of inner type times the length.
372
+ * @param itemCodec the fixed-size array item codec
373
+ * @param itemCount
374
+ */
375
+ export function array(itemCodec, itemCount) {
376
+ if (itemCodec.byteLength === undefined) {
377
+ throw new Error("array: itemCodec requires a byte length");
378
+ }
379
+ const byteLength = itemCodec.byteLength * itemCount;
380
+ return Codec.from({
381
+ byteLength,
382
+ encode(items) {
383
+ try {
384
+ return items.reduce((concatted, item) => bytesConcat(concatted, itemCodec.encode(item)), bytesFrom([]));
385
+ }
386
+ catch (e) {
387
+ throw new Error(`array(${e?.toString()})`);
388
+ }
389
+ },
390
+ decode(buffer) {
391
+ const value = bytesFrom(buffer);
392
+ if (value.byteLength != byteLength) {
393
+ throw new Error(`array: invalid buffer size, expected ${byteLength}, but got ${value.byteLength}`);
394
+ }
395
+ try {
396
+ const result = [];
397
+ for (let i = 0; i < value.byteLength; i += itemCodec.byteLength) {
398
+ result.push(itemCodec.decode(value.slice(i, i + itemCodec.byteLength)));
399
+ }
400
+ return result;
401
+ }
402
+ catch (e) {
403
+ throw new Error(`array(${e?.toString()})`);
404
+ }
405
+ },
406
+ });
407
+ }
408
+ /**
409
+ * Create a codec to deal with fixed LE or BE bytes.
410
+ * @param byteLength
411
+ * @param littleEndian
412
+ */
413
+ export function uint(byteLength, littleEndian = false) {
414
+ return Codec.from({
415
+ byteLength,
416
+ encode: (numLike) => {
417
+ if (littleEndian) {
418
+ return numToBytes(numLike, byteLength);
419
+ }
420
+ else {
421
+ return numBeToBytes(numLike, byteLength);
422
+ }
423
+ },
424
+ decode: (buffer) => {
425
+ if (littleEndian) {
426
+ return numFromBytes(buffer);
427
+ }
428
+ else {
429
+ return numBeFromBytes(buffer);
430
+ }
431
+ },
432
+ });
433
+ }
434
+ /**
435
+ * Create a codec to deal with fixed LE or BE bytes.
436
+ * @param byteLength
437
+ * @param littleEndian
438
+ */
439
+ export function uintNumber(byteLength, littleEndian = false) {
440
+ if (byteLength > 4) {
441
+ throw new Error("uintNumber: byteLength must be less than or equal to 4");
442
+ }
443
+ return uint(byteLength, littleEndian).map({
444
+ outMap: (num) => Number(num),
445
+ });
446
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./codec.js";
2
+ export * from "./predefined.js";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/molecule/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC"}