@solana/addresses 2.0.0-experimental.fb88a79 → 2.0.0-experimental.fbbf6ba

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.
package/README.md CHANGED
@@ -82,7 +82,7 @@ function handleSubmit() {
82
82
 
83
83
  ### `assertIsProgramDerivedAddress()`
84
84
 
85
- In the event that you receive an address/bump-seed tuple from some untrusted source, you can assert that such an tuple conforms to the `ProgramDerivedAddress` type using this function.
85
+ In the event that you receive an address/bump-seed tuple from some untrusted source, you can assert that such a tuple conforms to the `ProgramDerivedAddress` type using this function.
86
86
 
87
87
  See [`assertIsAddress()`](#assertisaddress) for an example of how to use an assertion function.
88
88
 
@@ -1,4 +1,4 @@
1
- export * from './address';
2
- export * from './program-derived-address';
3
- export * from './public-key';
1
+ export * from './address.js';
2
+ export * from './program-derived-address.js';
3
+ export * from './public-key.js';
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,4 @@
1
- import { Address } from './address';
1
+ import { Address } from './address.js';
2
2
  /**
3
3
  * An address derived from a program address and a set of seeds.
4
4
  * It includes the bump seed used to derive the address and
@@ -1,3 +1,3 @@
1
- import { Address } from './address';
1
+ import { Address } from './address.js';
2
2
  export declare function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Address>;
3
3
  //# sourceMappingURL=public-key.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solana/addresses",
3
- "version": "2.0.0-experimental.fb88a79",
3
+ "version": "2.0.0-experimental.fbbf6ba",
4
4
  "description": "Helpers for generating account addresses",
5
5
  "exports": {
6
6
  "browser": {
@@ -49,31 +49,9 @@
49
49
  "node": ">=17.4"
50
50
  },
51
51
  "dependencies": {
52
- "@solana/assertions": "2.0.0-experimental.fb88a79",
53
- "@solana/codecs-core": "2.0.0-experimental.fb88a79",
54
- "@solana/codecs-strings": "2.0.0-experimental.fb88a79"
55
- },
56
- "devDependencies": {
57
- "@solana/eslint-config-solana": "^1.0.2",
58
- "@swc/jest": "^0.2.29",
59
- "@types/jest": "^29.5.6",
60
- "@typescript-eslint/eslint-plugin": "^6.7.0",
61
- "@typescript-eslint/parser": "^6.3.0",
62
- "agadoo": "^3.0.0",
63
- "eslint": "^8.45.0",
64
- "eslint-plugin-jest": "^27.4.2",
65
- "eslint-plugin-sort-keys-fix": "^1.1.2",
66
- "jest": "^29.7.0",
67
- "jest-environment-jsdom": "^29.7.0",
68
- "jest-runner-eslint": "^2.1.2",
69
- "jest-runner-prettier": "^1.0.0",
70
- "prettier": "^3.1",
71
- "tsup": "^8.0.1",
72
- "typescript": "^5.2.2",
73
- "version-from-git": "^1.1.1",
74
- "build-scripts": "0.0.0",
75
- "test-config": "0.0.0",
76
- "tsconfig": "0.0.0"
52
+ "@solana/codecs-strings": "2.0.0-experimental.fbbf6ba",
53
+ "@solana/codecs-core": "2.0.0-experimental.fbbf6ba",
54
+ "@solana/assertions": "2.0.0-experimental.fbbf6ba"
77
55
  },
78
56
  "bundlewatch": {
79
57
  "defaultCompression": "gzip",
@@ -84,18 +62,19 @@
84
62
  ]
85
63
  },
86
64
  "scripts": {
87
- "compile:js": "tsup --config build-scripts/tsup.config.library.ts",
88
- "compile:typedefs": "tsc -p ./tsconfig.declarations.json",
89
- "dev": "jest -c node_modules/test-config/jest-dev.config.ts --rootDir . --watch",
90
- "publish-packages": "pnpm publish --tag experimental --access public --no-git-checks",
65
+ "compile:js": "tsup --config build-scripts/tsup.config.package.ts",
66
+ "compile:typedefs": "tsc -p ./tsconfig.declarations.json && node node_modules/@solana/build-scripts/add-js-extension-to-types.mjs",
67
+ "dev": "jest -c node_modules/@solana/test-config/jest-dev.config.ts --rootDir . --watch",
68
+ "publish-impl": "npm view $npm_package_name@$npm_package_version > /dev/null 2>&1 || pnpm publish --tag experimental --access public --no-git-checks",
69
+ "publish-packages": "pnpm prepublishOnly && pnpm publish-impl",
91
70
  "style:fix": "pnpm eslint --fix src/* && pnpm prettier -w src/* package.json",
92
- "test:lint": "jest -c node_modules/test-config/jest-lint.config.ts --rootDir . --silent",
93
- "test:prettier": "jest -c node_modules/test-config/jest-prettier.config.ts --rootDir . --silent",
71
+ "test:lint": "jest -c node_modules/@solana/test-config/jest-lint.config.ts --rootDir . --silent",
72
+ "test:prettier": "jest -c node_modules/@solana/test-config/jest-prettier.config.ts --rootDir . --silent",
94
73
  "test:treeshakability:browser": "agadoo dist/index.browser.js",
95
74
  "test:treeshakability:native": "agadoo dist/index.native.js",
96
75
  "test:treeshakability:node": "agadoo dist/index.node.js",
97
76
  "test:typecheck": "tsc --noEmit",
98
- "test:unit:browser": "jest -c node_modules/test-config/jest-unit.config.browser.ts --rootDir . --silent",
99
- "test:unit:node": "jest -c node_modules/test-config/jest-unit.config.node.ts --rootDir . --silent"
77
+ "test:unit:browser": "jest -c node_modules/@solana/test-config/jest-unit.config.browser.ts --rootDir . --silent",
78
+ "test:unit:node": "jest -c node_modules/@solana/test-config/jest-unit.config.node.ts --rootDir . --silent"
100
79
  }
101
80
  }
@@ -1,635 +0,0 @@
1
- this.globalThis = this.globalThis || {};
2
- this.globalThis.solanaWeb3 = (function (exports) {
3
- 'use strict';
4
-
5
- // ../codecs-core/dist/index.browser.js
6
- function assertByteArrayIsNotEmptyForCodec(codecDescription, bytes, offset = 0) {
7
- if (bytes.length - offset <= 0) {
8
- throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);
9
- }
10
- }
11
- function assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes, offset = 0) {
12
- const bytesLength = bytes.length - offset;
13
- if (bytesLength < expected) {
14
- throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);
15
- }
16
- }
17
- var padBytes = (bytes, length) => {
18
- if (bytes.length >= length)
19
- return bytes;
20
- const paddedBytes = new Uint8Array(length).fill(0);
21
- paddedBytes.set(bytes);
22
- return paddedBytes;
23
- };
24
- var fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);
25
- function getEncodedSize(value, encoder) {
26
- return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);
27
- }
28
- function createEncoder(encoder) {
29
- return Object.freeze({
30
- ...encoder,
31
- encode: (value) => {
32
- const bytes = new Uint8Array(getEncodedSize(value, encoder));
33
- encoder.write(value, bytes, 0);
34
- return bytes;
35
- }
36
- });
37
- }
38
- function createDecoder(decoder) {
39
- return Object.freeze({
40
- ...decoder,
41
- decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0]
42
- });
43
- }
44
- function isFixedSize(codec) {
45
- return "fixedSize" in codec && typeof codec.fixedSize === "number";
46
- }
47
- function isVariableSize(codec) {
48
- return !isFixedSize(codec);
49
- }
50
- function combineCodec(encoder, decoder) {
51
- if (isFixedSize(encoder) !== isFixedSize(decoder)) {
52
- throw new Error(`Encoder and decoder must either both be fixed-size or variable-size.`);
53
- }
54
- if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {
55
- throw new Error(
56
- `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`
57
- );
58
- }
59
- if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {
60
- throw new Error(
61
- `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`
62
- );
63
- }
64
- return {
65
- ...decoder,
66
- ...encoder,
67
- decode: decoder.decode,
68
- encode: encoder.encode,
69
- read: decoder.read,
70
- write: encoder.write
71
- };
72
- }
73
- function fixEncoder(encoder, fixedBytes) {
74
- return createEncoder({
75
- fixedSize: fixedBytes,
76
- write: (value, bytes, offset) => {
77
- const variableByteArray = encoder.encode(value);
78
- const fixedByteArray = variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;
79
- bytes.set(fixedByteArray, offset);
80
- return offset + fixedBytes;
81
- }
82
- });
83
- }
84
- function fixDecoder(decoder, fixedBytes) {
85
- return createDecoder({
86
- fixedSize: fixedBytes,
87
- read: (bytes, offset) => {
88
- assertByteArrayHasEnoughBytesForCodec("fixCodec", fixedBytes, bytes, offset);
89
- if (offset > 0 || bytes.length > fixedBytes) {
90
- bytes = bytes.slice(offset, offset + fixedBytes);
91
- }
92
- if (isFixedSize(decoder)) {
93
- bytes = fixBytes(bytes, decoder.fixedSize);
94
- }
95
- const [value] = decoder.read(bytes, 0);
96
- return [value, offset + fixedBytes];
97
- }
98
- });
99
- }
100
- function mapEncoder(encoder, unmap) {
101
- return createEncoder({
102
- ...isVariableSize(encoder) ? { ...encoder, getSizeFromValue: (value) => encoder.getSizeFromValue(unmap(value)) } : encoder,
103
- write: (value, bytes, offset) => encoder.write(unmap(value), bytes, offset)
104
- });
105
- }
106
-
107
- // ../codecs-numbers/dist/index.browser.js
108
- function assertNumberIsBetweenForCodec(codecDescription, min, max, value) {
109
- if (value < min || value > max) {
110
- throw new Error(
111
- `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`
112
- );
113
- }
114
- }
115
- function isLittleEndian(config) {
116
- return (config == null ? void 0 : config.endian) === 1 ? false : true;
117
- }
118
- function numberEncoderFactory(input) {
119
- return createEncoder({
120
- fixedSize: input.size,
121
- write(value, bytes, offset) {
122
- if (input.range) {
123
- assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);
124
- }
125
- const arrayBuffer = new ArrayBuffer(input.size);
126
- input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));
127
- bytes.set(new Uint8Array(arrayBuffer), offset);
128
- return offset + input.size;
129
- }
130
- });
131
- }
132
- function numberDecoderFactory(input) {
133
- return createDecoder({
134
- fixedSize: input.size,
135
- read(bytes, offset = 0) {
136
- assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);
137
- assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);
138
- const view = new DataView(toArrayBuffer(bytes, offset, input.size));
139
- return [input.get(view, isLittleEndian(input.config)), offset + input.size];
140
- }
141
- });
142
- }
143
- function toArrayBuffer(bytes, offset, length) {
144
- const bytesOffset = bytes.byteOffset + (offset != null ? offset : 0);
145
- const bytesLength = length != null ? length : bytes.byteLength;
146
- return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);
147
- }
148
- var getU32Encoder = (config = {}) => numberEncoderFactory({
149
- config,
150
- name: "u32",
151
- range: [0, Number("0xffffffff")],
152
- set: (view, value, le) => view.setUint32(0, value, le),
153
- size: 4
154
- });
155
- var getU32Decoder = (config = {}) => numberDecoderFactory({
156
- config,
157
- get: (view, le) => view.getUint32(0, le),
158
- name: "u32",
159
- size: 4
160
- });
161
-
162
- // ../codecs-strings/dist/index.browser.js
163
- function assertValidBaseString(alphabet4, testValue, givenValue = testValue) {
164
- if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {
165
- throw new Error(`Expected a string of base ${alphabet4.length}, got [${givenValue}].`);
166
- }
167
- }
168
- var getBaseXEncoder = (alphabet4) => {
169
- return createEncoder({
170
- getSizeFromValue: (value) => {
171
- const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
172
- if (tailChars === "")
173
- return value.length;
174
- const base10Number = getBigIntFromBaseX(tailChars, alphabet4);
175
- return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);
176
- },
177
- write(value, bytes, offset) {
178
- assertValidBaseString(alphabet4, value);
179
- if (value === "")
180
- return offset;
181
- const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
182
- if (tailChars === "") {
183
- bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);
184
- return offset + leadingZeroes.length;
185
- }
186
- let base10Number = getBigIntFromBaseX(tailChars, alphabet4);
187
- const tailBytes = [];
188
- while (base10Number > 0n) {
189
- tailBytes.unshift(Number(base10Number % 256n));
190
- base10Number /= 256n;
191
- }
192
- const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];
193
- bytes.set(bytesToAdd, offset);
194
- return offset + bytesToAdd.length;
195
- }
196
- });
197
- };
198
- var getBaseXDecoder = (alphabet4) => {
199
- return createDecoder({
200
- read(rawBytes, offset) {
201
- const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);
202
- if (bytes.length === 0)
203
- return ["", 0];
204
- let trailIndex = bytes.findIndex((n) => n !== 0);
205
- trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
206
- const leadingZeroes = alphabet4[0].repeat(trailIndex);
207
- if (trailIndex === bytes.length)
208
- return [leadingZeroes, rawBytes.length];
209
- const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
210
- const tailChars = getBaseXFromBigInt(base10Number, alphabet4);
211
- return [leadingZeroes + tailChars, rawBytes.length];
212
- }
213
- });
214
- };
215
- function partitionLeadingZeroes(value, zeroCharacter) {
216
- const leadingZeroIndex = [...value].findIndex((c) => c !== zeroCharacter);
217
- return leadingZeroIndex === -1 ? [value, ""] : [value.slice(0, leadingZeroIndex), value.slice(leadingZeroIndex)];
218
- }
219
- function getBigIntFromBaseX(value, alphabet4) {
220
- const base = BigInt(alphabet4.length);
221
- return [...value].reduce((sum, char) => sum * base + BigInt(alphabet4.indexOf(char)), 0n);
222
- }
223
- function getBaseXFromBigInt(value, alphabet4) {
224
- const base = BigInt(alphabet4.length);
225
- const tailChars = [];
226
- while (value > 0n) {
227
- tailChars.unshift(alphabet4[Number(value % base)]);
228
- value /= base;
229
- }
230
- return tailChars.join("");
231
- }
232
- var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
233
- var getBase58Encoder = () => getBaseXEncoder(alphabet2);
234
- var getBase58Decoder = () => getBaseXDecoder(alphabet2);
235
- var removeNullCharacters = (value) => (
236
- // eslint-disable-next-line no-control-regex
237
- value.replace(/\u0000/g, "")
238
- );
239
- var e = globalThis.TextDecoder;
240
- var o = globalThis.TextEncoder;
241
- var getUtf8Encoder = () => {
242
- let textEncoder;
243
- return createEncoder({
244
- getSizeFromValue: (value) => (textEncoder || (textEncoder = new o())).encode(value).length,
245
- write: (value, bytes, offset) => {
246
- const bytesToAdd = (textEncoder || (textEncoder = new o())).encode(value);
247
- bytes.set(bytesToAdd, offset);
248
- return offset + bytesToAdd.length;
249
- }
250
- });
251
- };
252
- var getUtf8Decoder = () => {
253
- let textDecoder;
254
- return createDecoder({
255
- read(bytes, offset) {
256
- const value = (textDecoder || (textDecoder = new e())).decode(bytes.slice(offset));
257
- return [removeNullCharacters(value), bytes.length];
258
- }
259
- });
260
- };
261
- function getStringEncoder(config = {}) {
262
- var _a, _b;
263
- const size = (_a = config.size) != null ? _a : getU32Encoder();
264
- const encoding = (_b = config.encoding) != null ? _b : getUtf8Encoder();
265
- if (size === "variable") {
266
- return encoding;
267
- }
268
- if (typeof size === "number") {
269
- return fixEncoder(encoding, size);
270
- }
271
- return createEncoder({
272
- getSizeFromValue: (value) => {
273
- const contentSize = getEncodedSize(value, encoding);
274
- return getEncodedSize(contentSize, size) + contentSize;
275
- },
276
- write: (value, bytes, offset) => {
277
- const contentSize = getEncodedSize(value, encoding);
278
- offset = size.write(contentSize, bytes, offset);
279
- return encoding.write(value, bytes, offset);
280
- }
281
- });
282
- }
283
- function getStringDecoder(config = {}) {
284
- var _a, _b;
285
- const size = (_a = config.size) != null ? _a : getU32Decoder();
286
- const encoding = (_b = config.encoding) != null ? _b : getUtf8Decoder();
287
- if (size === "variable") {
288
- return encoding;
289
- }
290
- if (typeof size === "number") {
291
- return fixDecoder(encoding, size);
292
- }
293
- return createDecoder({
294
- read: (bytes, offset = 0) => {
295
- assertByteArrayIsNotEmptyForCodec("string", bytes, offset);
296
- const [lengthBigInt, lengthOffset] = size.read(bytes, offset);
297
- const length = Number(lengthBigInt);
298
- offset = lengthOffset;
299
- const contentBytes = bytes.slice(offset, offset + length);
300
- assertByteArrayHasEnoughBytesForCodec("string", length, contentBytes);
301
- const [value, contentOffset] = encoding.read(contentBytes, 0);
302
- offset += contentOffset;
303
- return [value, offset];
304
- }
305
- });
306
- }
307
-
308
- // src/address.ts
309
- var memoizedBase58Encoder;
310
- var memoizedBase58Decoder;
311
- function getMemoizedBase58Encoder() {
312
- if (!memoizedBase58Encoder)
313
- memoizedBase58Encoder = getBase58Encoder();
314
- return memoizedBase58Encoder;
315
- }
316
- function getMemoizedBase58Decoder() {
317
- if (!memoizedBase58Decoder)
318
- memoizedBase58Decoder = getBase58Decoder();
319
- return memoizedBase58Decoder;
320
- }
321
- function isAddress(putativeAddress) {
322
- if (
323
- // Lowest address (32 bytes of zeroes)
324
- putativeAddress.length < 32 || // Highest address (32 bytes of 255)
325
- putativeAddress.length > 44
326
- ) {
327
- return false;
328
- }
329
- const base58Encoder = getMemoizedBase58Encoder();
330
- const bytes = base58Encoder.encode(putativeAddress);
331
- const numBytes = bytes.byteLength;
332
- if (numBytes !== 32) {
333
- return false;
334
- }
335
- return true;
336
- }
337
- function assertIsAddress(putativeAddress) {
338
- try {
339
- if (
340
- // Lowest address (32 bytes of zeroes)
341
- putativeAddress.length < 32 || // Highest address (32 bytes of 255)
342
- putativeAddress.length > 44
343
- ) {
344
- throw new Error("Expected input string to decode to a byte array of length 32.");
345
- }
346
- const base58Encoder = getMemoizedBase58Encoder();
347
- const bytes = base58Encoder.encode(putativeAddress);
348
- const numBytes = bytes.byteLength;
349
- if (numBytes !== 32) {
350
- throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
351
- }
352
- } catch (e2) {
353
- throw new Error(`\`${putativeAddress}\` is not a base-58 encoded address`, {
354
- cause: e2
355
- });
356
- }
357
- }
358
- function address(putativeAddress) {
359
- assertIsAddress(putativeAddress);
360
- return putativeAddress;
361
- }
362
- function getAddressEncoder() {
363
- return mapEncoder(
364
- getStringEncoder({ encoding: getMemoizedBase58Encoder(), size: 32 }),
365
- (putativeAddress) => address(putativeAddress)
366
- );
367
- }
368
- function getAddressDecoder() {
369
- return getStringDecoder({ encoding: getMemoizedBase58Decoder(), size: 32 });
370
- }
371
- function getAddressCodec() {
372
- return combineCodec(getAddressEncoder(), getAddressDecoder());
373
- }
374
- function getAddressComparator() {
375
- return new Intl.Collator("en", {
376
- caseFirst: "lower",
377
- ignorePunctuation: false,
378
- localeMatcher: "best fit",
379
- numeric: false,
380
- sensitivity: "variant",
381
- usage: "sort"
382
- }).compare;
383
- }
384
-
385
- // ../assertions/dist/index.browser.js
386
- function assertIsSecureContext() {
387
- if (!globalThis.isSecureContext) {
388
- throw new Error(
389
- "Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"
390
- );
391
- }
392
- }
393
- async function assertDigestCapabilityIsAvailable() {
394
- var _a;
395
- assertIsSecureContext();
396
- if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.digest) !== "function") {
397
- throw new Error("No digest implementation could be found");
398
- }
399
- }
400
- async function assertKeyExporterIsAvailable() {
401
- var _a;
402
- assertIsSecureContext();
403
- if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.exportKey) !== "function") {
404
- throw new Error("No key export implementation could be found");
405
- }
406
- }
407
-
408
- // src/vendor/noble/ed25519.ts
409
- var D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;
410
- var P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n;
411
- var RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;
412
- function mod(a) {
413
- const r = a % P;
414
- return r >= 0n ? r : P + r;
415
- }
416
- function pow2(x, power) {
417
- let r = x;
418
- while (power-- > 0n) {
419
- r *= r;
420
- r %= P;
421
- }
422
- return r;
423
- }
424
- function pow_2_252_3(x) {
425
- const x2 = x * x % P;
426
- const b2 = x2 * x % P;
427
- const b4 = pow2(b2, 2n) * b2 % P;
428
- const b5 = pow2(b4, 1n) * x % P;
429
- const b10 = pow2(b5, 5n) * b5 % P;
430
- const b20 = pow2(b10, 10n) * b10 % P;
431
- const b40 = pow2(b20, 20n) * b20 % P;
432
- const b80 = pow2(b40, 40n) * b40 % P;
433
- const b160 = pow2(b80, 80n) * b80 % P;
434
- const b240 = pow2(b160, 80n) * b80 % P;
435
- const b250 = pow2(b240, 10n) * b10 % P;
436
- const pow_p_5_8 = pow2(b250, 2n) * x % P;
437
- return pow_p_5_8;
438
- }
439
- function uvRatio(u, v) {
440
- const v3 = mod(v * v * v);
441
- const v7 = mod(v3 * v3 * v);
442
- const pow = pow_2_252_3(u * v7);
443
- let x = mod(u * v3 * pow);
444
- const vx2 = mod(v * x * x);
445
- const root1 = x;
446
- const root2 = mod(x * RM1);
447
- const useRoot1 = vx2 === u;
448
- const useRoot2 = vx2 === mod(-u);
449
- const noRoot = vx2 === mod(-u * RM1);
450
- if (useRoot1)
451
- x = root1;
452
- if (useRoot2 || noRoot)
453
- x = root2;
454
- if ((mod(x) & 1n) === 1n)
455
- x = mod(-x);
456
- if (!useRoot1 && !useRoot2) {
457
- return null;
458
- }
459
- return x;
460
- }
461
- function pointIsOnCurve(y, lastByte) {
462
- const y2 = mod(y * y);
463
- const u = mod(y2 - 1n);
464
- const v = mod(D * y2 + 1n);
465
- const x = uvRatio(u, v);
466
- if (x === null) {
467
- return false;
468
- }
469
- const isLastByteOdd = (lastByte & 128) !== 0;
470
- if (x === 0n && isLastByteOdd) {
471
- return false;
472
- }
473
- return true;
474
- }
475
-
476
- // src/curve.ts
477
- function byteToHex(byte) {
478
- const hexString = byte.toString(16);
479
- if (hexString.length === 1) {
480
- return `0${hexString}`;
481
- } else {
482
- return hexString;
483
- }
484
- }
485
- function decompressPointBytes(bytes) {
486
- const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~128 : byte)}${acc}`, "");
487
- const integerLiteralString = `0x${hexString}`;
488
- return BigInt(integerLiteralString);
489
- }
490
- async function compressedPointBytesAreOnCurve(bytes) {
491
- if (bytes.byteLength !== 32) {
492
- return false;
493
- }
494
- const y = decompressPointBytes(bytes);
495
- return pointIsOnCurve(y, bytes[31]);
496
- }
497
-
498
- // src/program-derived-address.ts
499
- function isProgramDerivedAddress(value) {
500
- return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number" && value[1] >= 0 && value[1] <= 255 && isAddress(value[0]);
501
- }
502
- function assertIsProgramDerivedAddress(value) {
503
- const validFormat = Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number";
504
- if (!validFormat) {
505
- throw new Error(
506
- `Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].`
507
- );
508
- }
509
- if (value[1] < 0 || value[1] > 255) {
510
- throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);
511
- }
512
- assertIsAddress(value[0]);
513
- }
514
- var MAX_SEED_LENGTH = 32;
515
- var MAX_SEEDS = 16;
516
- var PDA_MARKER_BYTES = [
517
- // The string 'ProgramDerivedAddress'
518
- 80,
519
- 114,
520
- 111,
521
- 103,
522
- 114,
523
- 97,
524
- 109,
525
- 68,
526
- 101,
527
- 114,
528
- 105,
529
- 118,
530
- 101,
531
- 100,
532
- 65,
533
- 100,
534
- 100,
535
- 114,
536
- 101,
537
- 115,
538
- 115
539
- ];
540
- var PointOnCurveError = class extends Error {
541
- };
542
- async function createProgramDerivedAddress({ programAddress, seeds }) {
543
- await assertDigestCapabilityIsAvailable();
544
- if (seeds.length > MAX_SEEDS) {
545
- throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);
546
- }
547
- let textEncoder;
548
- const seedBytes = seeds.reduce((acc, seed, ii) => {
549
- const bytes = typeof seed === "string" ? (textEncoder || (textEncoder = new TextEncoder())).encode(seed) : seed;
550
- if (bytes.byteLength > MAX_SEED_LENGTH) {
551
- throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);
552
- }
553
- acc.push(...bytes);
554
- return acc;
555
- }, []);
556
- const base58EncodedAddressCodec = getAddressCodec();
557
- const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);
558
- const addressBytesBuffer = await crypto.subtle.digest(
559
- "SHA-256",
560
- new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])
561
- );
562
- const addressBytes = new Uint8Array(addressBytesBuffer);
563
- if (await compressedPointBytesAreOnCurve(addressBytes)) {
564
- throw new PointOnCurveError("Invalid seeds; point must fall off the Ed25519 curve");
565
- }
566
- return base58EncodedAddressCodec.decode(addressBytes);
567
- }
568
- async function getProgramDerivedAddress({
569
- programAddress,
570
- seeds
571
- }) {
572
- let bumpSeed = 255;
573
- while (bumpSeed > 0) {
574
- try {
575
- const address2 = await createProgramDerivedAddress({
576
- programAddress,
577
- seeds: [...seeds, new Uint8Array([bumpSeed])]
578
- });
579
- return [address2, bumpSeed];
580
- } catch (e2) {
581
- if (e2 instanceof PointOnCurveError) {
582
- bumpSeed--;
583
- } else {
584
- throw e2;
585
- }
586
- }
587
- }
588
- throw new Error("Unable to find a viable program address bump seed");
589
- }
590
- async function createAddressWithSeed({ baseAddress, programAddress, seed }) {
591
- const { encode, decode } = getAddressCodec();
592
- const seedBytes = typeof seed === "string" ? new TextEncoder().encode(seed) : seed;
593
- if (seedBytes.byteLength > MAX_SEED_LENGTH) {
594
- throw new Error(`The seed exceeds the maximum length of 32 bytes`);
595
- }
596
- const programAddressBytes = encode(programAddress);
597
- if (programAddressBytes.length >= PDA_MARKER_BYTES.length && programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])) {
598
- throw new Error(`programAddress cannot end with the PDA marker`);
599
- }
600
- const addressBytesBuffer = await crypto.subtle.digest(
601
- "SHA-256",
602
- new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes])
603
- );
604
- const addressBytes = new Uint8Array(addressBytesBuffer);
605
- return decode(addressBytes);
606
- }
607
-
608
- // src/public-key.ts
609
- async function getAddressFromPublicKey(publicKey) {
610
- await assertKeyExporterIsAvailable();
611
- if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") {
612
- throw new Error("The `CryptoKey` must be an `Ed25519` public key");
613
- }
614
- const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
615
- return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));
616
- }
617
-
618
- exports.address = address;
619
- exports.assertIsAddress = assertIsAddress;
620
- exports.assertIsProgramDerivedAddress = assertIsProgramDerivedAddress;
621
- exports.createAddressWithSeed = createAddressWithSeed;
622
- exports.getAddressCodec = getAddressCodec;
623
- exports.getAddressComparator = getAddressComparator;
624
- exports.getAddressDecoder = getAddressDecoder;
625
- exports.getAddressEncoder = getAddressEncoder;
626
- exports.getAddressFromPublicKey = getAddressFromPublicKey;
627
- exports.getProgramDerivedAddress = getProgramDerivedAddress;
628
- exports.isAddress = isAddress;
629
- exports.isProgramDerivedAddress = isProgramDerivedAddress;
630
-
631
- return exports;
632
-
633
- })({});
634
- //# sourceMappingURL=out.js.map
635
- //# sourceMappingURL=index.development.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../codecs-core/src/assertions.ts","../../codecs-core/src/bytes.ts","../../codecs-core/src/codec.ts","../../codecs-core/src/combine-codec.ts","../../codecs-core/src/fix-codec.ts","../../codecs-core/src/map-codec.ts","../../codecs-numbers/src/assertions.ts","../../codecs-numbers/src/f32.ts","../../codecs-numbers/src/utils.ts","../../codecs-numbers/src/u128.ts","../../codecs-strings/dist/index.browser.js","../src/address.ts","../../assertions/src/subtle-crypto.ts","../src/vendor/noble/ed25519.ts","../src/curve.ts","../src/program-derived-address.ts","../src/public-key.ts"],"names":["e","address"],"mappings":";AAGO,SAAS,kCAAkC,kBAA0B,OAAmB,SAAS,GAAG;AACvG,MAAI,MAAM,SAAS,UAAU,GAAG;AAE5B,UAAM,IAAI,MAAM,UAAU,gBAAgB,oCAAoC;EAClF;AACJ;AAKO,SAAS,sCACZ,kBACA,UACA,OACA,SAAS,GACX;AACE,QAAM,cAAc,MAAM,SAAS;AACnC,MAAI,cAAc,UAAU;AAExB,UAAM,IAAI,MAAM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A,IAC1D,SAASD,IAAG;AACR,UAAIA,cAAa,mBAAmB;AAChC;AAAA,MACJ,OAAO;AACH,cAAMA;AAAA,MACV;AAAA,IACJ;AAAA,EACJ;AAEA,QAAM,IAAI,MAAM,mDAAmD;AACvE;AAEA,eAAsB,sBAAsB,EAAE,aAAa,gBAAgB,KAAK,GAAgC;AAC5G,QAAM,EAAE,QAAQ,OAAO,IAAI,gBAAgB;AAE3C,QAAM,YAAY,OAAO,SAAS,WAAW,IAAI,YAAY,EAAE,OAAO,IAAI,IAAI;AAC9E,MAAI,UAAU,aAAa,iBAAiB;AAExC,UAAM,IAAI,MAAM,iDAAiD;AAAA,EACrE;AAEA,QAAM,sBAAsB,OAAO,cAAc;AACjD,MACI,oBAAoB,UAAU,iBAAiB,UAC/C,oBAAoB,MAAM,CAAC,iBAAiB,MAAM,EAAE,MAAM,CAAC,MAAM,UAAU,SAAS,iBAAiB,KAAK,CAAC,GAC7G;AAEE,UAAM,IAAI,MAAM,+CAA+C;AAAA,EACnE;AAEA,QAAM,qBAAqB,MAAM,OAAO,OAAO;AAAA,IAC3C;AAAA,IACA,IAAI,WAAW,CAAC,GAAG,OAAO,WAAW,GAAG,GAAG,WAAW,GAAG,mBAAmB,CAAC;AAAA,EACjF;AACA,QAAM,eAAe,IAAI,WAAW,kBAAkB;AAEtD,SAAO,OAAO,YAAY;AAC9B;;;AC7JA,eAAsB,wBAAwB,WAAwC;AAClF,QAAM,6BAA6B;AACnC,MAAI,UAAU,SAAS,YAAY,UAAU,UAAU,SAAS,WAAW;AAEvE,UAAM,IAAI,MAAM,iDAAiD;AAAA,EACrE;AACA,QAAM,iBAAiB,MAAM,OAAO,OAAO,UAAU,OAAO,SAAS;AACrE,SAAO,kBAAkB,EAAE,OAAO,IAAI,WAAW,cAAc,CAAC;AACpE","sourcesContent":["/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","/**\n * Defines an offset in bytes.\n */\nexport type Offset = number;\n\ntype BaseEncoder<TFrom> = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => Uint8Array;\n /**\n * Writes the encoded value into the provided byte array at the given offset.\n * Returns the offset of the next byte after the encoded value.\n */\n readonly write: (value: TFrom, bytes: Uint8Array, offset: Offset) => Offset;\n};\n\nexport type FixedSizeEncoder<TFrom, TSize extends number = number> = BaseEncoder<TFrom> & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\nexport type VariableSizeEncoder<TFrom> = BaseEncoder<TFrom> & {\n /** The total size of the encoded value in bytes. */\n readonly getSizeFromValue: (value: TFrom) => number;\n /** The maximum size an encoded value can be in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can encode a value to a `Uint8Array`.\n */\nexport type Encoder<TFrom> = FixedSizeEncoder<TFrom> | VariableSizeEncoder<TFrom>;\n\ntype BaseDecoder<TTo> = {\n /** Decodes the provided byte array at the given offset (or zero) and returns the value directly. */\n readonly decode: (bytes: Uint8Array, offset?: Offset) => TTo;\n /**\n * Reads the encoded value from the provided byte array at the given offset.\n * Returns the decoded value and the offset of the next byte after the encoded value.\n */\n readonly read: (bytes: Uint8Array, offset: Offset) => [TTo, Offset];\n};\n\nexport type FixedSizeDecoder<TTo, TSize extends number = number> = BaseDecoder<TTo> & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\nexport type VariableSizeDecoder<TTo> = BaseDecoder<TTo> & {\n /** The maximum size an encoded value can be in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can decode a value from a `Uint8Array`.\n */\nexport type Decoder<TTo> = FixedSizeDecoder<TTo> | VariableSizeDecoder<TTo>;\n\nexport type FixedSizeCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number> = FixedSizeEncoder<\n TFrom,\n TSize\n> &\n FixedSizeDecoder<TTo, TSize>;\n\nexport type VariableSizeCodec<TFrom, TTo extends TFrom = TFrom> = VariableSizeEncoder<TFrom> & VariableSizeDecoder<TTo>;\n\n/**\n * An object that can encode and decode a value to and from a `Uint8Array`.\n * It supports encoding looser types than it decodes for convenience.\n * For example, a `bigint` encoder will always decode to a `bigint`\n * but can be used to encode a `number`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value. Defaults to `TFrom`.\n */\nexport type Codec<TFrom, TTo extends TFrom = TFrom> = FixedSizeCodec<TFrom, TTo> | VariableSizeCodec<TFrom, TTo>;\n\n/**\n * Get the encoded size of a given value in bytes.\n */\nexport function getEncodedSize<TFrom>(\n value: TFrom,\n encoder: { fixedSize: number } | { getSizeFromValue: (value: TFrom) => number }\n): number {\n return 'fixedSize' in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);\n}\n\n/** Fills the missing `encode` function using the existing `write` function. */\nexport function createEncoder<TFrom, TSize extends number>(\n encoder: Omit<FixedSizeEncoder<TFrom, TSize>, 'encode'>\n): FixedSizeEncoder<TFrom, TSize>;\nexport function createEncoder<TFrom>(encoder: Omit<VariableSizeEncoder<TFrom>, 'encode'>): VariableSizeEncoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>\n): Encoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>\n): Encoder<TFrom> {\n return Object.freeze({\n ...encoder,\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, encoder));\n encoder.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/** Fills the missing `decode` function using the existing `read` function. */\nexport function createDecoder<TTo, TSize extends number>(\n decoder: Omit<FixedSizeDecoder<TTo, TSize>, 'decode'>\n): FixedSizeDecoder<TTo, TSize>;\nexport function createDecoder<TTo>(decoder: Omit<VariableSizeDecoder<TTo>, 'decode'>): VariableSizeDecoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>\n): Decoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>\n): Decoder<TTo> {\n return Object.freeze({\n ...decoder,\n decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0],\n });\n}\n\n/** Fills the missing `encode` and `decode` function using the existing `write` and `read` functions. */\nexport function createCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number>(\n codec: Omit<FixedSizeCodec<TFrom, TTo, TSize>, 'encode' | 'decode'>\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec: Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n): VariableSizeCodec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n): Codec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n): Codec<TFrom, TTo> {\n return Object.freeze({\n ...codec,\n decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, codec));\n codec.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\nexport function isFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>\n): encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function isFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>\n): decoder is FixedSizeDecoder<TTo, TSize>;\nexport function isFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>\n): codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function isFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number }\n): codec is { fixedSize: TSize };\nexport function isFixedSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { fixedSize: number } {\n return 'fixedSize' in codec && typeof codec.fixedSize === 'number';\n}\n\nexport function assertIsFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n message?: string\n): asserts encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function assertIsFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n message?: string\n): asserts decoder is FixedSizeDecoder<TTo, TSize>;\nexport function assertIsFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n message?: string\n): asserts codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function assertIsFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number },\n message?: string\n): asserts codec is { fixedSize: TSize };\nexport function assertIsFixedSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string\n): asserts codec is { fixedSize: number } {\n if (!isFixedSize(codec)) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n\nexport function isVariableSize<TFrom>(encoder: Encoder<TFrom>): encoder is VariableSizeEncoder<TFrom>;\nexport function isVariableSize<TTo>(decoder: Decoder<TTo>): decoder is VariableSizeDecoder<TTo>;\nexport function isVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>\n): codec is VariableSizeCodec<TFrom, TTo>;\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number };\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number } {\n return !isFixedSize(codec);\n}\n\nexport function assertIsVariableSize<T>(\n encoder: Encoder<T>,\n message?: string\n): asserts encoder is VariableSizeEncoder<T>;\nexport function assertIsVariableSize<T>(\n decoder: Decoder<T>,\n message?: string\n): asserts decoder is VariableSizeDecoder<T>;\nexport function assertIsVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n message?: string\n): asserts codec is VariableSizeCodec<TFrom, TTo>;\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string\n): asserts codec is { maxSize?: number };\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string\n): asserts codec is { maxSize?: number } {\n if (!isVariableSize(codec)) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a variable-size codec, got a fixed-size one.');\n }\n}\n","import {\n Codec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\n\n/**\n * Combines an encoder and a decoder into a codec.\n * The encoder and decoder must have the same fixed size, max size and description.\n * If a description is provided, it will override the encoder and decoder descriptions.\n */\nexport function combineCodec<TFrom, TTo extends TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize>,\n decoder: FixedSizeDecoder<TTo, TSize>\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: VariableSizeEncoder<TFrom>,\n decoder: VariableSizeDecoder<TTo>\n): VariableSizeCodec<TFrom, TTo>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: Encoder<TFrom>,\n decoder: Decoder<TTo>\n): Codec<TFrom, TTo>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: Encoder<TFrom>,\n decoder: Decoder<TTo>\n): Codec<TFrom, TTo> {\n if (isFixedSize(encoder) !== isFixedSize(decoder)) {\n // TODO: Coded error.\n throw new Error(`Encoder and decoder must either both be fixed-size or variable-size.`);\n }\n\n if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`\n );\n }\n\n if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`\n );\n }\n\n return {\n ...decoder,\n ...encoder,\n decode: decoder.decode,\n encode: encoder.encode,\n read: decoder.read,\n write: encoder.write,\n };\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n Offset,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n */\nexport function fixEncoder<TFrom, TSize extends number>(\n encoder: Encoder<TFrom>,\n fixedBytes: TSize\n): FixedSizeEncoder<TFrom, TSize> {\n return createEncoder({\n fixedSize: fixedBytes,\n write: (value: TFrom, bytes: Uint8Array, offset: Offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function as using the nested `write` function on a fixed-sized byte\n // array may result in a out-of-bounds error on the nested encoder.\n const variableByteArray = encoder.encode(value);\n const fixedByteArray =\n variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;\n bytes.set(fixedByteArray, offset);\n return offset + fixedBytes;\n },\n });\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n */\nexport function fixDecoder<TTo, TSize extends number>(\n decoder: Decoder<TTo>,\n fixedBytes: TSize\n): FixedSizeDecoder<TTo, TSize> {\n return createDecoder({\n fixedSize: fixedBytes,\n read: (bytes: Uint8Array, offset: Offset) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodec', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (isFixedSize(decoder)) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.read(bytes, 0);\n return [value, offset + fixedBytes];\n },\n });\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n */\nexport function fixCodec<TFrom, TTo extends TFrom, TSize extends number>(\n codec: Codec<TFrom, TTo>,\n fixedBytes: TSize\n): FixedSizeCodec<TFrom, TTo, TSize> {\n return combineCodec(fixEncoder(codec, fixedBytes), fixDecoder(codec, fixedBytes));\n}\n","import {\n Codec,\n createCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isVariableSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\n\n/**\n * Converts an encoder A to a encoder B by mapping their values.\n */\nexport function mapEncoder<TOldFrom, TNewFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TOldFrom, TSize>,\n unmap: (value: TNewFrom) => TOldFrom\n): FixedSizeEncoder<TNewFrom, TSize>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: VariableSizeEncoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom\n): VariableSizeEncoder<TNewFrom>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom\n): Encoder<TNewFrom>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom\n): Encoder<TNewFrom> {\n return createEncoder({\n ...(isVariableSize(encoder)\n ? { ...encoder, getSizeFromValue: (value: TNewFrom) => encoder.getSizeFromValue(unmap(value)) }\n : encoder),\n write: (value: TNewFrom, bytes, offset) => encoder.write(unmap(value), bytes, offset),\n });\n}\n\n/**\n * Converts an decoder A to a decoder B by mapping their values.\n */\nexport function mapDecoder<TOldTo, TNewTo, TSize extends number>(\n decoder: FixedSizeDecoder<TOldTo, TSize>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): FixedSizeDecoder<TNewTo, TSize>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: VariableSizeDecoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): VariableSizeDecoder<TNewTo>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): Decoder<TNewTo>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): Decoder<TNewTo> {\n return createDecoder({\n ...decoder,\n read: (bytes: Uint8Array, offset) => {\n const [value, newOffset] = decoder.read(bytes, offset);\n return [map(value, bytes, offset), newOffset];\n },\n });\n}\n\n/**\n * Converts a codec A to a codec B by mapping their values.\n */\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom, TSize extends number>(\n codec: FixedSizeCodec<TOldFrom, TTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom\n): FixedSizeCodec<TNewFrom, TTo, TSize>;\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: VariableSizeCodec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom\n): VariableSizeCodec<TNewFrom, TTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: Codec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom\n): Codec<TNewFrom, TTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom, TSize extends number>(\n codec: FixedSizeCodec<TOldFrom, TOldTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): FixedSizeCodec<TNewFrom, TNewTo, TSize>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: VariableSizeCodec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): VariableSizeCodec<TNewFrom, TNewTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): Codec<TNewFrom, TNewTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map?: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo\n): Codec<TNewFrom, TNewTo> {\n return createCodec({\n ...mapEncoder(codec, unmap),\n read: map ? mapDecoder(codec, map).read : (codec.read as unknown as Decoder<TNewTo>['read']),\n });\n}\n","/**\n * Asserts that a given number is between a given range.\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint,\n) {\n if (value < min || value > max) {\n // TODO: Coded error.\n throw new Error(\n `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`,\n );\n }\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getF32Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<number, 4> =>\n numberEncoderFactory({\n config,\n name: 'f32',\n set: (view, value, le) => view.setFloat32(0, value, le),\n size: 4,\n });\n\nexport const getF32Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder<number, 4> =>\n numberDecoderFactory({\n config,\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n size: 4,\n });\n\nexport const getF32Codec = (config: NumberCodecConfig = {}): FixedSizeCodec<number, number, 4> =>\n combineCodec(getF32Encoder(config), getF32Decoder(config));\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n createDecoder,\n createEncoder,\n FixedSizeDecoder,\n FixedSizeEncoder,\n Offset,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecConfig } from './common';\n\ntype NumberFactorySharedInput<TSize extends number> = {\n name: string;\n size: TSize;\n config?: NumberCodecConfig;\n};\n\ntype NumberFactoryEncoderInput<TFrom, TSize extends number> = NumberFactorySharedInput<TSize> & {\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: TFrom, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput<TTo, TSize extends number> = NumberFactorySharedInput<TSize> & {\n get: (view: DataView, littleEndian?: boolean) => TTo;\n};\n\nfunction isLittleEndian(config?: NumberCodecConfig): boolean {\n return config?.endian === Endian.BIG ? false : true;\n}\n\nexport function numberEncoderFactory<TFrom extends number | bigint, TSize extends number>(\n input: NumberFactoryEncoderInput<TFrom, TSize>\n): FixedSizeEncoder<TFrom, TSize> {\n return createEncoder({\n fixedSize: input.size,\n write(value: TFrom, bytes: Uint8Array, offset: Offset): Offset {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));\n bytes.set(new Uint8Array(arrayBuffer), offset);\n return offset + input.size;\n },\n });\n}\n\nexport function numberDecoderFactory<TTo extends number | bigint, TSize extends number>(\n input: NumberFactoryDecoderInput<TTo, TSize>\n): FixedSizeDecoder<TTo, TSize> {\n return createDecoder({\n fixedSize: input.size,\n read(bytes, offset = 0): [TTo, number] {\n assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, isLittleEndian(input.config)), offset + input.size];\n },\n });\n}\n\n/**\n * Helper function to ensure that the ArrayBuffer is converted properly from a Uint8Array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n */\nfunction toArrayBuffer(bytes: Uint8Array, offset?: number, length?: number): ArrayBuffer {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n","import { combineCodec, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';\n\nimport { NumberCodecConfig } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU128Encoder = (config: NumberCodecConfig = {}): FixedSizeEncoder<number | bigint, 16> =>\n numberEncoderFactory({\n config,\n name: 'u128',\n range: [0, BigInt('0xffffffffffffffffffffffffffffffff')],\n set: (view, value, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const rightMask = 0xffffffffffffffffn;\n view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);\n view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);\n },\n size: 16,\n });\n\nexport const getU128Decoder = (config: NumberCodecConfig = {}): FixedSizeDecoder<bigint, 16> =>\n numberDecoderFactory({\n config,\n get: (view, le) => {\n const leftOffset = le ? 8 : 0;\n const rightOffset = le ? 0 : 8;\n const left = view.getBigUint64(leftOffset, le);\n const right = view.getBigUint64(rightOffset, le);\n return (left << 64n) + right;\n },\n name: 'u128',\n size: 16,\n });\n\nexport const getU128Codec = (config: NumberCodecConfig = {}): FixedSizeCodec<number | bigint, bigint, 16> =>\n combineCodec(getU128Encoder(config), getU128Decoder(config));\n","import { createEncoder, createDecoder, combineCodec, fixEncoder, getEncodedSize, fixDecoder, assertByteArrayIsNotEmptyForCodec, assertByteArrayHasEnoughBytesForCodec } from '@solana/codecs-core';\nimport { getU32Encoder, getU32Decoder } from '@solana/codecs-numbers';\n\n// src/assertions.ts\nfunction assertValidBaseString(alphabet4, testValue, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {\n throw new Error(`Expected a string of base ${alphabet4.length}, got [${givenValue}].`);\n }\n}\nvar getBaseXEncoder = (alphabet4) => {\n return createEncoder({\n getSizeFromValue: (value) => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);\n if (tailChars === \"\")\n return value.length;\n const base10Number = getBigIntFromBaseX(tailChars, alphabet4);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value, bytes, offset) {\n assertValidBaseString(alphabet4, value);\n if (value === \"\")\n return offset;\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);\n if (tailChars === \"\") {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n let base10Number = getBigIntFromBaseX(tailChars, alphabet4);\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n }\n });\n};\nvar getBaseXDecoder = (alphabet4) => {\n return createDecoder({\n read(rawBytes, offset) {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0)\n return [\"\", 0];\n let trailIndex = bytes.findIndex((n) => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet4[0].repeat(trailIndex);\n if (trailIndex === bytes.length)\n return [leadingZeroes, rawBytes.length];\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n const tailChars = getBaseXFromBigInt(base10Number, alphabet4);\n return [leadingZeroes + tailChars, rawBytes.length];\n }\n });\n};\nvar getBaseXCodec = (alphabet4) => combineCodec(getBaseXEncoder(alphabet4), getBaseXDecoder(alphabet4));\nfunction partitionLeadingZeroes(value, zeroCharacter) {\n const leadingZeroIndex = [...value].findIndex((c) => c !== zeroCharacter);\n return leadingZeroIndex === -1 ? [value, \"\"] : [value.slice(0, leadingZeroIndex), value.slice(leadingZeroIndex)];\n}\nfunction getBigIntFromBaseX(value, alphabet4) {\n const base = BigInt(alphabet4.length);\n return [...value].reduce((sum, char) => sum * base + BigInt(alphabet4.indexOf(char)), 0n);\n}\nfunction getBaseXFromBigInt(value, alphabet4) {\n const base = BigInt(alphabet4.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet4[Number(value % base)]);\n value /= base;\n }\n return tailChars.join(\"\");\n}\n\n// src/base10.ts\nvar alphabet = \"0123456789\";\nvar getBase10Encoder = () => getBaseXEncoder(alphabet);\nvar getBase10Decoder = () => getBaseXDecoder(alphabet);\nvar getBase10Codec = () => getBaseXCodec(alphabet);\nvar getBase16Encoder = () => createEncoder({\n getSizeFromValue: (value) => Math.ceil(value.length / 2),\n write(value, bytes, offset) {\n const lowercaseValue = value.toLowerCase();\n assertValidBaseString(\"0123456789abcdef\", lowercaseValue, value);\n const matches = lowercaseValue.match(/.{1,2}/g);\n const hexBytes = matches ? matches.map((byte) => parseInt(byte, 16)) : [];\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n }\n});\nvar getBase16Decoder = () => createDecoder({\n read(bytes, offset) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, \"0\"), \"\");\n return [value, bytes.length];\n }\n});\nvar getBase16Codec = () => combineCodec(getBase16Encoder(), getBase16Decoder());\n\n// src/base58.ts\nvar alphabet2 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\nvar getBase58Encoder = () => getBaseXEncoder(alphabet2);\nvar getBase58Decoder = () => getBaseXDecoder(alphabet2);\nvar getBase58Codec = () => getBaseXCodec(alphabet2);\nvar getBaseXResliceEncoder = (alphabet4, bits) => createEncoder({\n getSizeFromValue: (value) => Math.floor(value.length * bits / 8),\n write(value, bytes, offset) {\n assertValidBaseString(alphabet4, value);\n if (value === \"\")\n return offset;\n const charIndices = [...value].map((c) => alphabet4.indexOf(c));\n const reslicedBytes = reslice(charIndices, bits, 8, false);\n bytes.set(reslicedBytes, offset);\n return reslicedBytes.length + offset;\n }\n});\nvar getBaseXResliceDecoder = (alphabet4, bits) => createDecoder({\n read(rawBytes, offset = 0) {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0)\n return [\"\", rawBytes.length];\n const charIndices = reslice([...bytes], 8, bits, true);\n return [charIndices.map((i) => alphabet4[i]).join(\"\"), rawBytes.length];\n }\n});\nvar getBaseXResliceCodec = (alphabet4, bits) => combineCodec(getBaseXResliceEncoder(alphabet4, bits), getBaseXResliceDecoder(alphabet4, bits));\nfunction reslice(input, inputBits, outputBits, useRemainder) {\n const output = [];\n let accumulator = 0;\n let bitsInAccumulator = 0;\n const mask = (1 << outputBits) - 1;\n for (const value of input) {\n accumulator = accumulator << inputBits | value;\n bitsInAccumulator += inputBits;\n while (bitsInAccumulator >= outputBits) {\n bitsInAccumulator -= outputBits;\n output.push(accumulator >> bitsInAccumulator & mask);\n }\n }\n if (useRemainder && bitsInAccumulator > 0) {\n output.push(accumulator << outputBits - bitsInAccumulator & mask);\n }\n return output;\n}\nvar getBase64Encoder = () => {\n {\n return createEncoder({\n getSizeFromValue: (value) => {\n try {\n return atob(value).length;\n } catch (e2) {\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n write(value, bytes, offset) {\n try {\n const bytesToAdd = atob(value).split(\"\").map((c) => c.charCodeAt(0));\n bytes.set(bytesToAdd, offset);\n return bytesToAdd.length + offset;\n } catch (e2) {\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n }\n });\n }\n};\nvar getBase64Decoder = () => {\n {\n return createDecoder({\n read(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = btoa(String.fromCharCode(...slice));\n return [value, bytes.length];\n }\n });\n }\n};\nvar getBase64Codec = () => combineCodec(getBase64Encoder(), getBase64Decoder());\n\n// src/null-characters.ts\nvar removeNullCharacters = (value) => (\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, \"\")\n);\nvar padNullCharacters = (value, chars) => value.padEnd(chars, \"\\0\");\n\n// ../text-encoding-impl/dist/index.browser.js\nvar e = globalThis.TextDecoder;\nvar o = globalThis.TextEncoder;\n\n// src/utf8.ts\nvar getUtf8Encoder = () => {\n let textEncoder;\n return createEncoder({\n getSizeFromValue: (value) => (textEncoder ||= new o()).encode(value).length,\n write: (value, bytes, offset) => {\n const bytesToAdd = (textEncoder ||= new o()).encode(value);\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n }\n });\n};\nvar getUtf8Decoder = () => {\n let textDecoder;\n return createDecoder({\n read(bytes, offset) {\n const value = (textDecoder ||= new e()).decode(bytes.slice(offset));\n return [removeNullCharacters(value), bytes.length];\n }\n });\n};\nvar getUtf8Codec = () => combineCodec(getUtf8Encoder(), getUtf8Decoder());\n\n// src/string.ts\nfunction getStringEncoder(config = {}) {\n const size = config.size ?? getU32Encoder();\n const encoding = config.encoding ?? getUtf8Encoder();\n if (size === \"variable\") {\n return encoding;\n }\n if (typeof size === \"number\") {\n return fixEncoder(encoding, size);\n }\n return createEncoder({\n getSizeFromValue: (value) => {\n const contentSize = getEncodedSize(value, encoding);\n return getEncodedSize(contentSize, size) + contentSize;\n },\n write: (value, bytes, offset) => {\n const contentSize = getEncodedSize(value, encoding);\n offset = size.write(contentSize, bytes, offset);\n return encoding.write(value, bytes, offset);\n }\n });\n}\nfunction getStringDecoder(config = {}) {\n const size = config.size ?? getU32Decoder();\n const encoding = config.encoding ?? getUtf8Decoder();\n if (size === \"variable\") {\n return encoding;\n }\n if (typeof size === \"number\") {\n return fixDecoder(encoding, size);\n }\n return createDecoder({\n read: (bytes, offset = 0) => {\n assertByteArrayIsNotEmptyForCodec(\"string\", bytes, offset);\n const [lengthBigInt, lengthOffset] = size.read(bytes, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBytes = bytes.slice(offset, offset + length);\n assertByteArrayHasEnoughBytesForCodec(\"string\", length, contentBytes);\n const [value, contentOffset] = encoding.read(contentBytes, 0);\n offset += contentOffset;\n return [value, offset];\n }\n });\n}\nfunction getStringCodec(config = {}) {\n return combineCodec(getStringEncoder(config), getStringDecoder(config));\n}\n\nexport { assertValidBaseString, getBase10Codec, getBase10Decoder, getBase10Encoder, getBase16Codec, getBase16Decoder, getBase16Encoder, getBase58Codec, getBase58Decoder, getBase58Encoder, getBase64Codec, getBase64Decoder, getBase64Encoder, getBaseXCodec, getBaseXDecoder, getBaseXEncoder, getBaseXResliceCodec, getBaseXResliceDecoder, getBaseXResliceEncoder, getStringCodec, getStringDecoder, getStringEncoder, getUtf8Codec, getUtf8Decoder, getUtf8Encoder, padNullCharacters, removeNullCharacters };\n","import {\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n mapEncoder,\n} from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\n\nexport type Address<TAddress extends string = string> = TAddress & {\n readonly __brand: unique symbol;\n};\n\nlet memoizedBase58Encoder: Encoder<string> | undefined;\nlet memoizedBase58Decoder: Decoder<string> | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder<string> {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder<string> {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\nexport function isAddress(putativeAddress: string): putativeAddress is Address<typeof putativeAddress> {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\n\nexport function assertIsAddress(putativeAddress: string): asserts putativeAddress is Address<typeof putativeAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function address<TAddress extends string = string>(putativeAddress: TAddress): Address<TAddress> {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address<TAddress>;\n}\n\nexport function getAddressEncoder(): FixedSizeEncoder<Address, 32> {\n return mapEncoder(getStringEncoder({ encoding: getMemoizedBase58Encoder(), size: 32 }), putativeAddress =>\n address(putativeAddress),\n );\n}\n\nexport function getAddressDecoder(): FixedSizeDecoder<Address, 32> {\n return getStringDecoder({ encoding: getMemoizedBase58Decoder(), size: 32 }) as FixedSizeDecoder<Address, 32>;\n}\n\nexport function getAddressCodec(): FixedSizeCodec<Address, Address, 32> {\n return combineCodec(getAddressEncoder(), getAddressDecoder());\n}\n\nexport function getAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","function assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n // TODO: Coded error.\n throw new Error(\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts',\n );\n }\n}\n\nlet cachedEd25519Decision: PromiseLike<boolean> | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise<boolean> {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n })\n .then(() => {\n resolve((cachedEd25519Decision = true));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\nexport async function assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n // TODO: Coded error.\n throw new Error('No digest implementation could be found');\n }\n}\n\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key generation implementation could be found');\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n // TODO: Coded error.\n throw new Error(\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall and ' +\n 'import `@solana/webcrypto-ed25519-polyfill` before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20',\n );\n }\n}\n\nexport async function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key export implementation could be found');\n }\n}\n\nexport async function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n // TODO: Coded error.\n throw new Error('No signing implementation could be found');\n }\n}\n\nexport async function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n // TODO: Coded error.\n throw new Error('No signature verification implementation could be found');\n }\n}\n","/**!\n * noble-ed25519\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Paul Miller (https://paulmillr.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the “Software”), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nconst D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nconst P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; // 2n ** 255n - 19n; ed25519 is twisted edwards curve\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1\n\n// mod division\nfunction mod(a: bigint): bigint {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x: bigint, power: bigint): bigint {\n // pow2(x, 4) == x^(2^4)\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x: bigint): bigint {\n // x^(2^252-3) unrolled util for square root\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return pow_p_5_8;\n}\nfunction uvRatio(u: bigint, v: bigint): bigint | null {\n // for sqrt comp\n const v3 = mod(v * v * v); // v³\n const v7 = mod(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7); // (uv⁷)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n) x = mod(-x); // edIsNegative\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\n// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.3\nexport function pointIsOnCurve(y: bigint, lastByte: number): boolean {\n const y2 = mod(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n","import { pointIsOnCurve } from './vendor/noble/ed25519';\n\nfunction byteToHex(byte: number): string {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\n\nfunction decompressPointBytes(bytes: Uint8Array): bigint {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~0x80 : byte)}${acc}`, '');\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\n\nexport async function compressedPointBytesAreOnCurve(bytes: Uint8Array): Promise<boolean> {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n","import { assertDigestCapabilityIsAvailable } from '@solana/assertions';\n\nimport { Address, assertIsAddress, getAddressCodec, isAddress } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve';\n\n/**\n * An address derived from a program address and a set of seeds.\n * It includes the bump seed used to derive the address and\n * ensure the address is not on the Ed25519 curve.\n */\nexport type ProgramDerivedAddress<TAddress extends string = string> = Readonly<\n [Address<TAddress>, ProgramDerivedAddressBump]\n>;\n\n/**\n * A number between 0 and 255, inclusive.\n */\nexport type ProgramDerivedAddressBump = number & {\n readonly __brand: unique symbol;\n};\n\n/**\n * Returns true if the input value is a program derived address.\n */\nexport function isProgramDerivedAddress<TAddress extends string = string>(\n value: unknown,\n): value is ProgramDerivedAddress<TAddress> {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'string' &&\n typeof value[1] === 'number' &&\n value[1] >= 0 &&\n value[1] <= 255 &&\n isAddress(value[0])\n );\n}\n\n/**\n * Fails if the input value is not a program derived address.\n */\nexport function assertIsProgramDerivedAddress<TAddress extends string = string>(\n value: unknown,\n): asserts value is ProgramDerivedAddress<TAddress> {\n const validFormat =\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number';\n if (!validFormat) {\n // TODO: Coded error.\n throw new Error(\n `Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].`,\n );\n }\n if (value[1] < 0 || value[1] > 255) {\n // TODO: Coded error.\n throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);\n }\n assertIsAddress(value[0]);\n}\n\ntype ProgramDerivedAddressInput = Readonly<{\n programAddress: Address;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Address;\n programAddress: Address;\n seed: Seed;\n}>;\n\ntype Seed = string | Uint8Array;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\n// TODO: Coded error.\nclass PointOnCurveError extends Error {}\n\nasync function createProgramDerivedAddress({ programAddress, seeds }: ProgramDerivedAddressInput): Promise<Address> {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n // TODO: Coded error.\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES]),\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (await compressedPointBytesAreOnCurve(addressBytes)) {\n // TODO: Coded error.\n throw new PointOnCurveError('Invalid seeds; point must fall off the Ed25519 curve');\n }\n return base58EncodedAddressCodec.decode(addressBytes);\n}\n\nexport async function getProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise<ProgramDerivedAddress> {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])],\n });\n return [address, bumpSeed as ProgramDerivedAddressBump];\n } catch (e) {\n if (e instanceof PointOnCurveError) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n // TODO: Coded error.\n throw new Error('Unable to find a viable program address bump seed');\n}\n\nexport async function createAddressWithSeed({ baseAddress, programAddress, seed }: SeedInput): Promise<Address> {\n const { encode, decode } = getAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed exceeds the maximum length of 32 bytes`);\n }\n\n const programAddressBytes = encode(programAddress);\n if (\n programAddressBytes.length >= PDA_MARKER_BYTES.length &&\n programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])\n ) {\n // TODO: Coded error.\n throw new Error(`programAddress cannot end with the PDA marker`);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes]),\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return decode(addressBytes);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\n\nimport { Address, getAddressDecoder } from './address';\n\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Address> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n // TODO: Coded error.\n throw new Error('The `CryptoKey` must be an `Ed25519` public key');\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n}\n"]}
@@ -1,22 +0,0 @@
1
- this.globalThis = this.globalThis || {};
2
- this.globalThis.solanaWeb3 = (function (exports) {
3
- 'use strict';
4
-
5
- function E(e,r,t=0){if(r.length-t<=0)throw new Error(`Codec [${e}] cannot decode empty byte arrays.`)}function x(e,r,t,n=0){let o=t.length-n;if(o<r)throw new Error(`Codec [${e}] expected ${r} bytes, got ${o}.`)}var re=(e,r)=>{if(e.length>=r)return e;let t=new Uint8Array(r).fill(0);return t.set(e),t},te=(e,r)=>re(e.length<=r?e:e.slice(0,r),r);function w(e,r){return "fixedSize"in r?r.fixedSize:r.getSizeFromValue(e)}function p(e){return Object.freeze({...e,encode:r=>{let t=new Uint8Array(w(r,e));return e.write(r,t,0),t}})}function b(e){return Object.freeze({...e,decode:(r,t=0)=>e.read(r,t)[0]})}function y(e){return "fixedSize"in e&&typeof e.fixedSize=="number"}function ne(e){return !y(e)}function A(e,r){if(y(e)!==y(r))throw new Error("Encoder and decoder must either both be fixed-size or variable-size.");if(y(e)&&y(r)&&e.fixedSize!==r.fixedSize)throw new Error(`Encoder and decoder must have the same fixed size, got [${e.fixedSize}] and [${r.fixedSize}].`);if(!y(e)&&!y(r)&&e.maxSize!==r.maxSize)throw new Error(`Encoder and decoder must have the same max size, got [${e.maxSize}] and [${r.maxSize}].`);return {...r,...e,decode:r.decode,encode:e.encode,read:r.read,write:e.write}}function T(e,r){return p({fixedSize:r,write:(t,n,o)=>{let s=e.encode(t),i=s.length>r?s.slice(0,r):s;return n.set(i,o),o+r}})}function N(e,r){return b({fixedSize:r,read:(t,n)=>{x("fixCodec",r,t,n),(n>0||t.length>r)&&(t=t.slice(n,n+r)),y(e)&&(t=te(t,e.fixedSize));let[o]=e.read(t,0);return [o,n+r]}})}function P(e,r){return p({...ne(e)?{...e,getSizeFromValue:t=>e.getSizeFromValue(r(t))}:e,write:(t,n,o)=>e.write(r(t),n,o)})}function oe(e,r,t,n){if(n<r||n>t)throw new Error(`Codec [${e}] expected number to be in the range [${r}, ${t}], got ${n}.`)}function $(e){return (e==null?void 0:e.endian)!==1}function se(e){return p({fixedSize:e.size,write(r,t,n){e.range&&oe(e.name,e.range[0],e.range[1],r);let o=new ArrayBuffer(e.size);return e.set(new DataView(o),r,$(e.config)),t.set(new Uint8Array(o),n),n+e.size}})}function ie(e){return b({fixedSize:e.size,read(r,t=0){E(e.name,r,t),x(e.name,e.size,r,t);let n=new DataView(ae(r,t,e.size));return [e.get(n,$(e.config)),t+e.size]}})}function ae(e,r,t){let n=e.byteOffset+(r!=null?r:0),o=t!=null?t:e.byteLength;return e.buffer.slice(n,n+o)}var O=(e={})=>se({config:e,name:"u32",range:[0,+"0xffffffff"],set:(r,t,n)=>r.setUint32(0,t,n),size:4}),_=(e={})=>ie({config:e,get:(r,t)=>r.getUint32(0,t),name:"u32",size:4});function de(e,r,t=r){if(!r.match(new RegExp(`^[${e}]*$`)))throw new Error(`Expected a string of base ${e.length}, got [${t}].`)}var ce=e=>p({getSizeFromValue:r=>{let[t,n]=L(r,e[0]);if(n==="")return r.length;let o=V(n,e);return t.length+Math.ceil(o.toString(16).length/2)},write(r,t,n){if(de(e,r),r==="")return n;let[o,s]=L(r,e[0]);if(s==="")return t.set(new Uint8Array(o.length).fill(0),n),n+o.length;let i=V(s,e),d=[];for(;i>0n;)d.unshift(Number(i%256n)),i/=256n;let a=[...Array(o.length).fill(0),...d];return t.set(a,n),n+a.length}}),fe=e=>b({read(r,t){let n=t===0?r:r.slice(t);if(n.length===0)return ["",0];let o=n.findIndex(a=>a!==0);o=o===-1?n.length:o;let s=e[0].repeat(o);if(o===n.length)return [s,r.length];let i=n.slice(o).reduce((a,c)=>a*256n+BigInt(c),0n),d=ge(i,e);return [s+d,r.length]}});function L(e,r){let t=[...e].findIndex(n=>n!==r);return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]}function V(e,r){let t=BigInt(r.length);return [...e].reduce((n,o)=>n*t+BigInt(r.indexOf(o)),0n)}function ge(e,r){let t=BigInt(r.length),n=[];for(;e>0n;)n.unshift(r[Number(e%t)]),e/=t;return n.join("")}var k="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",M=()=>ce(k),K=()=>fe(k);var ue=e=>e.replace(/\u0000/g,"");var le=globalThis.TextDecoder,R=globalThis.TextEncoder,me=()=>{let e;return p({getSizeFromValue:r=>(e||(e=new R)).encode(r).length,write:(r,t,n)=>{let o=(e||(e=new R)).encode(r);return t.set(o,n),n+o.length}})},he=()=>{let e;return b({read(r,t){let n=(e||(e=new le)).decode(r.slice(t));return [ue(n),r.length]}})};function X(e={}){var n,o;let r=(n=e.size)!=null?n:O(),t=(o=e.encoding)!=null?o:me();return r==="variable"?t:typeof r=="number"?T(t,r):p({getSizeFromValue:s=>{let i=w(s,t);return w(i,r)+i},write:(s,i,d)=>{let a=w(s,t);return d=r.write(a,i,d),t.write(s,i,d)}})}function H(e={}){var n,o;let r=(n=e.size)!=null?n:_(),t=(o=e.encoding)!=null?o:he();return r==="variable"?t:typeof r=="number"?N(t,r):b({read:(s,i=0)=>{E("string",s,i);let[d,a]=r.read(s,i),c=Number(d);i=a;let u=s.slice(i,i+c);x("string",c,u);let[h,F]=t.read(u,0);return i+=F,[h,i]}})}var B,I;function S(){return B||(B=M()),B}function ye(){return I||(I=K()),I}function j(e){return !(e.length<32||e.length>44||S().encode(e).byteLength!==32)}function C(e){try{if(e.length<32||e.length>44)throw new Error("Expected input string to decode to a byte array of length 32.");let n=S().encode(e).byteLength;if(n!==32)throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${n}`)}catch(r){throw new Error(`\`${e}\` is not a base-58 encoded address`,{cause:r})}}function pe(e){return C(e),e}function be(){return P(X({encoding:S(),size:32}),e=>pe(e))}function D(){return H({encoding:ye(),size:32})}function U(){return A(be(),D())}function Me(){return new Intl.Collator("en",{caseFirst:"lower",ignorePunctuation:!1,localeMatcher:"best fit",numeric:!1,sensitivity:"variant",usage:"sort"}).compare}function G(){if(!globalThis.isSecureContext)throw new Error("Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts")}async function Z(){var e;if(G(),typeof globalThis.crypto>"u"||typeof((e=globalThis.crypto.subtle)==null?void 0:e.digest)!="function")throw new Error("No digest implementation could be found")}async function W(){var e;if(G(),typeof globalThis.crypto>"u"||typeof((e=globalThis.crypto.subtle)==null?void 0:e.exportKey)!="function")throw new Error("No key export implementation could be found")}var xe=37095705934669439343138083508754565189542113879843219016388785533085940283555n,f=57896044618658097711785492504343953926634992332820282019728792003956564819949n,q=19681161376707505956807079304988542015446066515923890162744021073123829784752n;function g(e){let r=e%f;return r>=0n?r:f+r}function l(e,r){let t=e;for(;r-- >0n;)t*=t,t%=f;return t}function we(e){let t=e*e%f*e%f,n=l(t,2n)*t%f,o=l(n,1n)*e%f,s=l(o,5n)*o%f,i=l(s,10n)*s%f,d=l(i,20n)*i%f,a=l(d,40n)*d%f,c=l(a,80n)*a%f,u=l(c,80n)*a%f,h=l(u,10n)*s%f;return l(h,2n)*e%f}function Ee(e,r){let t=g(r*r*r),n=g(t*t*r),o=we(e*n),s=g(e*t*o),i=g(r*s*s),d=s,a=g(s*q),c=i===e,u=i===g(-e),h=i===g(-e*q);return c&&(s=d),(u||h)&&(s=a),(g(s)&1n)===1n&&(s=g(-s)),!c&&!u?null:s}function Y(e,r){let t=g(e*e),n=g(t-1n),o=g(xe*t+1n),s=Ee(n,o);if(s===null)return !1;let i=(r&128)!==0;return !(s===0n&&i)}function Ae(e){let r=e.toString(16);return r.length===1?`0${r}`:r}function ve(e){let t=`0x${e.reduce((n,o,s)=>`${Ae(s===31?o&-129:o)}${n}`,"")}`;return BigInt(t)}async function J(e){if(e.byteLength!==32)return !1;let r=ve(e);return Y(r,e[31])}function tr(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&typeof e[1]=="number"&&e[1]>=0&&e[1]<=255&&j(e[0])}function nr(e){if(!(Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&typeof e[1]=="number"))throw new Error("Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].");if(e[1]<0||e[1]>255)throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${e[1]}.`);C(e[0]);}var ee=32,Q=16,v=[80,114,111,103,114,97,109,68,101,114,105,118,101,100,65,100,100,114,101,115,115],z=class extends Error{};async function ze({programAddress:e,seeds:r}){if(await Z(),r.length>Q)throw new Error(`A maximum of ${Q} seeds may be supplied when creating an address`);let t,n=r.reduce((a,c,u)=>{let h=typeof c=="string"?(t||(t=new TextEncoder)).encode(c):c;if(h.byteLength>ee)throw new Error(`The seed at index ${u} exceeds the maximum length of 32 bytes`);return a.push(...h),a},[]),o=U(),s=o.encode(e),i=await crypto.subtle.digest("SHA-256",new Uint8Array([...n,...s,...v])),d=new Uint8Array(i);if(await J(d))throw new z("Invalid seeds; point must fall off the Ed25519 curve");return o.decode(d)}async function or({programAddress:e,seeds:r}){let t=255;for(;t>0;)try{return [await ze({programAddress:e,seeds:[...r,new Uint8Array([t])]}),t]}catch(n){if(n instanceof z)t--;else throw n}throw new Error("Unable to find a viable program address bump seed")}async function sr({baseAddress:e,programAddress:r,seed:t}){let{encode:n,decode:o}=U(),s=typeof t=="string"?new TextEncoder().encode(t):t;if(s.byteLength>ee)throw new Error("The seed exceeds the maximum length of 32 bytes");let i=n(r);if(i.length>=v.length&&i.slice(-v.length).every((c,u)=>c===v[u]))throw new Error("programAddress cannot end with the PDA marker");let d=await crypto.subtle.digest("SHA-256",new Uint8Array([...n(e),...s,...i])),a=new Uint8Array(d);return o(a)}async function gr(e){if(await W(),e.type!=="public"||e.algorithm.name!=="Ed25519")throw new Error("The `CryptoKey` must be an `Ed25519` public key");let r=await crypto.subtle.exportKey("raw",e);return D().decode(new Uint8Array(r))}
6
-
7
- exports.address = pe;
8
- exports.assertIsAddress = C;
9
- exports.assertIsProgramDerivedAddress = nr;
10
- exports.createAddressWithSeed = sr;
11
- exports.getAddressCodec = U;
12
- exports.getAddressComparator = Me;
13
- exports.getAddressDecoder = D;
14
- exports.getAddressEncoder = be;
15
- exports.getAddressFromPublicKey = gr;
16
- exports.getProgramDerivedAddress = or;
17
- exports.isAddress = j;
18
- exports.isProgramDerivedAddress = tr;
19
-
20
- return exports;
21
-
22
- })({});