@solana/keys 2.0.0-experimental.9bf9fdb → 2.0.0-experimental.9e133fd

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/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright (c) 2018 Solana Labs, Inc
1
+ Copyright (c) 2023 Solana Labs, Inc
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining
4
4
  a copy of this software and associated documentation files (the
package/README.md CHANGED
@@ -18,35 +18,44 @@ This package contains utilities for validating, generating, and manipulating add
18
18
 
19
19
  ## Types
20
20
 
21
- ### `Base58EncodedAddress`
21
+ ### `Ed25519Signature`
22
22
 
23
- This type represents a string that validates as a Solana address or public key. Functions that require well-formed addresses should specify their inputs in terms of this type.
23
+ This type represents a 64-byte Ed25519 signature of some data with a private key.
24
24
 
25
- Whenever you need to validate an arbitrary string as a base58-encoded address, use the `assertIsBase58EncodedAddress()` function in this package.
25
+ Whenever you need to verify that a particular signature is, in fact, the one that would have been produced by signing some known bytes using the private key associated with some known public key, use the `verifySignature()` function in this package.
26
26
 
27
27
  ## Functions
28
28
 
29
- ### `assertIsBase58EncodedAddress()`
29
+ ### `generateKeyPair()`
30
30
 
31
- Client applications primarily deal with addresses and public keys in the form of base58-encoded strings. Addresses and public keys returned from the RPC API conform to the type `Base58EncodedAddress`. You can use a value of that type wherever a base58-encoded address or key is expected.
31
+ Generates an Ed25519 public/private key pair for use with other methods in this package that accept `CryptoKey` objects.
32
32
 
33
- From time to time you might acquire a string, that you expect to validate as an address, from an untrusted network API or user input. To assert that such an arbitrary string is a base58-encoded address, use the `assertIsBase58EncodedAddress` function.
33
+ ```ts
34
+ import { generateKeyPair } from '@solana/keys';
35
+
36
+ const { privateKey, publicKey } = await generateKeyPair();
37
+ ```
38
+
39
+ ### `signBytes()`
40
+
41
+ Given a private `CryptoKey` and a `Uint8Array` of bytes, this method will return the 64-byte Ed25519 signature of that data as a `Uint8Array`.
42
+
43
+ ```ts
44
+ import { signBytes } from '@solana/keys';
45
+
46
+ const data = new Uint8Array([1, 2, 3]);
47
+ const signature = await signBytes(privateKey, data);
48
+ ```
49
+
50
+ ### `verifySignature()`
51
+
52
+ Given a public `CryptoKey`, an `Ed25519Signature`, and a `Uint8Array` of bytes, this method will return `true` if the signature was produced by signing the bytes using the private key associated with the public key, and `false` otherwise.
34
53
 
35
54
  ```ts
36
- import { assertIsBase58EncodedAddress } from '@solana/web3.js`;
37
-
38
- // Imagine a function that fetches an account's balance when a user submits a form.
39
- function handleSubmit() {
40
- // We know only that what the user typed conforms to the `string` type.
41
- const address: string = accountAddressInput.value;
42
- try {
43
- // If this type assertion function doesn't throw, then
44
- // Typescript will upcast `address` to `Base58EncodedAddress`.
45
- assertIsBase58EncodedAddress(address);
46
- // At this point, `address` is a `Base58EncodedAddress` that can be used with the RPC.
47
- const balanceInLamports = await rpc.getBalance(address).send();
48
- } catch (e) {
49
- // `address` turned out not to be a base58-encoded address
50
- }
55
+ import { verifySignature } from '@solana/keys';
56
+
57
+ const data = new Uint8Array([1, 2, 3]);
58
+ if (!(await verifySignature(publicKey, signature, data))) {
59
+ throw new Error('The data were *not* signed by the private key associated with `publicKey`');
51
60
  }
52
61
  ```
@@ -1,49 +1,34 @@
1
1
  'use strict';
2
2
 
3
- var umiSerializers = require('@metaplex-foundation/umi-serializers');
3
+ var assertions = require('@solana/assertions');
4
4
 
5
- // ../build-scripts/env-shim.ts
6
- var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
7
- function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
8
- try {
9
- if (
10
- // Lowest address (32 bytes of zeroes)
11
- putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
12
- putativeBase58EncodedAddress.length > 44
13
- ) {
14
- throw new Error("Expected input string to decode to a byte array of length 32.");
15
- }
16
- const bytes = umiSerializers.base58.serialize(putativeBase58EncodedAddress);
17
- const numBytes = bytes.byteLength;
18
- if (numBytes !== 32) {
19
- throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
20
- }
21
- } catch (e) {
22
- throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
23
- cause: e
24
- });
25
- }
5
+ // src/key-pair.ts
6
+ async function generateKeyPair() {
7
+ await assertions.assertKeyGenerationIsAvailable();
8
+ const keyPair = await crypto.subtle.generateKey(
9
+ /* algorithm */
10
+ "Ed25519",
11
+ // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
12
+ /* extractable */
13
+ false,
14
+ // Prevents the bytes of the private key from being visible to JS.
15
+ /* allowed uses */
16
+ ["sign", "verify"]
17
+ );
18
+ return keyPair;
26
19
  }
27
- function getBase58EncodedAddressCodec(config) {
28
- return umiSerializers.string({
29
- description: config?.description ?? (__DEV__ ? "A 32-byte account address" : ""),
30
- encoding: umiSerializers.base58,
31
- size: 32
32
- });
20
+ async function signBytes(key, data) {
21
+ await assertions.assertSigningCapabilityIsAvailable();
22
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
23
+ return new Uint8Array(signedData);
33
24
  }
34
- function getBase58EncodedAddressComparator() {
35
- return new Intl.Collator("en", {
36
- caseFirst: "lower",
37
- ignorePunctuation: false,
38
- localeMatcher: "best fit",
39
- numeric: false,
40
- sensitivity: "variant",
41
- usage: "sort"
42
- }).compare;
25
+ async function verifySignature(key, signature, data) {
26
+ await assertions.assertVerificationCapabilityIsAvailable();
27
+ return await crypto.subtle.verify("Ed25519", key, signature, data);
43
28
  }
44
29
 
45
- exports.assertIsBase58EncodedAddress = assertIsBase58EncodedAddress;
46
- exports.getBase58EncodedAddressCodec = getBase58EncodedAddressCodec;
47
- exports.getBase58EncodedAddressComparator = getBase58EncodedAddressComparator;
30
+ exports.generateKeyPair = generateKeyPair;
31
+ exports.signBytes = signBytes;
32
+ exports.verifySignature = verifySignature;
48
33
  //# sourceMappingURL=out.js.map
49
34
  //# sourceMappingURL=index.browser.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../build-scripts/env-shim.ts","../src/base58.ts"],"names":[],"mappings":";AACO,IAAM,UAA2B,uBAAO,QAAgB,KAAU,EAAE,aAAa,eAAe;;;ACDvG,SAAS,QAAoB,cAAc;AAMpC,SAAS,6BACZ,8BACiG;AACjG,MAAI;AAEA;AAAA;AAAA,MAEI,6BAA6B,SAAS;AAAA,MAEtC,6BAA6B,SAAS;AAAA,MACxC;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,OAAO,UAAU,4BAA4B;AAC3D,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,UAAU;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAP;AACE,UAAM,IAAI,MAAM,KAAK,mEAAmE;AAAA,MACpF,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,6BACZ,QAGgC;AAChC,SAAO,OAAO;AAAA,IACV,aAAa,QAAQ,gBAAgB,UAAU,8BAA8B;AAAA,IAC7E,UAAU;AAAA,IACV,MAAM;AAAA,EACV,CAAC;AACL;AAEO,SAAS,oCAAsE;AAClF,SAAO,IAAI,KAAK,SAAS,MAAM;AAAA,IAC3B,WAAW;AAAA,IACX,mBAAmB;AAAA,IACnB,eAAe;AAAA,IACf,SAAS;AAAA,IACT,aAAa;AAAA,IACb,OAAO;AAAA,EACX,CAAC,EAAE;AACP","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","import { base58, Serializer, string } from '@metaplex-foundation/umi-serializers';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __base58EncodedAddress: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\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 putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.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 bytes = base58.serialize(putativeBase58EncodedAddress);\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(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function getBase58EncodedAddressCodec(\n config?: Readonly<{\n description: string;\n }>\n): Serializer<Base58EncodedAddress> {\n return string({\n description: config?.description ?? (__DEV__ ? 'A 32-byte account address' : ''),\n encoding: base58,\n size: 32,\n }) as unknown as Serializer<Base58EncodedAddress>;\n}\n\nexport function getBase58EncodedAddressComparator(): (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"]}
1
+ {"version":3,"sources":["../src/key-pair.ts","../src/signatures.ts"],"names":[],"mappings":";AAAA,SAAS,sCAAsC;AAE/C,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC,QAAM,UAAU,MAAM,OAAO,OAAO;AAAA;AAAA,IAChB;AAAA;AAAA;AAAA,IACE;AAAA;AAAA;AAAA,IACC,CAAC,QAAQ,QAAQ;AAAA,EACxC;AACA,SAAO;AACX;;;ACVA,SAAS,oCAAoC,+CAA+C;AAI5F,eAAsB,UAAU,KAAgB,MAA6C;AACzF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEA,eAAsB,gBAAgB,KAAgB,WAA6B,MAAoC;AACnH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,WAAW,IAAI;AACrE","sourcesContent":["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","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\n\nexport type Ed25519Signature = Uint8Array & { readonly __brand: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -1,45 +1,30 @@
1
- import { base58, string } from '@metaplex-foundation/umi-serializers';
1
+ import { assertKeyGenerationIsAvailable, assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';
2
2
 
3
- // ../build-scripts/env-shim.ts
4
- var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
5
- function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
6
- try {
7
- if (
8
- // Lowest address (32 bytes of zeroes)
9
- putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
10
- putativeBase58EncodedAddress.length > 44
11
- ) {
12
- throw new Error("Expected input string to decode to a byte array of length 32.");
13
- }
14
- const bytes = base58.serialize(putativeBase58EncodedAddress);
15
- const numBytes = bytes.byteLength;
16
- if (numBytes !== 32) {
17
- throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
18
- }
19
- } catch (e) {
20
- throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
21
- cause: e
22
- });
23
- }
3
+ // src/key-pair.ts
4
+ async function generateKeyPair() {
5
+ await assertKeyGenerationIsAvailable();
6
+ const keyPair = await crypto.subtle.generateKey(
7
+ /* algorithm */
8
+ "Ed25519",
9
+ // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
10
+ /* extractable */
11
+ false,
12
+ // Prevents the bytes of the private key from being visible to JS.
13
+ /* allowed uses */
14
+ ["sign", "verify"]
15
+ );
16
+ return keyPair;
24
17
  }
25
- function getBase58EncodedAddressCodec(config) {
26
- return string({
27
- description: config?.description ?? (__DEV__ ? "A 32-byte account address" : ""),
28
- encoding: base58,
29
- size: 32
30
- });
18
+ async function signBytes(key, data) {
19
+ await assertSigningCapabilityIsAvailable();
20
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
21
+ return new Uint8Array(signedData);
31
22
  }
32
- function getBase58EncodedAddressComparator() {
33
- return new Intl.Collator("en", {
34
- caseFirst: "lower",
35
- ignorePunctuation: false,
36
- localeMatcher: "best fit",
37
- numeric: false,
38
- sensitivity: "variant",
39
- usage: "sort"
40
- }).compare;
23
+ async function verifySignature(key, signature, data) {
24
+ await assertVerificationCapabilityIsAvailable();
25
+ return await crypto.subtle.verify("Ed25519", key, signature, data);
41
26
  }
42
27
 
43
- export { assertIsBase58EncodedAddress, getBase58EncodedAddressCodec, getBase58EncodedAddressComparator };
28
+ export { generateKeyPair, signBytes, verifySignature };
44
29
  //# sourceMappingURL=out.js.map
45
30
  //# sourceMappingURL=index.browser.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../build-scripts/env-shim.ts","../src/base58.ts"],"names":[],"mappings":";AACO,IAAM,UAA2B,uBAAO,QAAgB,KAAU,EAAE,aAAa,eAAe;;;ACDvG,SAAS,QAAoB,cAAc;AAMpC,SAAS,6BACZ,8BACiG;AACjG,MAAI;AAEA;AAAA;AAAA,MAEI,6BAA6B,SAAS;AAAA,MAEtC,6BAA6B,SAAS;AAAA,MACxC;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,OAAO,UAAU,4BAA4B;AAC3D,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,UAAU;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAP;AACE,UAAM,IAAI,MAAM,KAAK,mEAAmE;AAAA,MACpF,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,6BACZ,QAGgC;AAChC,SAAO,OAAO;AAAA,IACV,aAAa,QAAQ,gBAAgB,UAAU,8BAA8B;AAAA,IAC7E,UAAU;AAAA,IACV,MAAM;AAAA,EACV,CAAC;AACL;AAEO,SAAS,oCAAsE;AAClF,SAAO,IAAI,KAAK,SAAS,MAAM;AAAA,IAC3B,WAAW;AAAA,IACX,mBAAmB;AAAA,IACnB,eAAe;AAAA,IACf,SAAS;AAAA,IACT,aAAa;AAAA,IACb,OAAO;AAAA,EACX,CAAC,EAAE;AACP","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","import { base58, Serializer, string } from '@metaplex-foundation/umi-serializers';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __base58EncodedAddress: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\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 putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.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 bytes = base58.serialize(putativeBase58EncodedAddress);\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(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function getBase58EncodedAddressCodec(\n config?: Readonly<{\n description: string;\n }>\n): Serializer<Base58EncodedAddress> {\n return string({\n description: config?.description ?? (__DEV__ ? 'A 32-byte account address' : ''),\n encoding: base58,\n size: 32,\n }) as unknown as Serializer<Base58EncodedAddress>;\n}\n\nexport function getBase58EncodedAddressComparator(): (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"]}
1
+ {"version":3,"sources":["../src/key-pair.ts","../src/signatures.ts"],"names":[],"mappings":";AAAA,SAAS,sCAAsC;AAE/C,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC,QAAM,UAAU,MAAM,OAAO,OAAO;AAAA;AAAA,IAChB;AAAA;AAAA;AAAA,IACE;AAAA;AAAA;AAAA,IACC,CAAC,QAAQ,QAAQ;AAAA,EACxC;AACA,SAAO;AACX;;;ACVA,SAAS,oCAAoC,+CAA+C;AAI5F,eAAsB,UAAU,KAAgB,MAA6C;AACzF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEA,eAAsB,gBAAgB,KAAgB,WAA6B,MAAoC;AACnH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,WAAW,IAAI;AACrE","sourcesContent":["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","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\n\nexport type Ed25519Signature = Uint8Array & { readonly __brand: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -2,312 +2,90 @@ this.globalThis = this.globalThis || {};
2
2
  this.globalThis.solanaWeb3 = (function (exports) {
3
3
  'use strict';
4
4
 
5
- var __defProp = Object.defineProperty;
6
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
- var __publicField = (obj, key, value) => {
8
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
9
- return value;
10
- };
11
-
12
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/bytes.mjs
13
- var mergeBytes = (bytesArr) => {
14
- const totalLength = bytesArr.reduce((total, arr) => total + arr.length, 0);
15
- const result = new Uint8Array(totalLength);
16
- let offset = 0;
17
- bytesArr.forEach((arr) => {
18
- result.set(arr, offset);
19
- offset += arr.length;
20
- });
21
- return result;
22
- };
23
- var padBytes = (bytes, length) => {
24
- if (bytes.length >= length)
25
- return bytes;
26
- const paddedBytes = new Uint8Array(length).fill(0);
27
- paddedBytes.set(bytes);
28
- return paddedBytes;
29
- };
30
- var fixBytes = (bytes, length) => padBytes(bytes.slice(0, length), length);
31
-
32
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/errors.mjs
33
- var DeserializingEmptyBufferError = class extends Error {
34
- constructor(serializer) {
35
- super(`Serializer [${serializer}] cannot deserialize empty buffers.`);
36
- __publicField(this, "name", "DeserializingEmptyBufferError");
37
- }
38
- };
39
- var NotEnoughBytesError = class extends Error {
40
- constructor(serializer, expected, actual) {
41
- super(`Serializer [${serializer}] expected ${expected} bytes, got ${actual}.`);
42
- __publicField(this, "name", "NotEnoughBytesError");
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
+ );
43
11
  }
44
- };
45
-
46
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/fixSerializer.mjs
47
- function fixSerializer(serializer, fixedBytes, description) {
48
- return {
49
- description: description ?? `fixed(${fixedBytes}, ${serializer.description})`,
50
- fixedSize: fixedBytes,
51
- maxSize: fixedBytes,
52
- serialize: (value) => fixBytes(serializer.serialize(value), fixedBytes),
53
- deserialize: (buffer, offset = 0) => {
54
- buffer = buffer.slice(offset, offset + fixedBytes);
55
- if (buffer.length < fixedBytes) {
56
- throw new NotEnoughBytesError("fixSerializer", fixedBytes, buffer.length);
57
- }
58
- if (serializer.fixedSize !== null) {
59
- buffer = fixBytes(buffer, serializer.fixedSize);
60
- }
61
- const [value] = serializer.deserialize(buffer, 0);
62
- return [value, offset + fixedBytes];
63
- }
64
- };
65
12
  }
66
-
67
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/errors.mjs
68
- var InvalidBaseStringError = class extends Error {
69
- constructor(value, base, cause) {
70
- const message = `Expected a string of base ${base}, got [${value}].`;
71
- super(message);
72
- __publicField(this, "name", "InvalidBaseStringError");
73
- this.cause = cause;
74
- }
75
- };
76
-
77
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/baseX.mjs
78
- var baseX = (alphabet) => {
79
- const base = alphabet.length;
80
- const baseBigInt = BigInt(base);
81
- return {
82
- description: `base${base}`,
83
- fixedSize: null,
84
- maxSize: null,
85
- serialize(value) {
86
- if (!value.match(new RegExp(`^[${alphabet}]*$`))) {
87
- throw new InvalidBaseStringError(value, base);
88
- }
89
- if (value === "")
90
- return new Uint8Array();
91
- const chars = [...value];
92
- let trailIndex = chars.findIndex((c) => c !== alphabet[0]);
93
- trailIndex = trailIndex === -1 ? chars.length : trailIndex;
94
- const leadingZeroes = Array(trailIndex).fill(0);
95
- if (trailIndex === chars.length)
96
- return Uint8Array.from(leadingZeroes);
97
- const tailChars = chars.slice(trailIndex);
98
- let base10Number = 0n;
99
- let baseXPower = 1n;
100
- for (let i = tailChars.length - 1; i >= 0; i -= 1) {
101
- base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));
102
- baseXPower *= baseBigInt;
103
- }
104
- const tailBytes = [];
105
- while (base10Number > 0n) {
106
- tailBytes.unshift(Number(base10Number % 256n));
107
- base10Number /= 256n;
108
- }
109
- return Uint8Array.from(leadingZeroes.concat(tailBytes));
110
- },
111
- deserialize(buffer, offset = 0) {
112
- if (buffer.length === 0)
113
- return ["", 0];
114
- const bytes = buffer.slice(offset);
115
- let trailIndex = bytes.findIndex((n) => n !== 0);
116
- trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
117
- const leadingZeroes = alphabet[0].repeat(trailIndex);
118
- if (trailIndex === bytes.length)
119
- return [leadingZeroes, buffer.length];
120
- let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
121
- const tailChars = [];
122
- while (base10Number > 0n) {
123
- tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);
124
- base10Number /= baseBigInt;
125
- }
126
- return [leadingZeroes + tailChars.join(""), buffer.length];
127
- }
128
- };
129
- };
130
-
131
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/base58.mjs
132
- var base58 = baseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
133
-
134
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/nullCharacters.mjs
135
- var removeNullCharacters = (value) => (
136
- // eslint-disable-next-line no-control-regex
137
- value.replace(/\u0000/g, "")
138
- );
139
-
140
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/utf8.mjs
141
- var utf8 = {
142
- description: "utf8",
143
- fixedSize: null,
144
- maxSize: null,
145
- serialize(value) {
146
- return new TextEncoder().encode(value);
147
- },
148
- deserialize(buffer, offset = 0) {
149
- const value = new TextDecoder().decode(buffer.slice(offset));
150
- return [removeNullCharacters(value), buffer.length];
151
- }
152
- };
153
-
154
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/common.mjs
155
- var Endian;
156
- (function(Endian2) {
157
- Endian2["Little"] = "le";
158
- Endian2["Big"] = "be";
159
- })(Endian || (Endian = {}));
160
-
161
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/errors.mjs
162
- var NumberOutOfRangeError = class extends RangeError {
163
- constructor(serializer, min, max, actual) {
164
- super(`Serializer [${serializer}] expected number to be between ${min} and ${max}, got ${actual}.`);
165
- __publicField(this, "name", "NumberOutOfRangeError");
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
+ });
166
28
  }
167
- };
168
-
169
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/utils.mjs
170
- function numberFactory(input) {
171
- let littleEndian;
172
- let defaultDescription = input.name;
173
- if (input.size > 1) {
174
- littleEndian = !("endian" in input.options) || input.options.endian === Endian.Little;
175
- defaultDescription += littleEndian ? "(le)" : "(be)";
29
+ if (typeof cachedEd25519Decision === "boolean") {
30
+ return cachedEd25519Decision;
31
+ } else {
32
+ return await cachedEd25519Decision;
176
33
  }
177
- return {
178
- description: input.options.description ?? defaultDescription,
179
- fixedSize: input.size,
180
- maxSize: input.size,
181
- serialize(value) {
182
- if (input.range) {
183
- assertRange(input.name, input.range[0], input.range[1], value);
184
- }
185
- const buffer = new ArrayBuffer(input.size);
186
- input.set(new DataView(buffer), value, littleEndian);
187
- return new Uint8Array(buffer);
188
- },
189
- deserialize(bytes, offset = 0) {
190
- const slice = bytes.slice(offset, offset + input.size);
191
- assertEnoughBytes("i8", slice, input.size);
192
- const view = toDataView(slice);
193
- return [input.get(view, littleEndian), offset + input.size];
194
- }
195
- };
196
34
  }
197
- var toArrayBuffer = (array) => array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);
198
- var toDataView = (array) => new DataView(toArrayBuffer(array));
199
- var assertRange = (serializer, min, max, value) => {
200
- if (value < min || value > max) {
201
- throw new NumberOutOfRangeError(serializer, min, max, value);
35
+ async function assertKeyGenerationIsAvailable() {
36
+ assertIsSecureContext();
37
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.generateKey !== "function") {
38
+ throw new Error("No key generation implementation could be found");
202
39
  }
203
- };
204
- var assertEnoughBytes = (serializer, bytes, expected) => {
205
- if (bytes.length === 0) {
206
- throw new DeserializingEmptyBufferError(serializer);
40
+ if (!await isEd25519CurveSupported(globalThis.crypto.subtle)) {
41
+ throw new Error(
42
+ "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"
43
+ );
207
44
  }
208
- if (bytes.length < expected) {
209
- throw new NotEnoughBytesError(serializer, expected, bytes.length);
210
- }
211
- };
212
-
213
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/u32.mjs
214
- var u32 = (options = {}) => numberFactory({
215
- name: "u32",
216
- size: 4,
217
- range: [0, Number("0xffffffff")],
218
- set: (view, value, le) => view.setUint32(0, Number(value), le),
219
- get: (view, le) => view.getUint32(0, le),
220
- options
221
- });
222
-
223
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.2/node_modules/@metaplex-foundation/umi-serializers/dist/esm/utils.mjs
224
- function getSizeDescription(size) {
225
- return typeof size === "object" ? size.description : `${size}`;
226
45
  }
227
-
228
- // ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.2/node_modules/@metaplex-foundation/umi-serializers/dist/esm/string.mjs
229
- function string(options = {}) {
230
- const size = options.size ?? u32();
231
- const encoding = options.encoding ?? utf8;
232
- const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;
233
- if (size === "variable") {
234
- return {
235
- ...encoding,
236
- description
237
- };
46
+ async function assertSigningCapabilityIsAvailable() {
47
+ assertIsSecureContext();
48
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") {
49
+ throw new Error("No signing implementation could be found");
238
50
  }
239
- if (typeof size === "number") {
240
- return fixSerializer(encoding, size, description);
51
+ }
52
+ async function assertVerificationCapabilityIsAvailable() {
53
+ assertIsSecureContext();
54
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.verify !== "function") {
55
+ throw new Error("No signature verification implementation could be found");
241
56
  }
242
- return {
243
- description,
244
- fixedSize: null,
245
- maxSize: null,
246
- serialize: (value) => {
247
- const contentBytes = encoding.serialize(value);
248
- const lengthBytes = size.serialize(contentBytes.length);
249
- return mergeBytes([lengthBytes, contentBytes]);
250
- },
251
- deserialize: (buffer, offset = 0) => {
252
- if (buffer.slice(offset).length === 0) {
253
- throw new DeserializingEmptyBufferError("string");
254
- }
255
- const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);
256
- const length = Number(lengthBigInt);
257
- offset = lengthOffset;
258
- const contentBuffer = buffer.slice(offset, offset + length);
259
- if (contentBuffer.length < length) {
260
- throw new NotEnoughBytesError("string", length, contentBuffer.length);
261
- }
262
- const [value, contentOffset] = encoding.deserialize(contentBuffer);
263
- offset += contentOffset;
264
- return [value, offset];
265
- }
266
- };
267
57
  }
268
58
 
269
- // src/base58.ts
270
- function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
271
- try {
272
- if (
273
- // Lowest address (32 bytes of zeroes)
274
- putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
275
- putativeBase58EncodedAddress.length > 44
276
- ) {
277
- throw new Error("Expected input string to decode to a byte array of length 32.");
278
- }
279
- const bytes = base58.serialize(putativeBase58EncodedAddress);
280
- const numBytes = bytes.byteLength;
281
- if (numBytes !== 32) {
282
- throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
283
- }
284
- } catch (e) {
285
- throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
286
- cause: e
287
- });
288
- }
59
+ // src/key-pair.ts
60
+ async function generateKeyPair() {
61
+ await assertKeyGenerationIsAvailable();
62
+ const keyPair = await crypto.subtle.generateKey(
63
+ /* algorithm */
64
+ "Ed25519",
65
+ // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
66
+ /* extractable */
67
+ false,
68
+ // Prevents the bytes of the private key from being visible to JS.
69
+ /* allowed uses */
70
+ ["sign", "verify"]
71
+ );
72
+ return keyPair;
289
73
  }
290
- function getBase58EncodedAddressCodec(config) {
291
- return string({
292
- description: config?.description ?? ("A 32-byte account address" ),
293
- encoding: base58,
294
- size: 32
295
- });
74
+
75
+ // src/signatures.ts
76
+ async function signBytes(key, data) {
77
+ await assertSigningCapabilityIsAvailable();
78
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
79
+ return new Uint8Array(signedData);
296
80
  }
297
- function getBase58EncodedAddressComparator() {
298
- return new Intl.Collator("en", {
299
- caseFirst: "lower",
300
- ignorePunctuation: false,
301
- localeMatcher: "best fit",
302
- numeric: false,
303
- sensitivity: "variant",
304
- usage: "sort"
305
- }).compare;
81
+ async function verifySignature(key, signature, data) {
82
+ await assertVerificationCapabilityIsAvailable();
83
+ return await crypto.subtle.verify("Ed25519", key, signature, data);
306
84
  }
307
85
 
308
- exports.assertIsBase58EncodedAddress = assertIsBase58EncodedAddress;
309
- exports.getBase58EncodedAddressCodec = getBase58EncodedAddressCodec;
310
- exports.getBase58EncodedAddressComparator = getBase58EncodedAddressComparator;
86
+ exports.generateKeyPair = generateKeyPair;
87
+ exports.signBytes = signBytes;
88
+ exports.verifySignature = verifySignature;
311
89
 
312
90
  return exports;
313
91
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/src/bytes.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/src/fixSerializer.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/baseX.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/base58.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/nullCharacters.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/src/utf8.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/common.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/errors.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/src/u32.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.2/node_modules/@metaplex-foundation/umi-serializers/src/utils.ts","../../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.2/node_modules/@metaplex-foundation/umi-serializers/src/string.ts","../src/base58.ts"],"names":["mergeBytes","bytesArr","totalLength","reduce","total","arr","length","result","Uint8Array","offset","forEach","set","padBytes","bytes","paddedBytes","fill","fixBytes","slice","DeserializingEmptyBufferError","Error","constructor","serializer","name","NotEnoughBytesError","expected","actual","fixSerializer","fixedBytes","description","fixedSize","maxSize","serialize","value","deserialize","buffer","InvalidBaseStringError","base","cause","message","baseX","alphabet","baseBigInt","BigInt","match","RegExp","chars","trailIndex","findIndex","c","leadingZeroes","Array","from","tailChars","base10Number","baseXPower","i","indexOf","tailBytes","unshift","Number","concat","n","repeat","sum","byte","join","base58","removeNullCharacters","replace","utf8","TextEncoder","encode","TextDecoder","decode","Endian","NumberOutOfRangeError","RangeError","min","max","numberFactory","input","littleEndian","defaultDescription","size","options","endian","Little","range","assertRange","ArrayBuffer","DataView","assertEnoughBytes","view","toDataView","get","toArrayBuffer","array","byteOffset","byteLength","u32","le","setUint32","getUint32","getSizeDescription","string","encoding","contentBytes","lengthBytes","lengthBigInt","lengthOffset","contentBuffer","contentOffset"],"mappings":";;;;;;;;AAIaA,IAAAA,aAAcC,cAAuC;AAChE,QAAMC,cAAcD,SAASE,OAAO,CAACC,OAAOC,QAAQD,QAAQC,IAAIC,QAAQ,CAAC;AACzE,QAAMC,SAAS,IAAIC,WAAWN,WAAW;AACzC,MAAIO,SAAS;AACbR,WAASS,QAASL,SAAQ;AACxBE,WAAOI,IAAIN,KAAKI,MAAM;AACtBA,cAAUJ,IAAIC;EAChB,CAAC;AACD,SAAOC;AACT;IAOaK,WAAW,CAACC,OAAmBP,WAA+B;AACzE,MAAIO,MAAMP,UAAUA;AAAQ,WAAOO;AACnC,QAAMC,cAAc,IAAIN,WAAWF,MAAM,EAAES,KAAK,CAAC;AACjDD,cAAYH,IAAIE,KAAK;AACrB,SAAOC;AACT;AAQO,IAAME,WAAW,CAACH,OAAmBP,WAC1CM,SAASC,MAAMI,MAAM,GAAGX,MAAM,GAAGA,MAAM;;;ACjClC,IAAMY,gCAAN,cAA4CC,MAAM;EAGvDC,YAAYC,Y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AIwG,cAAcxG,SAASA,QAAQ;AACjC,cAAM,IAAIiB,oBAAoB,UAAUjB,QAAQwG,cAAcxG,MAAM;MACtE;AACA,YAAM,CAAC0B,OAAO+E,aAAa,IAAIN,SAASxE,YAAY6E,aAAa;AACjErG,gBAAUsG;AACV,aAAO,CAAC/E,OAAOvB,MAAM;IACvB;;AAEJ;;;AC7EO,SAAS,6BACZ,8BACiG;AACjG,MAAI;AAEA;AAAA;AAAA,MAEI,6BAA6B,SAAS;AAAA,MAEtC,6BAA6B,SAAS;AAAA,MACxC;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,OAAO,UAAU,4BAA4B;AAC3D,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,UAAU;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAP;AACE,UAAM,IAAI,MAAM,KAAK,mEAAmE;AAAA,MACpF,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,6BACZ,QAGgC;AAChC,SAAO,OAAO;AAAA,IACV,aAAa,QAAQ,gBAAgB,OAAU,8BAA8B;AAAA,IAC7E,UAAU;AAAA,IACV,MAAM;AAAA,EACV,CAAC;AACL;AAEO,SAAS,oCAAsE;AAClF,SAAO,IAAI,KAAK,SAAS,MAAM;AAAA,IAC3B,WAAW;AAAA,IACX,mBAAmB;AAAA,IACnB,eAAe;AAAA,IACf,SAAS;AAAA,IACT,aAAa;AAAA,IACb,OAAO;AAAA,EACX,CAAC,EAAE;AACP","sourcesContent":["/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * @category Utils\n */\nexport const mergeBytes = (bytesArr: Uint8Array[]): Uint8Array => {\n const totalLength = bytesArr.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n bytesArr.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 * @category Utils\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 * @category Utils\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.slice(0, length), length);\n","/** @category Errors */\nexport class DeserializingEmptyBufferError extends Error {\n readonly name: string = 'DeserializingEmptyBufferError';\n\n constructor(serializer: string) {\n super(`Serializer [${serializer}] cannot deserialize empty buffers.`);\n }\n}\n\n/** @category Errors */\nexport class NotEnoughBytesError extends Error {\n readonly name: string = 'NotEnoughBytesError';\n\n constructor(\n serializer: string,\n expected: bigint | number,\n actual: bigint | number\n ) {\n super(\n `Serializer [${serializer}] expected ${expected} bytes, got ${actual}.`\n );\n }\n}\n\n/** @category Errors */\nexport class ExpectedFixedSizeSerializerError extends Error {\n readonly name: string = 'ExpectedFixedSizeSerializerError';\n\n constructor(message?: string) {\n message ??= 'Expected a fixed-size serializer, got a variable-size one.';\n super(message);\n }\n}\n","import { fixBytes } from './bytes';\nimport { Serializer } from './common';\nimport { NotEnoughBytesError } from './errors';\n\n/**\n * Creates a fixed-size serializer from a given serializer.\n *\n * @param serializer - The serializer to wrap into a fixed-size serializer.\n * @param fixedBytes - The fixed number of bytes to read.\n * @param description - A custom description for the serializer.\n *\n * @category Serializers\n */\nexport function fixSerializer<T, U extends T = T>(\n serializer: Serializer<T, U>,\n fixedBytes: number,\n description?: string\n): Serializer<T, U> {\n return {\n description:\n description ?? `fixed(${fixedBytes}, ${serializer.description})`,\n fixedSize: fixedBytes,\n maxSize: fixedBytes,\n serialize: (value: T) => fixBytes(serializer.serialize(value), fixedBytes),\n deserialize: (buffer: Uint8Array, offset = 0) => {\n // Slice the buffer to the fixed size.\n buffer = buffer.slice(offset, offset + fixedBytes);\n // Ensure we have enough bytes.\n if (buffer.length < fixedBytes) {\n throw new NotEnoughBytesError(\n 'fixSerializer',\n fixedBytes,\n buffer.length\n );\n }\n // If the nested serializer is fixed-size, pad and truncate the buffer accordingly.\n if (serializer.fixedSize !== null) {\n buffer = fixBytes(buffer, serializer.fixedSize);\n }\n // Deserialize the value using the nested serializer.\n const [value] = serializer.deserialize(buffer, 0);\n return [value, offset + fixedBytes];\n },\n };\n}\n","/** @category Errors */\nexport class InvalidBaseStringError extends Error {\n readonly name: string = 'InvalidBaseStringError';\n\n readonly cause?: Error;\n\n constructor(value: string, base: number, cause?: Error) {\n const message = `Expected a string of base ${base}, got [${value}].`;\n super(message);\n this.cause = cause;\n }\n}\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { InvalidBaseStringError } from './errors';\n\n/**\n * A string serializer that uses a custom alphabet.\n * This can be used to create serializers for base58, base64, etc.\n * @category Serializers\n */\nexport const baseX = (alphabet: string): Serializer<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n fixedSize: null,\n maxSize: null,\n serialize(value: string): Uint8Array {\n // Check if the value is valid.\n if (!value.match(new RegExp(`^[${alphabet}]*$`))) {\n throw new InvalidBaseStringError(value, base);\n }\n if (value === '') return new Uint8Array();\n\n // Handle leading zeroes.\n const chars = [...value];\n let trailIndex = chars.findIndex((c) => c !== alphabet[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length) return Uint8Array.from(leadingZeroes);\n\n // From baseX to base10.\n const tailChars = chars.slice(trailIndex);\n let base10Number = 0n;\n let baseXPower = 1n;\n for (let i = tailChars.length - 1; i >= 0; i -= 1) {\n base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\n\n // From base10 to bytes.\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n return Uint8Array.from(leadingZeroes.concat(tailBytes));\n },\n deserialize(buffer, offset = 0): [string, number] {\n if (buffer.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n const bytes = buffer.slice(offset);\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, buffer.length];\n\n // From bytes to base10.\n let base10Number = bytes\n .slice(trailIndex)\n .reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n\n return [leadingZeroes + tailChars.join(''), buffer.length];\n },\n };\n};\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { baseX } from './baseX';\n\n/**\n * A string serializer that uses base58 encoding.\n * @category Serializers\n */\nexport const base58: Serializer<string> = baseX(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n","/**\n * Removes null characters from a string.\n * @category Utils\n */\nexport const removeNullCharacters = (value: string) =>\n // eslint-disable-next-line no-control-regex\n value.replace(/\\u0000/g, '');\n\n/**\n * Pads a string with null characters at the end.\n * @category Utils\n */\nexport const padNullCharacters = (value: string, chars: number) =>\n value.padEnd(chars, '\\u0000');\n","import type { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { removeNullCharacters } from './nullCharacters';\n\n/**\n * A string serializer that uses UTF-8 encoding\n * using the native `TextEncoder` API.\n * @category Serializers\n */\nexport const utf8: Serializer<string> = {\n description: 'utf8',\n fixedSize: null,\n maxSize: null,\n serialize(value: string) {\n return new TextEncoder().encode(value);\n },\n deserialize(buffer, offset = 0) {\n const value = new TextDecoder().decode(buffer.slice(offset));\n return [removeNullCharacters(value), buffer.length];\n },\n};\n","import {\n BaseSerializerOptions,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\n\n/**\n * Defines a serializer for numbers and bigints.\n * @category Serializers\n */\nexport type NumberSerializer =\n | Serializer<number>\n | Serializer<number | bigint, bigint>;\n\n/**\n * Defines the options for u8 and i8 serializers.\n * @category Serializers\n */\nexport type SingleByteNumberSerializerOptions = BaseSerializerOptions;\n\n/**\n * Defines the options for number serializers that use more than one byte.\n * @category Serializers\n */\nexport type NumberSerializerOptions = BaseSerializerOptions & {\n /**\n * Whether the serializer should use little-endian or big-endian encoding.\n * @defaultValue `Endian.Little`\n */\n endian?: Endian;\n};\n\n/**\n * Defines the endianness of a number serializer.\n * @category Serializers\n */\nexport enum Endian {\n Little = 'le',\n Big = 'be',\n}\n","/** @category Errors */\nexport class NumberOutOfRangeError extends RangeError {\n readonly name: string = 'NumberOutOfRangeError';\n\n constructor(\n serializer: string,\n min: number | bigint,\n max: number | bigint,\n actual: number | bigint\n ) {\n super(\n `Serializer [${serializer}] expected number to be between ${min} and ${max}, got ${actual}.`\n );\n }\n}\n","import {\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n} from '@metaplex-foundation/umi-serializers-core';\nimport {\n Endian,\n NumberSerializer,\n NumberSerializerOptions,\n SingleByteNumberSerializerOptions,\n} from './common';\nimport { NumberOutOfRangeError } from './errors';\n\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => number;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): Serializer<number>;\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => bigint;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): Serializer<number | bigint, bigint>;\nexport function numberFactory(input: {\n name: string;\n size: number;\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: number | bigint, littleEndian?: boolean) => void;\n get: (view: DataView, littleEndian?: boolean) => number | bigint;\n options: SingleByteNumberSerializerOptions | NumberSerializerOptions;\n}): NumberSerializer {\n let littleEndian: boolean | undefined;\n let defaultDescription: string = input.name;\n\n if (input.size > 1) {\n littleEndian =\n !('endian' in input.options) || input.options.endian === Endian.Little;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.options.description ?? defaultDescription,\n fixedSize: input.size,\n maxSize: input.size,\n serialize(value: number | bigint): Uint8Array {\n if (input.range) {\n assertRange(input.name, input.range[0], input.range[1], value);\n }\n const buffer = new ArrayBuffer(input.size);\n input.set(new DataView(buffer), value, littleEndian);\n return new Uint8Array(buffer);\n },\n deserialize(bytes, offset = 0): [number | bigint, number] {\n const slice = bytes.slice(offset, offset + input.size);\n assertEnoughBytes('i8', slice, input.size);\n const view = toDataView(slice);\n return [input.get(view, littleEndian), offset + input.size];\n },\n } as NumberSerializer;\n}\n\n/**\n * Helper function to ensure that the array buffer is converted properly from a uint8array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n * @param {Uint8Array} array Uint8array that's being converted into an array buffer\n * @returns {ArrayBuffer} An array buffer that's necessary to construct a data view\n */\nexport const toArrayBuffer = (array: Uint8Array): ArrayBuffer =>\n array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);\n\nexport const toDataView = (array: Uint8Array): DataView =>\n new DataView(toArrayBuffer(array));\n\nexport const assertRange = (\n serializer: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint\n) => {\n if (value < min || value > max) {\n throw new NumberOutOfRangeError(serializer, min, max, value);\n }\n};\n\nexport const assertEnoughBytes = (\n serializer: string,\n bytes: Uint8Array,\n expected: number\n) => {\n if (bytes.length === 0) {\n throw new DeserializingEmptyBufferError(serializer);\n }\n if (bytes.length < expected) {\n throw new NotEnoughBytesError(serializer, expected, bytes.length);\n }\n};\n","import { Serializer } from '@metaplex-foundation/umi-serializers-core';\nimport { NumberSerializerOptions } from './common';\nimport { numberFactory } from './utils';\n\nexport const u32 = (\n options: NumberSerializerOptions = {}\n): Serializer<number> =>\n numberFactory({\n name: 'u32',\n size: 4,\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, Number(value), le),\n get: (view, le) => view.getUint32(0, le),\n options,\n });\n","import { ExpectedFixedSizeSerializerError } from '@metaplex-foundation/umi-serializers-core';\nimport { ArrayLikeSerializerSize } from './arrayLikeSerializerSize';\nimport {\n InvalidArrayLikeRemainderSizeError,\n UnrecognizedArrayLikeSerializerSizeError,\n} from './errors';\nimport { sumSerializerSizes } from './sumSerializerSizes';\n\nexport function getResolvedSize(\n size: ArrayLikeSerializerSize,\n childrenSizes: (number | null)[],\n bytes: Uint8Array,\n offset: number\n): [number | bigint, number] {\n if (typeof size === 'number') {\n return [size, offset];\n }\n\n if (typeof size === 'object') {\n return size.deserialize(bytes, offset);\n }\n\n if (size === 'remainder') {\n const childrenSize = sumSerializerSizes(childrenSizes);\n if (childrenSize === null) {\n throw new ExpectedFixedSizeSerializerError(\n 'Serializers of \"remainder\" size must have fixed-size items.'\n );\n }\n const remainder = bytes.slice(offset).length;\n if (remainder % childrenSize !== 0) {\n throw new InvalidArrayLikeRemainderSizeError(remainder, childrenSize);\n }\n return [remainder / childrenSize, offset];\n }\n\n throw new UnrecognizedArrayLikeSerializerSizeError(size);\n}\n\nexport function getSizeDescription(\n size: ArrayLikeSerializerSize | string\n): string {\n return typeof size === 'object' ? size.description : `${size}`;\n}\n\nexport function getSizeFromChildren(\n size: ArrayLikeSerializerSize,\n childrenSizes: (number | null)[]\n): number | null {\n if (typeof size !== 'number') return null;\n if (size === 0) return 0;\n const childrenSize = sumSerializerSizes(childrenSizes);\n return childrenSize === null ? null : childrenSize * size;\n}\n\nexport function getSizePrefix(\n size: ArrayLikeSerializerSize,\n realSize: number\n): Uint8Array {\n return typeof size === 'object' ? size.serialize(realSize) : new Uint8Array();\n}\n","import {\n BaseSerializerOptions,\n DeserializingEmptyBufferError,\n NotEnoughBytesError,\n Serializer,\n fixSerializer,\n mergeBytes,\n} from '@metaplex-foundation/umi-serializers-core';\nimport { utf8 } from '@metaplex-foundation/umi-serializers-encodings';\nimport {\n NumberSerializer,\n u32,\n} from '@metaplex-foundation/umi-serializers-numbers';\nimport { getSizeDescription } from './utils';\n\n/**\n * Defines the options for string serializers.\n * @category Serializers\n */\nexport type StringSerializerOptions = BaseSerializerOptions & {\n /**\n * The size of the string. It can be one of the following:\n * - a {@link NumberSerializer} that prefixes the string with its size.\n * - a fixed number of bytes.\n * - or `'variable'` to use the rest of the buffer.\n * @defaultValue `u32()`\n */\n size?: NumberSerializer | number | 'variable';\n /**\n * The string serializer to use for encoding and decoding the content.\n * @defaultValue `utf8`\n */\n encoding?: Serializer<string>;\n};\n\n/**\n * Creates a string serializer.\n *\n * @param options - A set of options for the serializer.\n * @category Serializers\n */\nexport function string(\n options: StringSerializerOptions = {}\n): Serializer<string> {\n const size = options.size ?? u32();\n const encoding = options.encoding ?? utf8;\n const description =\n options.description ??\n `string(${encoding.description}; ${getSizeDescription(size)})`;\n\n if (size === 'variable') {\n return { ...encoding, description };\n }\n\n if (typeof size === 'number') {\n return fixSerializer(encoding, size, description);\n }\n\n return {\n description,\n fixedSize: null,\n maxSize: null,\n serialize: (value: string) => {\n const contentBytes = encoding.serialize(value);\n const lengthBytes = size.serialize(contentBytes.length);\n return mergeBytes([lengthBytes, contentBytes]);\n },\n deserialize: (buffer: Uint8Array, offset = 0) => {\n if (buffer.slice(offset).length === 0) {\n throw new DeserializingEmptyBufferError('string');\n }\n const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);\n const length = Number(lengthBigInt);\n offset = lengthOffset;\n const contentBuffer = buffer.slice(offset, offset + length);\n if (contentBuffer.length < length) {\n throw new NotEnoughBytesError('string', length, contentBuffer.length);\n }\n const [value, contentOffset] = encoding.deserialize(contentBuffer);\n offset += contentOffset;\n return [value, offset];\n },\n };\n}\n","import { base58, Serializer, string } from '@metaplex-foundation/umi-serializers';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __base58EncodedAddress: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\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 putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.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 bytes = base58.serialize(putativeBase58EncodedAddress);\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(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function getBase58EncodedAddressCodec(\n config?: Readonly<{\n description: string;\n }>\n): Serializer<Base58EncodedAddress> {\n return string({\n description: config?.description ?? (__DEV__ ? 'A 32-byte account address' : ''),\n encoding: base58,\n size: 32,\n }) as unknown as Serializer<Base58EncodedAddress>;\n}\n\nexport function getBase58EncodedAddressComparator(): (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"]}
1
+ {"version":3,"sources":["../../assertions/src/subtle-crypto.ts","../src/key-pair.ts","../src/signatures.ts"],"names":[],"mappings":";AAAA,SAAS,wBAAwB;AAC7B,MAAmB,CAAC,WAAW,iBAAiB;AAE5C,UAAM,IAAI;MACN;IAEJ;EACJ;AACJ;AAEA,I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AW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEA,eAAsB,gBAAgB,KAAgB,WAA6B,MAAoC;AACnH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,WAAW,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","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\n\nexport type Ed25519Signature = Uint8Array & { readonly __brand: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -1,45 +1,30 @@
1
- import { base58, string } from '@metaplex-foundation/umi-serializers';
1
+ import { assertKeyGenerationIsAvailable, assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';
2
2
 
3
- // ../build-scripts/env-shim.ts
4
- var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
5
- function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
6
- try {
7
- if (
8
- // Lowest address (32 bytes of zeroes)
9
- putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
10
- putativeBase58EncodedAddress.length > 44
11
- ) {
12
- throw new Error("Expected input string to decode to a byte array of length 32.");
13
- }
14
- const bytes = base58.serialize(putativeBase58EncodedAddress);
15
- const numBytes = bytes.byteLength;
16
- if (numBytes !== 32) {
17
- throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
18
- }
19
- } catch (e) {
20
- throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
21
- cause: e
22
- });
23
- }
3
+ // src/key-pair.ts
4
+ async function generateKeyPair() {
5
+ await assertKeyGenerationIsAvailable();
6
+ const keyPair = await crypto.subtle.generateKey(
7
+ /* algorithm */
8
+ "Ed25519",
9
+ // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
10
+ /* extractable */
11
+ false,
12
+ // Prevents the bytes of the private key from being visible to JS.
13
+ /* allowed uses */
14
+ ["sign", "verify"]
15
+ );
16
+ return keyPair;
24
17
  }
25
- function getBase58EncodedAddressCodec(config) {
26
- return string({
27
- description: config?.description ?? (__DEV__ ? "A 32-byte account address" : ""),
28
- encoding: base58,
29
- size: 32
30
- });
18
+ async function signBytes(key, data) {
19
+ await assertSigningCapabilityIsAvailable();
20
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
21
+ return new Uint8Array(signedData);
31
22
  }
32
- function getBase58EncodedAddressComparator() {
33
- return new Intl.Collator("en", {
34
- caseFirst: "lower",
35
- ignorePunctuation: false,
36
- localeMatcher: "best fit",
37
- numeric: false,
38
- sensitivity: "variant",
39
- usage: "sort"
40
- }).compare;
23
+ async function verifySignature(key, signature, data) {
24
+ await assertVerificationCapabilityIsAvailable();
25
+ return await crypto.subtle.verify("Ed25519", key, signature, data);
41
26
  }
42
27
 
43
- export { assertIsBase58EncodedAddress, getBase58EncodedAddressCodec, getBase58EncodedAddressComparator };
28
+ export { generateKeyPair, signBytes, verifySignature };
44
29
  //# sourceMappingURL=out.js.map
45
30
  //# sourceMappingURL=index.native.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../build-scripts/env-shim.ts","../src/base58.ts"],"names":[],"mappings":";AACO,IAAM,UAA2B,uBAAO,QAAgB,KAAU,EAAE,aAAa,eAAe;;;ACDvG,SAAS,QAAoB,cAAc;AAMpC,SAAS,6BACZ,8BACiG;AACjG,MAAI;AAEA;AAAA;AAAA,MAEI,6BAA6B,SAAS;AAAA,MAEtC,6BAA6B,SAAS;AAAA,MACxC;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,OAAO,UAAU,4BAA4B;AAC3D,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,UAAU;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAP;AACE,UAAM,IAAI,MAAM,KAAK,mEAAmE;AAAA,MACpF,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,6BACZ,QAGgC;AAChC,SAAO,OAAO;AAAA,IACV,aAAa,QAAQ,gBAAgB,UAAU,8BAA8B;AAAA,IAC7E,UAAU;AAAA,IACV,MAAM;AAAA,EACV,CAAC;AACL;AAEO,SAAS,oCAAsE;AAClF,SAAO,IAAI,KAAK,SAAS,MAAM;AAAA,IAC3B,WAAW;AAAA,IACX,mBAAmB;AAAA,IACnB,eAAe;AAAA,IACf,SAAS;AAAA,IACT,aAAa;AAAA,IACb,OAAO;AAAA,EACX,CAAC,EAAE;AACP","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","import { base58, Serializer, string } from '@metaplex-foundation/umi-serializers';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __base58EncodedAddress: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\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 putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.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 bytes = base58.serialize(putativeBase58EncodedAddress);\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(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function getBase58EncodedAddressCodec(\n config?: Readonly<{\n description: string;\n }>\n): Serializer<Base58EncodedAddress> {\n return string({\n description: config?.description ?? (__DEV__ ? 'A 32-byte account address' : ''),\n encoding: base58,\n size: 32,\n }) as unknown as Serializer<Base58EncodedAddress>;\n}\n\nexport function getBase58EncodedAddressComparator(): (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"]}
1
+ {"version":3,"sources":["../src/key-pair.ts","../src/signatures.ts"],"names":[],"mappings":";AAAA,SAAS,sCAAsC;AAE/C,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC,QAAM,UAAU,MAAM,OAAO,OAAO;AAAA;AAAA,IAChB;AAAA;AAAA;AAAA,IACE;AAAA;AAAA;AAAA,IACC,CAAC,QAAQ,QAAQ;AAAA,EACxC;AACA,SAAO;AACX;;;ACVA,SAAS,oCAAoC,+CAA+C;AAI5F,eAAsB,UAAU,KAAgB,MAA6C;AACzF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEA,eAAsB,gBAAgB,KAAgB,WAA6B,MAAoC;AACnH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,WAAW,IAAI;AACrE","sourcesContent":["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","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\n\nexport type Ed25519Signature = Uint8Array & { readonly __brand: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -1,49 +1,34 @@
1
1
  'use strict';
2
2
 
3
- var umiSerializers = require('@metaplex-foundation/umi-serializers');
3
+ var assertions = require('@solana/assertions');
4
4
 
5
- // ../build-scripts/env-shim.ts
6
- var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
7
- function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
8
- try {
9
- if (
10
- // Lowest address (32 bytes of zeroes)
11
- putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
12
- putativeBase58EncodedAddress.length > 44
13
- ) {
14
- throw new Error("Expected input string to decode to a byte array of length 32.");
15
- }
16
- const bytes = umiSerializers.base58.serialize(putativeBase58EncodedAddress);
17
- const numBytes = bytes.byteLength;
18
- if (numBytes !== 32) {
19
- throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
20
- }
21
- } catch (e) {
22
- throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
23
- cause: e
24
- });
25
- }
5
+ // src/key-pair.ts
6
+ async function generateKeyPair() {
7
+ await assertions.assertKeyGenerationIsAvailable();
8
+ const keyPair = await crypto.subtle.generateKey(
9
+ /* algorithm */
10
+ "Ed25519",
11
+ // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
12
+ /* extractable */
13
+ false,
14
+ // Prevents the bytes of the private key from being visible to JS.
15
+ /* allowed uses */
16
+ ["sign", "verify"]
17
+ );
18
+ return keyPair;
26
19
  }
27
- function getBase58EncodedAddressCodec(config) {
28
- return umiSerializers.string({
29
- description: config?.description ?? (__DEV__ ? "A 32-byte account address" : ""),
30
- encoding: umiSerializers.base58,
31
- size: 32
32
- });
20
+ async function signBytes(key, data) {
21
+ await assertions.assertSigningCapabilityIsAvailable();
22
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
23
+ return new Uint8Array(signedData);
33
24
  }
34
- function getBase58EncodedAddressComparator() {
35
- return new Intl.Collator("en", {
36
- caseFirst: "lower",
37
- ignorePunctuation: false,
38
- localeMatcher: "best fit",
39
- numeric: false,
40
- sensitivity: "variant",
41
- usage: "sort"
42
- }).compare;
25
+ async function verifySignature(key, signature, data) {
26
+ await assertions.assertVerificationCapabilityIsAvailable();
27
+ return await crypto.subtle.verify("Ed25519", key, signature, data);
43
28
  }
44
29
 
45
- exports.assertIsBase58EncodedAddress = assertIsBase58EncodedAddress;
46
- exports.getBase58EncodedAddressCodec = getBase58EncodedAddressCodec;
47
- exports.getBase58EncodedAddressComparator = getBase58EncodedAddressComparator;
30
+ exports.generateKeyPair = generateKeyPair;
31
+ exports.signBytes = signBytes;
32
+ exports.verifySignature = verifySignature;
48
33
  //# sourceMappingURL=out.js.map
49
34
  //# sourceMappingURL=index.node.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../build-scripts/env-shim.ts","../src/base58.ts"],"names":[],"mappings":";AACO,IAAM,UAA2B,uBAAO,QAAgB,KAAU,EAAE,aAAa,eAAe;;;ACDvG,SAAS,QAAoB,cAAc;AAMpC,SAAS,6BACZ,8BACiG;AACjG,MAAI;AAEA;AAAA;AAAA,MAEI,6BAA6B,SAAS;AAAA,MAEtC,6BAA6B,SAAS;AAAA,MACxC;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,OAAO,UAAU,4BAA4B;AAC3D,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,UAAU;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAP;AACE,UAAM,IAAI,MAAM,KAAK,mEAAmE;AAAA,MACpF,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,6BACZ,QAGgC;AAChC,SAAO,OAAO;AAAA,IACV,aAAa,QAAQ,gBAAgB,UAAU,8BAA8B;AAAA,IAC7E,UAAU;AAAA,IACV,MAAM;AAAA,EACV,CAAC;AACL;AAEO,SAAS,oCAAsE;AAClF,SAAO,IAAI,KAAK,SAAS,MAAM;AAAA,IAC3B,WAAW;AAAA,IACX,mBAAmB;AAAA,IACnB,eAAe;AAAA,IACf,SAAS;AAAA,IACT,aAAa;AAAA,IACb,OAAO;AAAA,EACX,CAAC,EAAE;AACP","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","import { base58, Serializer, string } from '@metaplex-foundation/umi-serializers';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __base58EncodedAddress: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\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 putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.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 bytes = base58.serialize(putativeBase58EncodedAddress);\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(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function getBase58EncodedAddressCodec(\n config?: Readonly<{\n description: string;\n }>\n): Serializer<Base58EncodedAddress> {\n return string({\n description: config?.description ?? (__DEV__ ? 'A 32-byte account address' : ''),\n encoding: base58,\n size: 32,\n }) as unknown as Serializer<Base58EncodedAddress>;\n}\n\nexport function getBase58EncodedAddressComparator(): (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"]}
1
+ {"version":3,"sources":["../src/key-pair.ts","../src/signatures.ts"],"names":[],"mappings":";AAAA,SAAS,sCAAsC;AAE/C,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC,QAAM,UAAU,MAAM,OAAO,OAAO;AAAA;AAAA,IAChB;AAAA;AAAA;AAAA,IACE;AAAA;AAAA;AAAA,IACC,CAAC,QAAQ,QAAQ;AAAA,EACxC;AACA,SAAO;AACX;;;ACVA,SAAS,oCAAoC,+CAA+C;AAI5F,eAAsB,UAAU,KAAgB,MAA6C;AACzF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEA,eAAsB,gBAAgB,KAAgB,WAA6B,MAAoC;AACnH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,WAAW,IAAI;AACrE","sourcesContent":["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","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\n\nexport type Ed25519Signature = Uint8Array & { readonly __brand: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -1,45 +1,30 @@
1
- import { base58, string } from '@metaplex-foundation/umi-serializers';
1
+ import { assertKeyGenerationIsAvailable, assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';
2
2
 
3
- // ../build-scripts/env-shim.ts
4
- var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
5
- function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
6
- try {
7
- if (
8
- // Lowest address (32 bytes of zeroes)
9
- putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
10
- putativeBase58EncodedAddress.length > 44
11
- ) {
12
- throw new Error("Expected input string to decode to a byte array of length 32.");
13
- }
14
- const bytes = base58.serialize(putativeBase58EncodedAddress);
15
- const numBytes = bytes.byteLength;
16
- if (numBytes !== 32) {
17
- throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
18
- }
19
- } catch (e) {
20
- throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
21
- cause: e
22
- });
23
- }
3
+ // src/key-pair.ts
4
+ async function generateKeyPair() {
5
+ await assertKeyGenerationIsAvailable();
6
+ const keyPair = await crypto.subtle.generateKey(
7
+ /* algorithm */
8
+ "Ed25519",
9
+ // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
10
+ /* extractable */
11
+ false,
12
+ // Prevents the bytes of the private key from being visible to JS.
13
+ /* allowed uses */
14
+ ["sign", "verify"]
15
+ );
16
+ return keyPair;
24
17
  }
25
- function getBase58EncodedAddressCodec(config) {
26
- return string({
27
- description: config?.description ?? (__DEV__ ? "A 32-byte account address" : ""),
28
- encoding: base58,
29
- size: 32
30
- });
18
+ async function signBytes(key, data) {
19
+ await assertSigningCapabilityIsAvailable();
20
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
21
+ return new Uint8Array(signedData);
31
22
  }
32
- function getBase58EncodedAddressComparator() {
33
- return new Intl.Collator("en", {
34
- caseFirst: "lower",
35
- ignorePunctuation: false,
36
- localeMatcher: "best fit",
37
- numeric: false,
38
- sensitivity: "variant",
39
- usage: "sort"
40
- }).compare;
23
+ async function verifySignature(key, signature, data) {
24
+ await assertVerificationCapabilityIsAvailable();
25
+ return await crypto.subtle.verify("Ed25519", key, signature, data);
41
26
  }
42
27
 
43
- export { assertIsBase58EncodedAddress, getBase58EncodedAddressCodec, getBase58EncodedAddressComparator };
28
+ export { generateKeyPair, signBytes, verifySignature };
44
29
  //# sourceMappingURL=out.js.map
45
30
  //# sourceMappingURL=index.node.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../build-scripts/env-shim.ts","../src/base58.ts"],"names":[],"mappings":";AACO,IAAM,UAA2B,uBAAO,QAAgB,KAAU,EAAE,aAAa,eAAe;;;ACDvG,SAAS,QAAoB,cAAc;AAMpC,SAAS,6BACZ,8BACiG;AACjG,MAAI;AAEA;AAAA;AAAA,MAEI,6BAA6B,SAAS;AAAA,MAEtC,6BAA6B,SAAS;AAAA,MACxC;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,OAAO,UAAU,4BAA4B;AAC3D,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,UAAU;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAP;AACE,UAAM,IAAI,MAAM,KAAK,mEAAmE;AAAA,MACpF,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,6BACZ,QAGgC;AAChC,SAAO,OAAO;AAAA,IACV,aAAa,QAAQ,gBAAgB,UAAU,8BAA8B;AAAA,IAC7E,UAAU;AAAA,IACV,MAAM;AAAA,EACV,CAAC;AACL;AAEO,SAAS,oCAAsE;AAClF,SAAO,IAAI,KAAK,SAAS,MAAM;AAAA,IAC3B,WAAW;AAAA,IACX,mBAAmB;AAAA,IACnB,eAAe;AAAA,IACf,SAAS;AAAA,IACT,aAAa;AAAA,IACb,OAAO;AAAA,EACX,CAAC,EAAE;AACP","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","import { base58, Serializer, string } from '@metaplex-foundation/umi-serializers';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __base58EncodedAddress: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\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 putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.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 bytes = base58.serialize(putativeBase58EncodedAddress);\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(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function getBase58EncodedAddressCodec(\n config?: Readonly<{\n description: string;\n }>\n): Serializer<Base58EncodedAddress> {\n return string({\n description: config?.description ?? (__DEV__ ? 'A 32-byte account address' : ''),\n encoding: base58,\n size: 32,\n }) as unknown as Serializer<Base58EncodedAddress>;\n}\n\nexport function getBase58EncodedAddressComparator(): (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"]}
1
+ {"version":3,"sources":["../src/key-pair.ts","../src/signatures.ts"],"names":[],"mappings":";AAAA,SAAS,sCAAsC;AAE/C,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC,QAAM,UAAU,MAAM,OAAO,OAAO;AAAA;AAAA,IAChB;AAAA;AAAA;AAAA,IACE;AAAA;AAAA;AAAA,IACC,CAAC,QAAQ,QAAQ;AAAA,EACxC;AACA,SAAO;AACX;;;ACVA,SAAS,oCAAoC,+CAA+C;AAI5F,eAAsB,UAAU,KAAgB,MAA6C;AACzF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEA,eAAsB,gBAAgB,KAAgB,WAA6B,MAAoC;AACnH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,WAAW,IAAI;AACrE","sourcesContent":["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","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\n\nexport type Ed25519Signature = Uint8Array & { readonly __brand: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -2,11 +2,15 @@ this.globalThis = this.globalThis || {};
2
2
  this.globalThis.solanaWeb3 = (function (exports) {
3
3
  'use strict';
4
4
 
5
- var O=Object.defineProperty;var U=(e,r,t)=>r in e?O(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var u=(e,r,t)=>(U(e,typeof r!="symbol"?r+"":r,t),t);var S=e=>{let r=e.reduce((n,i)=>n+i.length,0),t=new Uint8Array(r),o=0;return e.forEach(n=>{t.set(n,o),o+=n.length;}),t},N=(e,r)=>{if(e.length>=r)return e;let t=new Uint8Array(r).fill(0);return t.set(e),t},g=(e,r)=>N(e.slice(0,r),r);var x=class extends Error{constructor(t){super(`Serializer [${t}] cannot deserialize empty buffers.`);u(this,"name","DeserializingEmptyBufferError");}},d=class extends Error{constructor(t,o,n){super(`Serializer [${t}] expected ${o} bytes, got ${n}.`);u(this,"name","NotEnoughBytesError");}};function w(e,r,t){return {description:t??`fixed(${r}, ${e.description})`,fixedSize:r,maxSize:r,serialize:o=>g(e.serialize(o),r),deserialize:(o,n=0)=>{if(o=o.slice(n,n+r),o.length<r)throw new d("fixSerializer",r,o.length);e.fixedSize!==null&&(o=g(o,e.fixedSize));let[i]=e.deserialize(o,0);return [i,n+r]}}}var z=class extends Error{constructor(t,o,n){let i=`Expected a string of base ${o}, got [${t}].`;super(i);u(this,"name","InvalidBaseStringError");this.cause=n;}};var $=e=>{let r=e.length,t=BigInt(r);return {description:`base${r}`,fixedSize:null,maxSize:null,serialize(o){if(!o.match(new RegExp(`^[${e}]*$`)))throw new z(o,r);if(o==="")return new Uint8Array;let n=[...o],i=n.findIndex(m=>m!==e[0]);i=i===-1?n.length:i;let a=Array(i).fill(0);if(i===n.length)return Uint8Array.from(a);let p=n.slice(i),l=0n,c=1n;for(let m=p.length-1;m>=0;m-=1)l+=c*BigInt(e.indexOf(p[m])),c*=t;let f=[];for(;l>0n;)f.unshift(Number(l%256n)),l/=256n;return Uint8Array.from(a.concat(f))},deserialize(o,n=0){if(o.length===0)return ["",0];let i=o.slice(n),a=i.findIndex(f=>f!==0);a=a===-1?i.length:a;let p=e[0].repeat(a);if(a===i.length)return [p,o.length];let l=i.slice(a).reduce((f,m)=>f*256n+BigInt(m),0n),c=[];for(;l>0n;)c.unshift(e[Number(l%t)]),l/=t;return [p+c.join(""),o.length]}}};var h=$("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var I=e=>e.replace(/\u0000/g,"");var b={description:"utf8",fixedSize:null,maxSize:null,serialize(e){return new TextEncoder().encode(e)},deserialize(e,r=0){let t=new TextDecoder().decode(e.slice(r));return [I(t),e.length]}};var E;(function(e){e.Little="le",e.Big="be";})(E||(E={}));var y=class extends RangeError{constructor(t,o,n,i){super(`Serializer [${t}] expected number to be between ${o} and ${n}, got ${i}.`);u(this,"name","NumberOutOfRangeError");}};function v(e){let r,t=e.name;return e.size>1&&(r=!("endian"in e.options)||e.options.endian===E.Little,t+=r?"(le)":"(be)"),{description:e.options.description??t,fixedSize:e.size,maxSize:e.size,serialize(o){e.range&&_(e.name,e.range[0],e.range[1],o);let n=new ArrayBuffer(e.size);return e.set(new DataView(n),o,r),new Uint8Array(n)},deserialize(o,n=0){let i=o.slice(n,n+e.size);L("i8",i,e.size);let a=R(i);return [e.get(a,r),n+e.size]}}}var C=e=>e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset),R=e=>new DataView(C(e)),_=(e,r,t,o)=>{if(o<r||o>t)throw new y(e,r,t,o)},L=(e,r,t)=>{if(r.length===0)throw new x(e);if(r.length<t)throw new d(e,t,r.length)};var B=(e={})=>v({name:"u32",size:4,range:[0,+"0xffffffff"],set:(r,t,o)=>r.setUint32(0,Number(t),o),get:(r,t)=>r.getUint32(0,t),options:e});function D(e){return typeof e=="object"?e.description:`${e}`}function A(e={}){let r=e.size??B(),t=e.encoding??b,o=e.description??`string(${t.description}; ${D(r)})`;return r==="variable"?{...t,description:o}:typeof r=="number"?w(t,r,o):{description:o,fixedSize:null,maxSize:null,serialize:n=>{let i=t.serialize(n),a=r.serialize(i.length);return S([a,i])},deserialize:(n,i=0)=>{if(n.slice(i).length===0)throw new x("string");let[a,p]=r.deserialize(n,i),l=Number(a);i=p;let c=n.slice(i,i+l);if(c.length<l)throw new d("string",l,c.length);let[f,m]=t.deserialize(c);return i+=m,[f,i]}}}function Je(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 t=h.serialize(e).byteLength;if(t!==32)throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${t}`)}catch(r){throw new Error(`\`${e}\` is not a base-58 encoded address`,{cause:r})}}function Qe(e){return A({description:e?.description??"",encoding:h,size:32})}function We(){return new Intl.Collator("en",{caseFirst:"lower",ignorePunctuation:!1,localeMatcher:"best fit",numeric:!1,sensitivity:"variant",usage:"sort"}).compare}
5
+ function n(){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 e;async function y(t){return e===void 0&&(e=new Promise(o=>{t.generateKey("Ed25519",!1,["sign","verify"]).catch(()=>{o(e=!1);}).then(()=>{o(e=!0);});})),typeof e=="boolean"?e:await e}async function a(){if(n(),typeof globalThis.crypto>"u"||typeof globalThis.crypto.subtle?.generateKey!="function")throw new Error("No key generation implementation could be found");if(!await y(globalThis.crypto.subtle))throw new Error(`This runtime does not support the generation of Ed25519 key pairs.
6
6
 
7
- exports.assertIsBase58EncodedAddress = Je;
8
- exports.getBase58EncodedAddressCodec = Qe;
9
- exports.getBase58EncodedAddressComparator = We;
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 s(){if(n(),typeof globalThis.crypto>"u"||typeof globalThis.crypto.subtle?.sign!="function")throw new Error("No signing implementation could be found")}async function l(){if(n(),typeof globalThis.crypto>"u"||typeof globalThis.crypto.subtle?.verify!="function")throw new Error("No signature verification implementation could be found")}async function d(){return await a(),await crypto.subtle.generateKey("Ed25519",!1,["sign","verify"])}async function m(t,o){await s();let r=await crypto.subtle.sign("Ed25519",t,o);return new Uint8Array(r)}async function w(t,o,r){return await l(),await crypto.subtle.verify("Ed25519",t,o,r)}
10
+
11
+ exports.generateKeyPair = d;
12
+ exports.signBytes = m;
13
+ exports.verifySignature = w;
10
14
 
11
15
  return exports;
12
16
 
@@ -1,2 +1,3 @@
1
- export * from './base58';
1
+ export * from './key-pair';
2
+ export * from './signatures';
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,2 @@
1
+ export declare function generateKeyPair(): Promise<CryptoKeyPair>;
2
+ //# sourceMappingURL=key-pair.d.ts.map
@@ -0,0 +1,6 @@
1
+ export type Ed25519Signature = Uint8Array & {
2
+ readonly __brand: unique symbol;
3
+ };
4
+ export declare function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature>;
5
+ export declare function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean>;
6
+ //# sourceMappingURL=signatures.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solana/keys",
3
- "version": "2.0.0-experimental.9bf9fdb",
3
+ "version": "2.0.0-experimental.9e133fd",
4
4
  "description": "Helpers for generating and transforming key material",
5
5
  "exports": {
6
6
  "browser": {
@@ -49,33 +49,29 @@
49
49
  "node": ">=17.4"
50
50
  },
51
51
  "dependencies": {
52
- "@metaplex-foundation/umi-serializers": "^0.8.2"
52
+ "@solana/assertions": "2.0.0-experimental.9e133fd"
53
53
  },
54
54
  "devDependencies": {
55
- "@solana/eslint-config-solana": "^1.0.1",
56
- "@swc/core": "^1.3.18",
57
- "@swc/jest": "^0.2.26",
58
- "@types/jest": "^29.5.2",
59
- "@typescript-eslint/eslint-plugin": "^5.57.1",
60
- "@typescript-eslint/parser": "^5.57.1",
55
+ "@solana/eslint-config-solana": "^1.0.2",
56
+ "@swc/jest": "^0.2.28",
57
+ "@types/jest": "^29.5.5",
58
+ "@typescript-eslint/eslint-plugin": "^6.7.0",
59
+ "@typescript-eslint/parser": "^6.3.0",
61
60
  "agadoo": "^3.0.0",
62
- "eslint": "^8.37.0",
63
- "eslint-plugin-jest": "^27.1.5",
64
- "eslint-plugin-react-hooks": "^4.6.0",
61
+ "eslint": "^8.45.0",
62
+ "eslint-plugin-jest": "^27.2.3",
65
63
  "eslint-plugin-sort-keys-fix": "^1.1.2",
66
- "jest": "^29.6.1",
67
- "jest-environment-jsdom": "^29.6.0",
64
+ "jest": "^29.7.0",
65
+ "jest-environment-jsdom": "^29.6.4",
68
66
  "jest-runner-eslint": "^2.1.0",
69
67
  "jest-runner-prettier": "^1.0.0",
70
- "postcss": "^8.4.12",
71
- "prettier": "^2.8.8",
72
- "ts-node": "^10.9.1",
73
- "tsup": "6.7.0",
74
- "typescript": "^5.0.4",
68
+ "prettier": "^2.8",
69
+ "tsup": "7.2.0",
70
+ "typescript": "^5.2.2",
75
71
  "version-from-git": "^1.1.1",
76
- "build-scripts": "0.0.0",
77
72
  "test-config": "0.0.0",
78
- "tsconfig": "0.0.0"
73
+ "tsconfig": "0.0.0",
74
+ "build-scripts": "0.0.0"
79
75
  },
80
76
  "bundlewatch": {
81
77
  "defaultCompression": "gzip",
@@ -90,11 +86,12 @@
90
86
  "compile:typedefs": "tsc -p ./tsconfig.declarations.json",
91
87
  "dev": "jest -c node_modules/test-config/jest-dev.config.ts --rootDir . --watch",
92
88
  "publish-packages": "pnpm publish --tag experimental --access public --no-git-checks",
89
+ "style:fix": "pnpm eslint --fix src/* && pnpm prettier -w src/* package.json",
93
90
  "test:lint": "jest -c node_modules/test-config/jest-lint.config.ts --rootDir . --silent",
94
91
  "test:prettier": "jest -c node_modules/test-config/jest-prettier.config.ts --rootDir . --silent",
95
92
  "test:treeshakability:browser": "agadoo dist/index.browser.js",
96
- "test:treeshakability:native": "agadoo dist/index.node.js",
97
- "test:treeshakability:node": "agadoo dist/index.native.js",
93
+ "test:treeshakability:native": "agadoo dist/index.native.js",
94
+ "test:treeshakability:node": "agadoo dist/index.node.js",
98
95
  "test:typecheck": "tsc --noEmit",
99
96
  "test:unit:browser": "jest -c node_modules/test-config/jest-unit.config.browser.ts --rootDir . --silent",
100
97
  "test:unit:node": "jest -c node_modules/test-config/jest-unit.config.node.ts --rootDir . --silent"
@@ -1,10 +0,0 @@
1
- import { Serializer } from '@metaplex-foundation/umi-serializers';
2
- export type Base58EncodedAddress<TAddress extends string = string> = TAddress & {
3
- readonly __base58EncodedAddress: unique symbol;
4
- };
5
- export declare function assertIsBase58EncodedAddress(putativeBase58EncodedAddress: string): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress>;
6
- export declare function getBase58EncodedAddressCodec(config?: Readonly<{
7
- description: string;
8
- }>): Serializer<Base58EncodedAddress>;
9
- export declare function getBase58EncodedAddressComparator(): (x: string, y: string) => number;
10
- //# sourceMappingURL=base58.d.ts.map