@ocap/util 1.30.26 → 1.31.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 (39) hide show
  1. package/esm/amm.d.mts +158 -0
  2. package/esm/amm.mjs +269 -0
  3. package/esm/arcade.d.mts +217 -0
  4. package/esm/arcade.mjs +484 -0
  5. package/esm/bonding-reserve-aup.d.mts +125 -0
  6. package/esm/bonding-reserve-aup.mjs +230 -0
  7. package/esm/composable-container.d.mts +141 -0
  8. package/esm/composable-container.mjs +264 -0
  9. package/esm/conditional-market.d.mts +151 -0
  10. package/esm/conditional-market.mjs +376 -0
  11. package/esm/curve.d.mts +43 -5
  12. package/esm/curve.mjs +71 -9
  13. package/esm/foreign-receipt.d.mts +126 -0
  14. package/esm/foreign-receipt.mjs +388 -0
  15. package/esm/index.d.mts +8 -1
  16. package/esm/index.mjs +8 -1
  17. package/esm/node_modules/@noble/hashes/_md.mjs +168 -0
  18. package/esm/node_modules/@noble/hashes/sha2.mjs +185 -0
  19. package/esm/node_modules/@noble/hashes/utils.mjs +175 -0
  20. package/lib/amm.cjs +279 -0
  21. package/lib/amm.d.cts +158 -0
  22. package/lib/arcade.cjs +491 -0
  23. package/lib/arcade.d.cts +217 -0
  24. package/lib/bonding-reserve-aup.cjs +232 -0
  25. package/lib/bonding-reserve-aup.d.cts +125 -0
  26. package/lib/composable-container.cjs +270 -0
  27. package/lib/composable-container.d.cts +141 -0
  28. package/lib/conditional-market.cjs +377 -0
  29. package/lib/conditional-market.d.cts +151 -0
  30. package/lib/curve.cjs +73 -9
  31. package/lib/curve.d.cts +43 -5
  32. package/lib/foreign-receipt.cjs +396 -0
  33. package/lib/foreign-receipt.d.cts +126 -0
  34. package/lib/index.cjs +57 -1
  35. package/lib/index.d.cts +8 -1
  36. package/lib/node_modules/@noble/hashes/_md.cjs +171 -0
  37. package/lib/node_modules/@noble/hashes/sha2.cjs +185 -0
  38. package/lib/node_modules/@noble/hashes/utils.cjs +183 -0
  39. package/package.json +2 -2
package/lib/index.d.cts CHANGED
@@ -1,5 +1,12 @@
1
1
  import { BN } from "./bn.cjs";
2
2
  import { scopeMatch, scopeMatchAny } from "./scope-match.cjs";
3
+ import { ArcadeFourWaySplitConfig, ArcadeMachineBankroll, ArcadePlaySettlementResult, ArcadeRtpMetrics, LootTableResolution, LootTableTier, PityConfig, ProvablyFairRollInput, ProvablyFairRollResult, RevenueSharePool, ShareHolderPosition, SplitGraphNodes, SplitRecipientEdge, assertMachineBankrollSolvency, deriveProvablyFairRoll, generateHashChain, resolveHierarchicalSplitDag, resolveWeightedLootTable, settleArcadeMachinePlay, verifyHashChainStep } from "./arcade.cjs";
4
+ import { AssetViewDescriptor, AssetViewFormat, AupMultiViewAssetManifest, BondingCurveMintConfig, BondingMintQuote, BondingReserveVault, GenerativeLayerOption, GenerativeTraitLayerSpec, ReserveBackedAssetRecord, buildAupMultiViewManifest, quoteBondingCurveMint } from "./bonding-reserve-aup.cjs";
5
+ import { ComposableAssetNode, ContainerSlotDefinition, LeaseMountTerms, MountedSlotAssignment, SlotMountMode, SynthesisExecutionResult, SynthesisRecipe, SynthesisRecipeRequirement, assertAssetRedeemableOrTransferable, assertNoContainerCycle, createComposableAssetNode, mountContainerSlotItem, synthesizeContainerRecipe, unmountContainerSlotItem } from "./composable-container.cjs";
6
+ import { ConditionalMarketConfig, ConditionalMarketFeeConfig, ConditionalMarketPool, ConditionalMarketStatus, ConditionalResolutionChallenge, ConditionalResolutionProposal, FinalizeResolutionResult, OutcomeBuyQuote } from "./conditional-market.cjs";
7
+ import { ForeignQuoteSpec, ForeignReceiptKey, ForeignReceiptRecord, ForeignReceiptRegistry, ForeignReceiptStatus, ForeignVaultSplitResult, SponsoredQuotaConfig, SponsoredQuotaTracker, computeForeignQuoteDigest, computeForeignReceiptId, formatForeignReceiptKey, isAssetUnlockedByReceipt, sha256Hex, splitForeignVaultPayment } from "./foreign-receipt.cjs";
8
+ import { Direction, calcConstantCost, calcConstantPrice, calcCost, calcFee, calcLinearCost, calcLinearPrice, calcPrice, calcQuadraticCost, calcQuadraticPrice, calcQuotaMintFromPayment, consumePrepaidQuota } from "./curve.cjs";
9
+ import { BNInput, MAX_TOTAL_FEE_BPS, MINIMUM_LIQUIDITY, calcAddLiquidity, calcGraduationSettlement, calcGraduationSupplySplit, calcInitialLiquidity, calcLimitOrderFill, calcRemoveLiquidity, calcSwapExactIn, calcSwapExactOut, isqrt } from "./amm.cjs";
3
10
  import { LiteralUnion } from "type-fest";
4
11
 
5
12
  //#region src/index.d.ts
@@ -228,4 +235,4 @@ declare function isSameDid(a: string, b: string): boolean;
228
235
  declare function extractMethod(did: unknown): string | null;
229
236
  declare function formatTxType(type: string): string;
230
237
  //#endregion
231
- export { BN, BytesType, EncodingType, KeyPairType, UUID, bytesToHex, extractMethod, formatTxType, fromBase58, fromBase64, fromTokenToUnit, fromUnitToToken, hexToBytes, hexToNumber, hexToUtf8, isBN, isBase58btc, isBigNumber, isHex, isHexPrefixed, isHexStrict, isSameDid, isUUID, isUint8Array, leftPad, numberToBN, numberToHex, numberToString, rightPad, scopeMatch, scopeMatchAny, stripHexPrefix, toAddress, toBN, toBase58, toBase64, toBuffer, toDid, toHex, toUint8Array, utf8ToHex };
238
+ export { ArcadeFourWaySplitConfig, ArcadeMachineBankroll, ArcadePlaySettlementResult, ArcadeRtpMetrics, AssetViewDescriptor, AssetViewFormat, AupMultiViewAssetManifest, BN, BNInput, BondingCurveMintConfig, BondingMintQuote, BondingReserveVault, BytesType, ComposableAssetNode, ConditionalMarketConfig, ConditionalMarketFeeConfig, ConditionalMarketPool, ConditionalMarketStatus, ConditionalResolutionChallenge, ConditionalResolutionProposal, ContainerSlotDefinition, Direction, EncodingType, FinalizeResolutionResult, ForeignQuoteSpec, ForeignReceiptKey, ForeignReceiptRecord, ForeignReceiptRegistry, ForeignReceiptStatus, ForeignVaultSplitResult, GenerativeLayerOption, GenerativeTraitLayerSpec, KeyPairType, LeaseMountTerms, LootTableResolution, LootTableTier, MAX_TOTAL_FEE_BPS, MINIMUM_LIQUIDITY, MountedSlotAssignment, OutcomeBuyQuote, PityConfig, ProvablyFairRollInput, ProvablyFairRollResult, ReserveBackedAssetRecord, RevenueSharePool, ShareHolderPosition, SlotMountMode, SplitGraphNodes, SplitRecipientEdge, SponsoredQuotaConfig, SponsoredQuotaTracker, SynthesisExecutionResult, SynthesisRecipe, SynthesisRecipeRequirement, UUID, assertAssetRedeemableOrTransferable, assertMachineBankrollSolvency, assertNoContainerCycle, buildAupMultiViewManifest, bytesToHex, calcAddLiquidity, calcConstantCost, calcConstantPrice, calcCost, calcFee, calcGraduationSettlement, calcGraduationSupplySplit, calcInitialLiquidity, calcLimitOrderFill, calcLinearCost, calcLinearPrice, calcPrice, calcQuadraticCost, calcQuadraticPrice, calcQuotaMintFromPayment, calcRemoveLiquidity, calcSwapExactIn, calcSwapExactOut, computeForeignQuoteDigest, computeForeignReceiptId, consumePrepaidQuota, createComposableAssetNode, deriveProvablyFairRoll, extractMethod, formatForeignReceiptKey, formatTxType, fromBase58, fromBase64, fromTokenToUnit, fromUnitToToken, generateHashChain, hexToBytes, hexToNumber, hexToUtf8, isAssetUnlockedByReceipt, isBN, isBase58btc, isBigNumber, isHex, isHexPrefixed, isHexStrict, isSameDid, isUUID, isUint8Array, isqrt, leftPad, mountContainerSlotItem, numberToBN, numberToHex, numberToString, quoteBondingCurveMint, resolveHierarchicalSplitDag, resolveWeightedLootTable, rightPad, scopeMatch, scopeMatchAny, settleArcadeMachinePlay, sha256Hex, splitForeignVaultPayment, stripHexPrefix, synthesizeContainerRecipe, toAddress, toBN, toBase58, toBase64, toBuffer, toDid, toHex, toUint8Array, unmountContainerSlotItem, utf8ToHex, verifyHashChainStep };
@@ -0,0 +1,171 @@
1
+ const require_utils = require('./utils.cjs');
2
+
3
+ //#region ../../node_modules/@noble/hashes/_md.js
4
+ /**
5
+ * Internal Merkle-Damgard hash utils.
6
+ * @module
7
+ */
8
+ /**
9
+ * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
10
+ * Returns bits from `b` when `a` is set, otherwise from `c`.
11
+ * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
12
+ * set the same bit.
13
+ * @param a - selector word
14
+ * @param b - word chosen when selector bit is set
15
+ * @param c - word chosen when selector bit is clear
16
+ * @returns Mixed 32-bit word.
17
+ * @example
18
+ * Combine three words with the shared 32-bit choice primitive.
19
+ * ```ts
20
+ * Chi(0xffffffff, 0x12345678, 0x87654321);
21
+ * ```
22
+ */
23
+ function Chi(a, b, c) {
24
+ return a & b ^ ~a & c;
25
+ }
26
+ /**
27
+ * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
28
+ * Returns bits shared by at least two inputs.
29
+ * @param a - first input word
30
+ * @param b - second input word
31
+ * @param c - third input word
32
+ * @returns Mixed 32-bit word.
33
+ * @example
34
+ * Combine three words with the shared 32-bit majority primitive.
35
+ * ```ts
36
+ * Maj(0xffffffff, 0x12345678, 0x87654321);
37
+ * ```
38
+ */
39
+ function Maj(a, b, c) {
40
+ return a & b ^ a & c ^ b & c;
41
+ }
42
+ /**
43
+ * Merkle-Damgard hash construction base class.
44
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
45
+ * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
46
+ * strings with partial-byte tails.
47
+ * @param blockLen - internal block size in bytes
48
+ * @param outputLen - digest size in bytes
49
+ * @param padOffset - trailing length field size in bytes
50
+ * @param isLE - whether length and state words are encoded in little-endian
51
+ * @example
52
+ * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
53
+ * ```ts
54
+ * import { _SHA1 } from '@noble/hashes/legacy.js';
55
+ * const hash = new _SHA1();
56
+ * hash.update(new Uint8Array([97, 98, 99]));
57
+ * hash.digest();
58
+ * ```
59
+ */
60
+ var HashMD = class {
61
+ blockLen;
62
+ outputLen;
63
+ canXOF = false;
64
+ padOffset;
65
+ isLE;
66
+ buffer;
67
+ view;
68
+ finished = false;
69
+ length = 0;
70
+ pos = 0;
71
+ destroyed = false;
72
+ constructor(blockLen, outputLen, padOffset, isLE) {
73
+ this.blockLen = blockLen;
74
+ this.outputLen = outputLen;
75
+ this.padOffset = padOffset;
76
+ this.isLE = isLE;
77
+ this.buffer = new Uint8Array(blockLen);
78
+ this.view = require_utils.createView(this.buffer);
79
+ }
80
+ update(data) {
81
+ require_utils.aexists(this);
82
+ require_utils.abytes(data);
83
+ const { view, buffer, blockLen } = this;
84
+ const len = data.length;
85
+ for (let pos = 0; pos < len;) {
86
+ const take = Math.min(blockLen - this.pos, len - pos);
87
+ if (take === blockLen) {
88
+ const dataView = require_utils.createView(data);
89
+ for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
90
+ continue;
91
+ }
92
+ buffer.set(data.subarray(pos, pos + take), this.pos);
93
+ this.pos += take;
94
+ pos += take;
95
+ if (this.pos === blockLen) {
96
+ this.process(view, 0);
97
+ this.pos = 0;
98
+ }
99
+ }
100
+ this.length += data.length;
101
+ this.roundClean();
102
+ return this;
103
+ }
104
+ digestInto(out) {
105
+ require_utils.aexists(this);
106
+ require_utils.aoutput(out, this);
107
+ this.finished = true;
108
+ const { buffer, view, blockLen, isLE } = this;
109
+ let { pos } = this;
110
+ buffer[pos++] = 128;
111
+ require_utils.clean(this.buffer.subarray(pos));
112
+ if (this.padOffset > blockLen - pos) {
113
+ this.process(view, 0);
114
+ pos = 0;
115
+ }
116
+ for (let i = pos; i < blockLen; i++) buffer[i] = 0;
117
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
118
+ this.process(view, 0);
119
+ const oview = require_utils.createView(out);
120
+ const len = this.outputLen;
121
+ if (len % 4) throw new Error("_sha2: outputLen must be aligned to 32bit");
122
+ const outLen = len / 4;
123
+ const state = this.get();
124
+ if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
125
+ for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
126
+ }
127
+ digest() {
128
+ const { buffer, outputLen } = this;
129
+ this.digestInto(buffer);
130
+ const res = buffer.slice(0, outputLen);
131
+ this.destroy();
132
+ return res;
133
+ }
134
+ _cloneInto(to) {
135
+ to ||= new this.constructor();
136
+ to.set(...this.get());
137
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
138
+ to.destroyed = destroyed;
139
+ to.finished = finished;
140
+ to.length = length;
141
+ to.pos = pos;
142
+ if (length % blockLen) to.buffer.set(buffer);
143
+ return to;
144
+ }
145
+ clone() {
146
+ return this._cloneInto();
147
+ }
148
+ };
149
+ /**
150
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
151
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
152
+ */
153
+ /** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
154
+ * square roots of the first eight prime numbers. Exported as a shared table; callers must treat
155
+ * it as read-only because constructors copy words from it by index. */
156
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
157
+ 1779033703,
158
+ 3144134277,
159
+ 1013904242,
160
+ 2773480762,
161
+ 1359893119,
162
+ 2600822924,
163
+ 528734635,
164
+ 1541459225
165
+ ]);
166
+
167
+ //#endregion
168
+ exports.Chi = Chi;
169
+ exports.HashMD = HashMD;
170
+ exports.Maj = Maj;
171
+ exports.SHA256_IV = SHA256_IV;
@@ -0,0 +1,185 @@
1
+ const require_utils = require('./utils.cjs');
2
+ const require__md = require('./_md.cjs');
3
+
4
+ //#region ../../node_modules/@noble/hashes/sha2.js
5
+ /**
6
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
7
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
8
+ * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
9
+ * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
10
+ * @module
11
+ */
12
+ /**
13
+ * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
14
+ * of the cube roots of the first 64 primes (2..311).
15
+ */
16
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
17
+ 1116352408,
18
+ 1899447441,
19
+ 3049323471,
20
+ 3921009573,
21
+ 961987163,
22
+ 1508970993,
23
+ 2453635748,
24
+ 2870763221,
25
+ 3624381080,
26
+ 310598401,
27
+ 607225278,
28
+ 1426881987,
29
+ 1925078388,
30
+ 2162078206,
31
+ 2614888103,
32
+ 3248222580,
33
+ 3835390401,
34
+ 4022224774,
35
+ 264347078,
36
+ 604807628,
37
+ 770255983,
38
+ 1249150122,
39
+ 1555081692,
40
+ 1996064986,
41
+ 2554220882,
42
+ 2821834349,
43
+ 2952996808,
44
+ 3210313671,
45
+ 3336571891,
46
+ 3584528711,
47
+ 113926993,
48
+ 338241895,
49
+ 666307205,
50
+ 773529912,
51
+ 1294757372,
52
+ 1396182291,
53
+ 1695183700,
54
+ 1986661051,
55
+ 2177026350,
56
+ 2456956037,
57
+ 2730485921,
58
+ 2820302411,
59
+ 3259730800,
60
+ 3345764771,
61
+ 3516065817,
62
+ 3600352804,
63
+ 4094571909,
64
+ 275423344,
65
+ 430227734,
66
+ 506948616,
67
+ 659060556,
68
+ 883997877,
69
+ 958139571,
70
+ 1322822218,
71
+ 1537002063,
72
+ 1747873779,
73
+ 1955562222,
74
+ 2024104815,
75
+ 2227730452,
76
+ 2361852424,
77
+ 2428436474,
78
+ 2756734187,
79
+ 3204031479,
80
+ 3329325298
81
+ ]);
82
+ /** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
83
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
84
+ /** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
85
+ var SHA2_32B = class extends require__md.HashMD {
86
+ constructor(outputLen) {
87
+ super(64, outputLen, 8, false);
88
+ }
89
+ get() {
90
+ const { A, B, C, D, E, F, G, H } = this;
91
+ return [
92
+ A,
93
+ B,
94
+ C,
95
+ D,
96
+ E,
97
+ F,
98
+ G,
99
+ H
100
+ ];
101
+ }
102
+ set(A, B, C, D, E, F, G, H) {
103
+ this.A = A | 0;
104
+ this.B = B | 0;
105
+ this.C = C | 0;
106
+ this.D = D | 0;
107
+ this.E = E | 0;
108
+ this.F = F | 0;
109
+ this.G = G | 0;
110
+ this.H = H | 0;
111
+ }
112
+ process(view, offset) {
113
+ for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
114
+ for (let i = 16; i < 64; i++) {
115
+ const W15 = SHA256_W[i - 15];
116
+ const W2 = SHA256_W[i - 2];
117
+ const s0 = require_utils.rotr(W15, 7) ^ require_utils.rotr(W15, 18) ^ W15 >>> 3;
118
+ SHA256_W[i] = (require_utils.rotr(W2, 17) ^ require_utils.rotr(W2, 19) ^ W2 >>> 10) + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
119
+ }
120
+ let { A, B, C, D, E, F, G, H } = this;
121
+ for (let i = 0; i < 64; i++) {
122
+ const sigma1 = require_utils.rotr(E, 6) ^ require_utils.rotr(E, 11) ^ require_utils.rotr(E, 25);
123
+ const T1 = H + sigma1 + require__md.Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
124
+ const T2 = (require_utils.rotr(A, 2) ^ require_utils.rotr(A, 13) ^ require_utils.rotr(A, 22)) + require__md.Maj(A, B, C) | 0;
125
+ H = G;
126
+ G = F;
127
+ F = E;
128
+ E = D + T1 | 0;
129
+ D = C;
130
+ C = B;
131
+ B = A;
132
+ A = T1 + T2 | 0;
133
+ }
134
+ A = A + this.A | 0;
135
+ B = B + this.B | 0;
136
+ C = C + this.C | 0;
137
+ D = D + this.D | 0;
138
+ E = E + this.E | 0;
139
+ F = F + this.F | 0;
140
+ G = G + this.G | 0;
141
+ H = H + this.H | 0;
142
+ this.set(A, B, C, D, E, F, G, H);
143
+ }
144
+ roundClean() {
145
+ require_utils.clean(SHA256_W);
146
+ }
147
+ destroy() {
148
+ this.destroyed = true;
149
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
150
+ require_utils.clean(this.buffer);
151
+ }
152
+ };
153
+ /** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
154
+ var _SHA256 = class extends SHA2_32B {
155
+ A = require__md.SHA256_IV[0] | 0;
156
+ B = require__md.SHA256_IV[1] | 0;
157
+ C = require__md.SHA256_IV[2] | 0;
158
+ D = require__md.SHA256_IV[3] | 0;
159
+ E = require__md.SHA256_IV[4] | 0;
160
+ F = require__md.SHA256_IV[5] | 0;
161
+ G = require__md.SHA256_IV[6] | 0;
162
+ H = require__md.SHA256_IV[7] | 0;
163
+ constructor() {
164
+ super(32);
165
+ }
166
+ };
167
+ /**
168
+ * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
169
+ *
170
+ * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
171
+ * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
172
+ * - Each sha256 hash is executing 2^18 bit operations.
173
+ * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
174
+ * @param msg - message bytes to hash
175
+ * @returns Digest bytes.
176
+ * @example
177
+ * Hash a message with SHA2-256.
178
+ * ```ts
179
+ * sha256(new Uint8Array([97, 98, 99]));
180
+ * ```
181
+ */
182
+ const sha256 = /* @__PURE__ */ require_utils.createHasher(() => new _SHA256(), /* @__PURE__ */ require_utils.oidNist(1));
183
+
184
+ //#endregion
185
+ exports.sha256 = sha256;
@@ -0,0 +1,183 @@
1
+
2
+ //#region ../../node_modules/@noble/hashes/utils.js
3
+ /**
4
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
5
+ * @param a - value to test
6
+ * @returns `true` when the value is a Uint8Array-compatible view.
7
+ * @example
8
+ * Check whether a value is a Uint8Array-compatible view.
9
+ * ```ts
10
+ * isBytes(new Uint8Array([1, 2, 3]));
11
+ * ```
12
+ */
13
+ function isBytes(a) {
14
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
15
+ }
16
+ /**
17
+ * Asserts something is Uint8Array.
18
+ * @param value - value to validate
19
+ * @param length - optional exact length constraint
20
+ * @param title - label included in thrown errors
21
+ * @returns The validated byte array.
22
+ * @throws On wrong argument types. {@link TypeError}
23
+ * @throws On wrong argument ranges or values. {@link RangeError}
24
+ * @example
25
+ * Validate that a value is a byte array.
26
+ * ```ts
27
+ * abytes(new Uint8Array([1, 2, 3]));
28
+ * ```
29
+ */
30
+ function abytes(value, length, title = "") {
31
+ const bytes = isBytes(value);
32
+ const len = value?.length;
33
+ const needsLen = length !== void 0;
34
+ if (!bytes || needsLen && len !== length) {
35
+ const prefix = title && `"${title}" `;
36
+ const ofLen = needsLen ? ` of length ${length}` : "";
37
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
38
+ const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
39
+ if (!bytes) throw new TypeError(message);
40
+ throw new RangeError(message);
41
+ }
42
+ return value;
43
+ }
44
+ /**
45
+ * Asserts a hash instance has not been destroyed or finished.
46
+ * @param instance - hash instance to validate
47
+ * @param checkFinished - whether to reject finalized instances
48
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
49
+ * @example
50
+ * Validate that a hash instance is still usable.
51
+ * ```ts
52
+ * import { aexists } from '@noble/hashes/utils.js';
53
+ * import { sha256 } from '@noble/hashes/sha2.js';
54
+ * const hash = sha256.create();
55
+ * aexists(hash);
56
+ * ```
57
+ */
58
+ function aexists(instance, checkFinished = true) {
59
+ if (instance.destroyed) throw new Error("Hash instance has been destroyed");
60
+ if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
61
+ }
62
+ /**
63
+ * Asserts output is a sufficiently-sized byte array.
64
+ * @param out - destination buffer
65
+ * @param instance - hash instance providing output length
66
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
67
+ * @throws On wrong argument types. {@link TypeError}
68
+ * @throws On wrong argument ranges or values. {@link RangeError}
69
+ * @example
70
+ * Validate a caller-provided digest buffer.
71
+ * ```ts
72
+ * import { aoutput } from '@noble/hashes/utils.js';
73
+ * import { sha256 } from '@noble/hashes/sha2.js';
74
+ * const hash = sha256.create();
75
+ * aoutput(new Uint8Array(hash.outputLen), hash);
76
+ * ```
77
+ */
78
+ function aoutput(out, instance) {
79
+ abytes(out, void 0, "digestInto() output");
80
+ const min = instance.outputLen;
81
+ if (out.length < min) throw new RangeError("\"digestInto() output\" expected to be of length >=" + min);
82
+ }
83
+ /**
84
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
85
+ * @param arrays - arrays to overwrite with zeros
86
+ * @example
87
+ * Zeroize sensitive buffers in place.
88
+ * ```ts
89
+ * clean(new Uint8Array([1, 2, 3]));
90
+ * ```
91
+ */
92
+ function clean(...arrays) {
93
+ for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
94
+ }
95
+ /**
96
+ * Creates a DataView for byte-level manipulation.
97
+ * @param arr - source typed array
98
+ * @returns DataView over the same buffer region.
99
+ * @example
100
+ * Create a DataView over an existing buffer.
101
+ * ```ts
102
+ * createView(new Uint8Array(4));
103
+ * ```
104
+ */
105
+ function createView(arr) {
106
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
107
+ }
108
+ /**
109
+ * Rotate-right operation for uint32 values.
110
+ * @param word - source word
111
+ * @param shift - shift amount in bits
112
+ * @returns Rotated word.
113
+ * @example
114
+ * Rotate a 32-bit word to the right.
115
+ * ```ts
116
+ * rotr(0x12345678, 8);
117
+ * ```
118
+ */
119
+ function rotr(word, shift) {
120
+ return word << 32 - shift | word >>> shift;
121
+ }
122
+ /**
123
+ * Creates a callable hash function from a stateful class constructor.
124
+ * @param hashCons - hash constructor or factory
125
+ * @param info - optional metadata such as DER OID
126
+ * @returns Frozen callable hash wrapper with `.create()`.
127
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
128
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
129
+ * init time.
130
+ * @example
131
+ * Wrap a stateful hash constructor into a callable helper.
132
+ * ```ts
133
+ * import { createHasher } from '@noble/hashes/utils.js';
134
+ * import { sha256 } from '@noble/hashes/sha2.js';
135
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
136
+ * wrapped(new Uint8Array([1]));
137
+ * ```
138
+ */
139
+ function createHasher(hashCons, info = {}) {
140
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
141
+ const tmp = hashCons(void 0);
142
+ hashC.outputLen = tmp.outputLen;
143
+ hashC.blockLen = tmp.blockLen;
144
+ hashC.canXOF = tmp.canXOF;
145
+ hashC.create = (opts) => hashCons(opts);
146
+ Object.assign(hashC, info);
147
+ return Object.freeze(hashC);
148
+ }
149
+ /**
150
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
151
+ * @param suffix - final OID byte for the selected hash.
152
+ * The helper accepts any byte even though only the documented NIST hash
153
+ * suffixes are meaningful downstream.
154
+ * @returns Object containing the DER-encoded OID.
155
+ * @example
156
+ * Build OID metadata for a NIST hash.
157
+ * ```ts
158
+ * oidNist(0x01);
159
+ * ```
160
+ */
161
+ const oidNist = (suffix) => ({ oid: Uint8Array.from([
162
+ 6,
163
+ 9,
164
+ 96,
165
+ 134,
166
+ 72,
167
+ 1,
168
+ 101,
169
+ 3,
170
+ 4,
171
+ 2,
172
+ suffix
173
+ ]) });
174
+
175
+ //#endregion
176
+ exports.abytes = abytes;
177
+ exports.aexists = aexists;
178
+ exports.aoutput = aoutput;
179
+ exports.clean = clean;
180
+ exports.createHasher = createHasher;
181
+ exports.createView = createView;
182
+ exports.oidNist = oidNist;
183
+ exports.rotr = rotr;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocap/util",
3
- "version": "1.30.26",
3
+ "version": "1.31.1",
4
4
  "type": "module",
5
5
  "description": "utils shared across multiple forge js libs, works in both node.js and browser",
6
6
  "keywords": [
@@ -12,7 +12,7 @@
12
12
  "access": "public"
13
13
  },
14
14
  "dependencies": {
15
- "@ocap/types": "1.30.26",
15
+ "@ocap/types": "1.31.1",
16
16
  "@types/bn.js": "^5.2.0",
17
17
  "base64-url": "^2.3.3",
18
18
  "bn.js": "5.2.3",