@solana/keys 2.0.0-experimental.fcff844 → 2.0.0-experimental.fd64233

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.
@@ -134,3 +134,5 @@ exports.isSignature = isSignature;
134
134
  exports.signBytes = signBytes;
135
135
  exports.signature = signature;
136
136
  exports.verifySignature = verifySignature;
137
+ //# sourceMappingURL=out.js.map
138
+ //# sourceMappingURL=index.browser.cjs.map
@@ -1,4 +1,4 @@
1
- export * from './key-pair';
2
- export * from './private-key';
3
- export * from './signatures';
1
+ export * from './key-pair.js';
2
+ export * from './private-key.js';
3
+ export * from './signatures.js';
4
4
  //# sourceMappingURL=index.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solana/keys",
3
- "version": "2.0.0-experimental.fcff844",
3
+ "version": "2.0.0-experimental.fd64233",
4
4
  "description": "Helpers for generating and transforming key material",
5
5
  "exports": {
6
6
  "browser": {
@@ -49,15 +49,15 @@
49
49
  "node": ">=17.4"
50
50
  },
51
51
  "dependencies": {
52
- "@solana/assertions": "2.0.0-experimental.fcff844",
53
- "@solana/codecs-core": "2.0.0-experimental.fcff844",
54
- "@solana/codecs-strings": "2.0.0-experimental.fcff844"
52
+ "@solana/assertions": "2.0.0-experimental.fd64233",
53
+ "@solana/codecs-core": "2.0.0-experimental.fd64233",
54
+ "@solana/codecs-strings": "2.0.0-experimental.fd64233"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@solana/eslint-config-solana": "^1.0.2",
58
58
  "@swc/jest": "^0.2.29",
59
- "@types/jest": "^29.5.6",
60
- "@typescript-eslint/eslint-plugin": "^6.7.0",
59
+ "@types/jest": "^29.5.11",
60
+ "@typescript-eslint/eslint-plugin": "^6.13.2",
61
61
  "@typescript-eslint/parser": "^6.3.0",
62
62
  "agadoo": "^3.0.0",
63
63
  "eslint": "^8.45.0",
@@ -84,8 +84,8 @@
84
84
  ]
85
85
  },
86
86
  "scripts": {
87
- "compile:js": "tsup --config build-scripts/tsup.config.library.ts",
88
- "compile:typedefs": "tsc -p ./tsconfig.declarations.json",
87
+ "compile:js": "tsup --config build-scripts/tsup.config.package.ts",
88
+ "compile:typedefs": "tsc -p ./tsconfig.declarations.json && node node_modules/build-scripts/add-js-extension-to-types.mjs",
89
89
  "dev": "jest -c node_modules/test-config/jest-dev.config.ts --rootDir . --watch",
90
90
  "publish-packages": "pnpm publish --tag experimental --access public --no-git-checks",
91
91
  "style:fix": "pnpm eslint --fix src/* && pnpm prettier -w src/* package.json",
@@ -1,262 +0,0 @@
1
- this.globalThis = this.globalThis || {};
2
- this.globalThis.solanaWeb3 = (function (exports) {
3
- 'use strict';
4
-
5
- // ../assertions/dist/index.browser.js
6
- function assertIsSecureContext() {
7
- if (!globalThis.isSecureContext) {
8
- throw new Error(
9
- "Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"
10
- );
11
- }
12
- }
13
- var cachedEd25519Decision;
14
- async function isEd25519CurveSupported(subtle) {
15
- if (cachedEd25519Decision === void 0) {
16
- cachedEd25519Decision = new Promise((resolve) => {
17
- subtle.generateKey(
18
- "Ed25519",
19
- /* extractable */
20
- false,
21
- ["sign", "verify"]
22
- ).catch(() => {
23
- resolve(cachedEd25519Decision = false);
24
- }).then(() => {
25
- resolve(cachedEd25519Decision = true);
26
- });
27
- });
28
- }
29
- if (typeof cachedEd25519Decision === "boolean") {
30
- return cachedEd25519Decision;
31
- } else {
32
- return await cachedEd25519Decision;
33
- }
34
- }
35
- async function assertKeyGenerationIsAvailable() {
36
- var _a;
37
- assertIsSecureContext();
38
- if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.generateKey) !== "function") {
39
- throw new Error("No key generation implementation could be found");
40
- }
41
- if (!await isEd25519CurveSupported(globalThis.crypto.subtle)) {
42
- throw new Error(
43
- "This runtime does not support the generation of Ed25519 key pairs.\n\nInstall and import `@solana/webcrypto-ed25519-polyfill` before generating keys in environments that do not support Ed25519.\n\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20"
44
- );
45
- }
46
- }
47
- async function assertSigningCapabilityIsAvailable() {
48
- var _a;
49
- assertIsSecureContext();
50
- if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.sign) !== "function") {
51
- throw new Error("No signing implementation could be found");
52
- }
53
- }
54
- async function assertVerificationCapabilityIsAvailable() {
55
- var _a;
56
- assertIsSecureContext();
57
- if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.verify) !== "function") {
58
- throw new Error("No signature verification implementation could be found");
59
- }
60
- }
61
-
62
- // src/key-pair.ts
63
- async function generateKeyPair() {
64
- await assertKeyGenerationIsAvailable();
65
- const keyPair = await crypto.subtle.generateKey(
66
- /* algorithm */
67
- "Ed25519",
68
- // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
69
- /* extractable */
70
- false,
71
- // Prevents the bytes of the private key from being visible to JS.
72
- /* allowed uses */
73
- ["sign", "verify"]
74
- );
75
- return keyPair;
76
- }
77
-
78
- // src/private-key.ts
79
- function addPkcs8Header(bytes) {
80
- return new Uint8Array([
81
- /**
82
- * PKCS#8 header
83
- */
84
- 48,
85
- // ASN.1 sequence tag
86
- 46,
87
- // Length of sequence (46 more bytes)
88
- 2,
89
- // ASN.1 integer tag
90
- 1,
91
- // Length of integer
92
- 0,
93
- // Version number
94
- 48,
95
- // ASN.1 sequence tag
96
- 5,
97
- // Length of sequence
98
- 6,
99
- // ASN.1 object identifier tag
100
- 3,
101
- // Length of object identifier
102
- // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
103
- 43,
104
- // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)
105
- 101,
106
- // thawte(101)
107
- // Ed25519 identifier
108
- 112,
109
- // id-Ed25519(112)
110
- /**
111
- * Private key payload
112
- */
113
- 4,
114
- // ASN.1 octet string tag
115
- 34,
116
- // String length (34 more bytes)
117
- // Private key bytes as octet string
118
- 4,
119
- // ASN.1 octet string tag
120
- 32,
121
- // String length (32 bytes)
122
- ...bytes
123
- ]);
124
- }
125
- async function createPrivateKeyFromBytes(bytes, extractable) {
126
- if (bytes.byteLength !== 32) {
127
- throw new Error("Private key bytes must be of length 32");
128
- }
129
- const privateKeyBytesPkcs8 = addPkcs8Header(bytes);
130
- return await crypto.subtle.importKey("pkcs8", privateKeyBytesPkcs8, "Ed25519", extractable != null ? extractable : false, ["sign"]);
131
- }
132
-
133
- // ../codecs-core/dist/index.browser.js
134
- function getEncodedSize(value, encoder) {
135
- return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);
136
- }
137
- function createEncoder(encoder) {
138
- return Object.freeze({
139
- ...encoder,
140
- encode: (value) => {
141
- const bytes = new Uint8Array(getEncodedSize(value, encoder));
142
- encoder.write(value, bytes, 0);
143
- return bytes;
144
- }
145
- });
146
- }
147
-
148
- // ../codecs-strings/dist/index.browser.js
149
- function assertValidBaseString(alphabet4, testValue, givenValue = testValue) {
150
- if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {
151
- throw new Error(`Expected a string of base ${alphabet4.length}, got [${givenValue}].`);
152
- }
153
- }
154
- var getBaseXEncoder = (alphabet4) => {
155
- return createEncoder({
156
- getSizeFromValue: (value) => {
157
- const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
158
- if (tailChars === "")
159
- return value.length;
160
- const base10Number = getBigIntFromBaseX(tailChars, alphabet4);
161
- return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);
162
- },
163
- write(value, bytes, offset) {
164
- assertValidBaseString(alphabet4, value);
165
- if (value === "")
166
- return offset;
167
- const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
168
- if (tailChars === "") {
169
- bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);
170
- return offset + leadingZeroes.length;
171
- }
172
- let base10Number = getBigIntFromBaseX(tailChars, alphabet4);
173
- const tailBytes = [];
174
- while (base10Number > 0n) {
175
- tailBytes.unshift(Number(base10Number % 256n));
176
- base10Number /= 256n;
177
- }
178
- const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];
179
- bytes.set(bytesToAdd, offset);
180
- return offset + bytesToAdd.length;
181
- }
182
- });
183
- };
184
- function partitionLeadingZeroes(value, zeroCharacter) {
185
- const leadingZeroIndex = [...value].findIndex((c) => c !== zeroCharacter);
186
- return leadingZeroIndex === -1 ? [value, ""] : [value.slice(0, leadingZeroIndex), value.slice(leadingZeroIndex)];
187
- }
188
- function getBigIntFromBaseX(value, alphabet4) {
189
- const base = BigInt(alphabet4.length);
190
- return [...value].reduce((sum, char) => sum * base + BigInt(alphabet4.indexOf(char)), 0n);
191
- }
192
- var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
193
- var getBase58Encoder = () => getBaseXEncoder(alphabet2);
194
-
195
- // src/signatures.ts
196
- var base58Encoder;
197
- function assertIsSignature(putativeSignature) {
198
- if (!base58Encoder)
199
- base58Encoder = getBase58Encoder();
200
- try {
201
- if (
202
- // Lowest value (64 bytes of zeroes)
203
- putativeSignature.length < 64 || // Highest value (64 bytes of 255)
204
- putativeSignature.length > 88
205
- ) {
206
- throw new Error("Expected input string to decode to a byte array of length 64.");
207
- }
208
- const bytes = base58Encoder.encode(putativeSignature);
209
- const numBytes = bytes.byteLength;
210
- if (numBytes !== 64) {
211
- throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);
212
- }
213
- } catch (e2) {
214
- throw new Error(`\`${putativeSignature}\` is not a signature`, {
215
- cause: e2
216
- });
217
- }
218
- }
219
- function isSignature(putativeSignature) {
220
- if (!base58Encoder)
221
- base58Encoder = getBase58Encoder();
222
- if (
223
- // Lowest value (64 bytes of zeroes)
224
- putativeSignature.length < 64 || // Highest value (64 bytes of 255)
225
- putativeSignature.length > 88
226
- ) {
227
- return false;
228
- }
229
- const bytes = base58Encoder.encode(putativeSignature);
230
- const numBytes = bytes.byteLength;
231
- if (numBytes !== 64) {
232
- return false;
233
- }
234
- return true;
235
- }
236
- async function signBytes(key, data) {
237
- await assertSigningCapabilityIsAvailable();
238
- const signedData = await crypto.subtle.sign("Ed25519", key, data);
239
- return new Uint8Array(signedData);
240
- }
241
- function signature(putativeSignature) {
242
- assertIsSignature(putativeSignature);
243
- return putativeSignature;
244
- }
245
- async function verifySignature(key, signature2, data) {
246
- await assertVerificationCapabilityIsAvailable();
247
- return await crypto.subtle.verify("Ed25519", key, signature2, data);
248
- }
249
-
250
- exports.assertIsSignature = assertIsSignature;
251
- exports.createPrivateKeyFromBytes = createPrivateKeyFromBytes;
252
- exports.generateKeyPair = generateKeyPair;
253
- exports.isSignature = isSignature;
254
- exports.signBytes = signBytes;
255
- exports.signature = signature;
256
- exports.verifySignature = verifySignature;
257
-
258
- return exports;
259
-
260
- })({});
261
- //# sourceMappingURL=out.js.map
262
- //# sourceMappingURL=index.development.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../assertions/src/subtle-crypto.ts","../src/key-pair.ts","../src/private-key.ts","../../codecs-core/src/codec.ts","../../codecs-strings/src/assertions.ts","../../codecs-strings/src/baseX.ts","../../codecs-strings/src/base16.ts","../../codecs-strings/src/base64.ts","../src/signatures.ts"],"names":["alphabet","e","signature"],"mappings":";AAAA,SAAS,wBAAwB;AAC7B,MAAmB,CAAC,WAAW,iBAAiB;AAE5C,UAAM,IAAI;MACN;IAEJ;EACJ;AACJ;AAEA,IAAI;AACJ,eAAe,wBAAwB,QAAwC;AAC3E,MAAI,0BAA0B,QAAW;AACrC,4BAAwB,IAAI,QAAQ,CAAA,YAAW;AAC3C,aACK;QAAY;;QAA6B;QAAO,CAAC,QAAQ,QAAQ;MAAC,EAClE,MAAM,MAAM;AACT,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IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,QAAQ,EAAE;AAAA,IAC9G;AAAA,EACJ,SAASC,IAAG;AACR,UAAM,IAAI,MAAM,KAAK,iBAAiB,yBAAyB;AAAA,MAC3D,OAAOA;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,YAAY,mBAA2D;AACnF,MAAI,CAAC;AAAe,oBAAgB,iBAAiB;AAGrD;AAAA;AAAA,IAEI,kBAAkB,SAAS;AAAA,IAE3B,kBAAkB,SAAS;AAAA,IAC7B;AACE,WAAO;AAAA,EACX;AAEA,QAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,QAAM,WAAW,MAAM;AACvB,MAAI,aAAa,IAAI;AACjB,WAAO;AAAA,EACX;AACA,SAAO;AACX;AAEA,eAAsB,UAAU,KAAgB,MAA2C;AACvF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEO,SAAS,UAAU,mBAAsC;AAC5D,oBAAkB,iBAAiB;AACnC,SAAO;AACX;AAEA,eAAsB,gBAAgB,KAAgBC,YAA2B,MAAoC;AACjH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAKA,YAAW,IAAI;AACrE","sourcesContent":["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","import { assertKeyGenerationIsAvailable } from '@solana/assertions';\n\nexport async function generateKeyPair(): Promise<CryptoKeyPair> {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ 'Ed25519', // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify'],\n );\n return keyPair as CryptoKeyPair;\n}\n","function addPkcs8Header(bytes: Uint8Array): Uint8Array {\n // prettier-ignore\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n\n ...bytes\n ]);\n}\n\nexport async function createPrivateKeyFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKey> {\n if (bytes.byteLength !== 32) {\n // TODO: Coded error.\n throw new Error('Private key bytes must be of length 32');\n }\n const privateKeyBytesPkcs8 = addPkcs8Header(bytes);\n return await crypto.subtle.importKey('pkcs8', privateKeyBytesPkcs8, 'Ed25519', extractable ?? false, ['sign']);\n}\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","/**\n * Asserts that a given string matches a given alphabet.\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base ${alphabet.length}, got [${givenValue}].`);\n }\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Encodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXEncoder = (alphabet: string): VariableSizeEncoder<string> => {\n return createEncoder({\n getSizeFromValue: (value: string): number => {\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (tailChars === '') return value.length;\n\n const base10Number = getBigIntFromBaseX(tailChars, alphabet);\n return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);\n },\n write(value: string, bytes, offset) {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return offset;\n\n // Handle leading zeroes.\n const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet[0]);\n if (tailChars === '') {\n bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);\n return offset + leadingZeroes.length;\n }\n\n // From baseX to base10.\n let base10Number = getBigIntFromBaseX(tailChars, alphabet);\n\n // From base10 to bytes.\n const tailBytes: number[] = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n\n const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];\n bytes.set(bytesToAdd, offset);\n return offset + bytesToAdd.length;\n },\n });\n};\n\n/**\n * Decodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXDecoder = (alphabet: string): VariableSizeDecoder<string> => {\n return createDecoder({\n read(rawBytes, offset): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = getBaseXFromBigInt(base10Number, alphabet);\n\n return [leadingZeroes + tailChars, rawBytes.length];\n },\n });\n};\n\n/**\n * A string codec that requires a custom alphabet and uses\n * the length of that alphabet as the base. It then divides\n * the input by the base as many times as necessary to get\n * the output. It also supports leading zeroes by using the\n * first character of the alphabet as the zero character.\n *\n * This can be used to create codecs such as base10 or base58.\n */\nexport const getBaseXCodec = (alphabet: string): VariableSizeCodec<string> =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n\nfunction partitionLeadingZeroes(value: string, zeroCharacter: string): [string, string] {\n const leadingZeroIndex = [...value].findIndex(c => c !== zeroCharacter);\n return leadingZeroIndex === -1 ? [value, ''] : [value.slice(0, leadingZeroIndex), value.slice(leadingZeroIndex)];\n}\n\nfunction getBigIntFromBaseX(value: string, alphabet: string): bigint {\n const base = BigInt(alphabet.length);\n return [...value].reduce((sum, char) => sum * base + BigInt(alphabet.indexOf(char)), 0n);\n}\n\nfunction getBaseXFromBigInt(value: bigint, alphabet: string): string {\n const base = BigInt(alphabet.length);\n const tailChars = [];\n while (value > 0n) {\n tailChars.unshift(alphabet[Number(value % base)]);\n value /= base;\n }\n return tailChars.join('');\n}\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/** Encodes strings in base16. */\nexport const getBase16Encoder = (): VariableSizeEncoder<string> =>\n createEncoder({\n getSizeFromValue: (value: string) => Math.ceil(value.length / 2),\n write(value: string, 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: string) => parseInt(byte, 16)) : [];\n bytes.set(hexBytes, offset);\n return hexBytes.length + offset;\n },\n });\n\n/** Decodes strings in base16. */\nexport const getBase16Decoder = (): VariableSizeDecoder<string> =>\n 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 });\n\n/** Encodes and decodes strings in base16. */\nexport const getBase16Codec = (): VariableSizeCodec<string> => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import {\n combineCodec,\n createDecoder,\n createEncoder,\n mapDecoder,\n mapEncoder,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/** Encodes strings in base64. */\nexport const getBase64Encoder = (): VariableSizeEncoder<string> => {\n if (__BROWSER__) {\n return createEncoder({\n getSizeFromValue: (value: string) => {\n try {\n return (atob as Window['atob'])(value).length;\n } catch (e) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n write(value: string, bytes, offset) {\n try {\n const bytesToAdd = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n bytes.set(bytesToAdd, offset);\n return bytesToAdd.length + offset;\n } catch (e) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n });\n }\n\n if (__NODEJS__) {\n return createEncoder({\n getSizeFromValue: (value: string) => Buffer.from(value, 'base64').length,\n write(value: string, bytes, offset) {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n const buffer = Buffer.from(value, 'base64');\n bytes.set(buffer, offset);\n return buffer.length + offset;\n },\n });\n }\n\n return mapEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/** Decodes strings in base64. */\nexport const getBase64Decoder = (): VariableSizeDecoder<string> => {\n if (__BROWSER__) {\n return createDecoder({\n read(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = (btoa as Window['btoa'])(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n });\n }\n\n if (__NODEJS__) {\n return createDecoder({\n read: (bytes, offset = 0) => [Buffer.from(bytes, offset).toString('base64'), bytes.length],\n });\n }\n\n return mapDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '='),\n );\n};\n\n/** Encodes and decodes strings in base64. */\nexport const getBase64Codec = (): VariableSizeCodec<string> => combineCodec(getBase64Encoder(), getBase64Decoder());\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -1,21 +0,0 @@
1
- this.globalThis = this.globalThis || {};
2
- this.globalThis.solanaWeb3 = (function (exports) {
3
- 'use strict';
4
-
5
- function u(){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")}var o;async function b(e){return o===void 0&&(o=new Promise(r=>{e.generateKey("Ed25519",!1,["sign","verify"]).catch(()=>{r(o=!1);}).then(()=>{r(o=!0);});})),typeof o=="boolean"?o:await o}async function h(){var e;if(u(),typeof globalThis.crypto>"u"||typeof((e=globalThis.crypto.subtle)==null?void 0:e.generateKey)!="function")throw new Error("No key generation implementation could be found");if(!await b(globalThis.crypto.subtle))throw new Error(`This runtime does not support the generation of Ed25519 key pairs.
6
-
7
- Install and import \`@solana/webcrypto-ed25519-polyfill\` before generating keys in environments that do not support Ed25519.
8
-
9
- For a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20`)}async function y(){var e;if(u(),typeof globalThis.crypto>"u"||typeof((e=globalThis.crypto.subtle)==null?void 0:e.sign)!="function")throw new Error("No signing implementation could be found")}async function p(){var e;if(u(),typeof globalThis.crypto>"u"||typeof((e=globalThis.crypto.subtle)==null?void 0:e.verify)!="function")throw new Error("No signature verification implementation could be found")}async function U(){return await h(),await crypto.subtle.generateKey("Ed25519",!1,["sign","verify"])}function v(e){return new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32,...e])}async function K(e,r){if(e.byteLength!==32)throw new Error("Private key bytes must be of length 32");let t=v(e);return await crypto.subtle.importKey("pkcs8",t,"Ed25519",r!=null?r:!1,["sign"])}function m(e,r){return "fixedSize"in r?r.fixedSize:r.getSizeFromValue(e)}function w(e){return Object.freeze({...e,encode:r=>{let t=new Uint8Array(m(r,e));return e.write(r,t,0),t}})}function S(e,r,t=r){if(!r.match(new RegExp(`^[${e}]*$`)))throw new Error(`Expected a string of base ${e.length}, got [${t}].`)}var z=e=>w({getSizeFromValue:r=>{let[t,n]=x(r,e[0]);if(n==="")return r.length;let i=E(n,e);return t.length+Math.ceil(i.toString(16).length/2)},write(r,t,n){if(S(e,r),r==="")return n;let[i,d]=x(r,e[0]);if(d==="")return t.set(new Uint8Array(i.length).fill(0),n),n+i.length;let c=E(d,e),g=[];for(;c>0n;)g.unshift(Number(c%256n)),c/=256n;let f=[...Array(i.length).fill(0),...g];return t.set(f,n),n+f.length}});function x(e,r){let t=[...e].findIndex(n=>n!==r);return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]}function E(e,r){let t=BigInt(r.length);return [...e].reduce((n,i)=>n*t+BigInt(r.indexOf(i)),0n)}var C="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",l=()=>z(C);var s;function B(e){s||(s=l());try{if(e.length<64||e.length>88)throw new Error("Expected input string to decode to a byte array of length 64.");let t=s.encode(e).byteLength;if(t!==64)throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${t}`)}catch(r){throw new Error(`\`${e}\` is not a signature`,{cause:r})}}function Q(e){return s||(s=l()),!(e.length<64||e.length>88||s.encode(e).byteLength!==64)}async function Y(e,r){await y();let t=await crypto.subtle.sign("Ed25519",e,r);return new Uint8Array(t)}function ee(e){return B(e),e}async function re(e,r,t){return await p(),await crypto.subtle.verify("Ed25519",e,r,t)}
10
-
11
- exports.assertIsSignature = B;
12
- exports.createPrivateKeyFromBytes = K;
13
- exports.generateKeyPair = U;
14
- exports.isSignature = Q;
15
- exports.signBytes = Y;
16
- exports.signature = ee;
17
- exports.verifySignature = re;
18
-
19
- return exports;
20
-
21
- })({});