Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@solana/keys

Package Overview
Dependencies
Maintainers
13
Versions
1478
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@solana/keys - npm Package Compare versions

Comparing version 2.0.0-experimental.ca5fcbd to 2.0.0-experimental.ca7c151

dist/types/index.d.ts.map

61

dist/index.browser.js

@@ -1,45 +0,30 @@

import { base58, string } from '@metaplex-foundation/umi-serializers';
import { assertKeyGenerationIsAvailable, assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';
// ../build-scripts/env-shim.ts
var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
try {
if (
// Lowest address (32 bytes of zeroes)
putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
putativeBase58EncodedAddress.length > 44
) {
throw new Error("Expected input string to decode to a byte array of length 32.");
}
const bytes = base58.serialize(putativeBase58EncodedAddress);
const numBytes = bytes.byteLength;
if (numBytes !== 32) {
throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
}
} catch (e) {
throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
cause: e
});
}
// src/key-pair.ts
async function generateKeyPair() {
await assertKeyGenerationIsAvailable();
const keyPair = await crypto.subtle.generateKey(
/* algorithm */
"Ed25519",
// Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
/* extractable */
false,
// Prevents the bytes of the private key from being visible to JS.
/* allowed uses */
["sign", "verify"]
);
return keyPair;
}
function getBase58EncodedAddressCodec(config) {
return string({
description: config?.description ?? (__DEV__ ? "A 32-byte account address" : ""),
encoding: base58,
size: 32
});
async function signBytes(key, data) {
await assertSigningCapabilityIsAvailable();
const signedData = await crypto.subtle.sign("Ed25519", key, data);
return new Uint8Array(signedData);
}
function getBase58EncodedAddressComparator() {
return new Intl.Collator("en", {
caseFirst: "lower",
ignorePunctuation: false,
localeMatcher: "best fit",
numeric: false,
sensitivity: "variant",
usage: "sort"
}).compare;
async function verifySignature(key, signature, data) {
await assertVerificationCapabilityIsAvailable();
return await crypto.subtle.verify("Ed25519", key, signature, data);
}
export { assertIsBase58EncodedAddress, getBase58EncodedAddressCodec, getBase58EncodedAddressComparator };
export { generateKeyPair, signBytes, verifySignature };
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.browser.js.map

@@ -5,308 +5,86 @@ this.globalThis = this.globalThis || {};

var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/bytes.mjs
var mergeBytes = (bytesArr) => {
const totalLength = bytesArr.reduce((total, arr) => total + arr.length, 0);
const result = new Uint8Array(totalLength);
let offset = 0;
bytesArr.forEach((arr) => {
result.set(arr, offset);
offset += arr.length;
});
return result;
};
var padBytes = (bytes, length) => {
if (bytes.length >= length)
return bytes;
const paddedBytes = new Uint8Array(length).fill(0);
paddedBytes.set(bytes);
return paddedBytes;
};
var fixBytes = (bytes, length) => padBytes(bytes.slice(0, length), length);
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/errors.mjs
var DeserializingEmptyBufferError = class extends Error {
constructor(serializer) {
super(`Serializer [${serializer}] cannot deserialize empty buffers.`);
__publicField(this, "name", "DeserializingEmptyBufferError");
// ../assertions/dist/index.browser.js
function assertIsSecureContext() {
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 NotEnoughBytesError = class extends Error {
constructor(serializer, expected, actual) {
super(`Serializer [${serializer}] expected ${expected} bytes, got ${actual}.`);
__publicField(this, "name", "NotEnoughBytesError");
}
};
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-core@0.8.2/node_modules/@metaplex-foundation/umi-serializers-core/dist/esm/fixSerializer.mjs
function fixSerializer(serializer, fixedBytes, description) {
return {
description: description ?? `fixed(${fixedBytes}, ${serializer.description})`,
fixedSize: fixedBytes,
maxSize: fixedBytes,
serialize: (value) => fixBytes(serializer.serialize(value), fixedBytes),
deserialize: (buffer, offset = 0) => {
buffer = buffer.slice(offset, offset + fixedBytes);
if (buffer.length < fixedBytes) {
throw new NotEnoughBytesError("fixSerializer", fixedBytes, buffer.length);
}
if (serializer.fixedSize !== null) {
buffer = fixBytes(buffer, serializer.fixedSize);
}
const [value] = serializer.deserialize(buffer, 0);
return [value, offset + fixedBytes];
}
};
}
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/errors.mjs
var InvalidBaseStringError = class extends Error {
constructor(value, base, cause) {
const message = `Expected a string of base ${base}, got [${value}].`;
super(message);
__publicField(this, "name", "InvalidBaseStringError");
this.cause = cause;
var cachedEd25519Decision;
async function isEd25519CurveSupported(subtle) {
if (cachedEd25519Decision === void 0) {
cachedEd25519Decision = new Promise((resolve) => {
subtle.generateKey(
"Ed25519",
/* extractable */
false,
["sign", "verify"]
).catch(() => {
resolve(cachedEd25519Decision = false);
}).then(() => {
resolve(cachedEd25519Decision = true);
});
});
}
};
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/baseX.mjs
var baseX = (alphabet) => {
const base = alphabet.length;
const baseBigInt = BigInt(base);
return {
description: `base${base}`,
fixedSize: null,
maxSize: null,
serialize(value) {
if (!value.match(new RegExp(`^[${alphabet}]*$`))) {
throw new InvalidBaseStringError(value, base);
}
if (value === "")
return new Uint8Array();
const chars = [...value];
let trailIndex = chars.findIndex((c) => c !== alphabet[0]);
trailIndex = trailIndex === -1 ? chars.length : trailIndex;
const leadingZeroes = Array(trailIndex).fill(0);
if (trailIndex === chars.length)
return Uint8Array.from(leadingZeroes);
const tailChars = chars.slice(trailIndex);
let base10Number = 0n;
let baseXPower = 1n;
for (let i = tailChars.length - 1; i >= 0; i -= 1) {
base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));
baseXPower *= baseBigInt;
}
const tailBytes = [];
while (base10Number > 0n) {
tailBytes.unshift(Number(base10Number % 256n));
base10Number /= 256n;
}
return Uint8Array.from(leadingZeroes.concat(tailBytes));
},
deserialize(buffer, offset = 0) {
if (buffer.length === 0)
return ["", 0];
const bytes = buffer.slice(offset);
let trailIndex = bytes.findIndex((n) => n !== 0);
trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
const leadingZeroes = alphabet[0].repeat(trailIndex);
if (trailIndex === bytes.length)
return [leadingZeroes, buffer.length];
let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
const tailChars = [];
while (base10Number > 0n) {
tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);
base10Number /= baseBigInt;
}
return [leadingZeroes + tailChars.join(""), buffer.length];
}
};
};
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/base58.mjs
var base58 = baseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/nullCharacters.mjs
var removeNullCharacters = (value) => (
// eslint-disable-next-line no-control-regex
value.replace(/\u0000/g, "")
);
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-encodings@0.8.2/node_modules/@metaplex-foundation/umi-serializers-encodings/dist/esm/utf8.mjs
var utf8 = {
description: "utf8",
fixedSize: null,
maxSize: null,
serialize(value) {
return new TextEncoder().encode(value);
},
deserialize(buffer, offset = 0) {
const value = new TextDecoder().decode(buffer.slice(offset));
return [removeNullCharacters(value), buffer.length];
if (typeof cachedEd25519Decision === "boolean") {
return cachedEd25519Decision;
} else {
return await cachedEd25519Decision;
}
};
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/common.mjs
var Endian;
(function(Endian2) {
Endian2["Little"] = "le";
Endian2["Big"] = "be";
})(Endian || (Endian = {}));
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/errors.mjs
var NumberOutOfRangeError = class extends RangeError {
constructor(serializer, min, max, actual) {
super(`Serializer [${serializer}] expected number to be between ${min} and ${max}, got ${actual}.`);
__publicField(this, "name", "NumberOutOfRangeError");
}
async function assertKeyGenerationIsAvailable() {
assertIsSecureContext();
if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.generateKey !== "function") {
throw new Error("No key generation implementation could be found");
}
};
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/utils.mjs
function numberFactory(input) {
let littleEndian;
let defaultDescription = input.name;
if (input.size > 1) {
littleEndian = !("endian" in input.options) || input.options.endian === Endian.Little;
defaultDescription += littleEndian ? "(le)" : "(be)";
if (!await isEd25519CurveSupported(globalThis.crypto.subtle)) {
throw new Error(
"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"
);
}
return {
description: input.options.description ?? defaultDescription,
fixedSize: input.size,
maxSize: input.size,
serialize(value) {
if (input.range) {
assertRange(input.name, input.range[0], input.range[1], value);
}
const buffer = new ArrayBuffer(input.size);
input.set(new DataView(buffer), value, littleEndian);
return new Uint8Array(buffer);
},
deserialize(bytes, offset = 0) {
const slice = bytes.slice(offset, offset + input.size);
assertEnoughBytes("i8", slice, input.size);
const view = toDataView(slice);
return [input.get(view, littleEndian), offset + input.size];
}
};
}
var toArrayBuffer = (array) => array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);
var toDataView = (array) => new DataView(toArrayBuffer(array));
var assertRange = (serializer, min, max, value) => {
if (value < min || value > max) {
throw new NumberOutOfRangeError(serializer, min, max, value);
async function assertSigningCapabilityIsAvailable() {
assertIsSecureContext();
if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") {
throw new Error("No signing implementation could be found");
}
};
var assertEnoughBytes = (serializer, bytes, expected) => {
if (bytes.length === 0) {
throw new DeserializingEmptyBufferError(serializer);
}
async function assertVerificationCapabilityIsAvailable() {
assertIsSecureContext();
if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.verify !== "function") {
throw new Error("No signature verification implementation could be found");
}
if (bytes.length < expected) {
throw new NotEnoughBytesError(serializer, expected, bytes.length);
}
};
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers-numbers@0.8.2/node_modules/@metaplex-foundation/umi-serializers-numbers/dist/esm/u32.mjs
var u32 = (options = {}) => numberFactory({
name: "u32",
size: 4,
range: [0, Number("0xffffffff")],
set: (view, value, le) => view.setUint32(0, Number(value), le),
get: (view, le) => view.getUint32(0, le),
options
});
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.2/node_modules/@metaplex-foundation/umi-serializers/dist/esm/utils.mjs
function getSizeDescription(size) {
return typeof size === "object" ? size.description : `${size}`;
}
// ../../node_modules/.pnpm/@metaplex-foundation+umi-serializers@0.8.2/node_modules/@metaplex-foundation/umi-serializers/dist/esm/string.mjs
function string(options = {}) {
const size = options.size ?? u32();
const encoding = options.encoding ?? utf8;
const description = options.description ?? `string(${encoding.description}; ${getSizeDescription(size)})`;
if (size === "variable") {
return {
...encoding,
description
};
}
if (typeof size === "number") {
return fixSerializer(encoding, size, description);
}
return {
description,
fixedSize: null,
maxSize: null,
serialize: (value) => {
const contentBytes = encoding.serialize(value);
const lengthBytes = size.serialize(contentBytes.length);
return mergeBytes([lengthBytes, contentBytes]);
},
deserialize: (buffer, offset = 0) => {
if (buffer.slice(offset).length === 0) {
throw new DeserializingEmptyBufferError("string");
}
const [lengthBigInt, lengthOffset] = size.deserialize(buffer, offset);
const length = Number(lengthBigInt);
offset = lengthOffset;
const contentBuffer = buffer.slice(offset, offset + length);
if (contentBuffer.length < length) {
throw new NotEnoughBytesError("string", length, contentBuffer.length);
}
const [value, contentOffset] = encoding.deserialize(contentBuffer);
offset += contentOffset;
return [value, offset];
}
};
// src/key-pair.ts
async function generateKeyPair() {
await assertKeyGenerationIsAvailable();
const keyPair = await crypto.subtle.generateKey(
/* algorithm */
"Ed25519",
// Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
/* extractable */
false,
// Prevents the bytes of the private key from being visible to JS.
/* allowed uses */
["sign", "verify"]
);
return keyPair;
}
// src/base58.ts
function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
try {
if (
// Lowest address (32 bytes of zeroes)
putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
putativeBase58EncodedAddress.length > 44
) {
throw new Error("Expected input string to decode to a byte array of length 32.");
}
const bytes = base58.serialize(putativeBase58EncodedAddress);
const numBytes = bytes.byteLength;
if (numBytes !== 32) {
throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
}
} catch (e) {
throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
cause: e
});
}
// src/signatures.ts
async function signBytes(key, data) {
await assertSigningCapabilityIsAvailable();
const signedData = await crypto.subtle.sign("Ed25519", key, data);
return new Uint8Array(signedData);
}
function getBase58EncodedAddressCodec(config) {
return string({
description: config?.description ?? ("A 32-byte account address" ),
encoding: base58,
size: 32
});
async function verifySignature(key, signature, data) {
await assertVerificationCapabilityIsAvailable();
return await crypto.subtle.verify("Ed25519", key, signature, data);
}
function getBase58EncodedAddressComparator() {
return new Intl.Collator("en", {
caseFirst: "lower",
ignorePunctuation: false,
localeMatcher: "best fit",
numeric: false,
sensitivity: "variant",
usage: "sort"
}).compare;
}
exports.assertIsBase58EncodedAddress = assertIsBase58EncodedAddress;
exports.getBase58EncodedAddressCodec = getBase58EncodedAddressCodec;
exports.getBase58EncodedAddressComparator = getBase58EncodedAddressComparator;
exports.generateKeyPair = generateKeyPair;
exports.signBytes = signBytes;
exports.verifySignature = verifySignature;

@@ -313,0 +91,0 @@ return exports;

@@ -1,45 +0,30 @@

import { base58, string } from '@metaplex-foundation/umi-serializers';
import { assertKeyGenerationIsAvailable, assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';
// ../build-scripts/env-shim.ts
var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
try {
if (
// Lowest address (32 bytes of zeroes)
putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
putativeBase58EncodedAddress.length > 44
) {
throw new Error("Expected input string to decode to a byte array of length 32.");
}
const bytes = base58.serialize(putativeBase58EncodedAddress);
const numBytes = bytes.byteLength;
if (numBytes !== 32) {
throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
}
} catch (e) {
throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
cause: e
});
}
// src/key-pair.ts
async function generateKeyPair() {
await assertKeyGenerationIsAvailable();
const keyPair = await crypto.subtle.generateKey(
/* algorithm */
"Ed25519",
// Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
/* extractable */
false,
// Prevents the bytes of the private key from being visible to JS.
/* allowed uses */
["sign", "verify"]
);
return keyPair;
}
function getBase58EncodedAddressCodec(config) {
return string({
description: config?.description ?? (__DEV__ ? "A 32-byte account address" : ""),
encoding: base58,
size: 32
});
async function signBytes(key, data) {
await assertSigningCapabilityIsAvailable();
const signedData = await crypto.subtle.sign("Ed25519", key, data);
return new Uint8Array(signedData);
}
function getBase58EncodedAddressComparator() {
return new Intl.Collator("en", {
caseFirst: "lower",
ignorePunctuation: false,
localeMatcher: "best fit",
numeric: false,
sensitivity: "variant",
usage: "sort"
}).compare;
async function verifySignature(key, signature, data) {
await assertVerificationCapabilityIsAvailable();
return await crypto.subtle.verify("Ed25519", key, signature, data);
}
export { assertIsBase58EncodedAddress, getBase58EncodedAddressCodec, getBase58EncodedAddressComparator };
export { generateKeyPair, signBytes, verifySignature };
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.native.js.map

@@ -1,45 +0,30 @@

import { base58, string } from '@metaplex-foundation/umi-serializers';
import { assertKeyGenerationIsAvailable, assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';
// ../build-scripts/env-shim.ts
var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
try {
if (
// Lowest address (32 bytes of zeroes)
putativeBase58EncodedAddress.length < 32 || // Highest address (32 bytes of 255)
putativeBase58EncodedAddress.length > 44
) {
throw new Error("Expected input string to decode to a byte array of length 32.");
}
const bytes = base58.serialize(putativeBase58EncodedAddress);
const numBytes = bytes.byteLength;
if (numBytes !== 32) {
throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
}
} catch (e) {
throw new Error(`\`${putativeBase58EncodedAddress}\` is not a base-58 encoded address`, {
cause: e
});
}
// src/key-pair.ts
async function generateKeyPair() {
await assertKeyGenerationIsAvailable();
const keyPair = await crypto.subtle.generateKey(
/* algorithm */
"Ed25519",
// Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
/* extractable */
false,
// Prevents the bytes of the private key from being visible to JS.
/* allowed uses */
["sign", "verify"]
);
return keyPair;
}
function getBase58EncodedAddressCodec(config) {
return string({
description: config?.description ?? (__DEV__ ? "A 32-byte account address" : ""),
encoding: base58,
size: 32
});
async function signBytes(key, data) {
await assertSigningCapabilityIsAvailable();
const signedData = await crypto.subtle.sign("Ed25519", key, data);
return new Uint8Array(signedData);
}
function getBase58EncodedAddressComparator() {
return new Intl.Collator("en", {
caseFirst: "lower",
ignorePunctuation: false,
localeMatcher: "best fit",
numeric: false,
sensitivity: "variant",
usage: "sort"
}).compare;
async function verifySignature(key, signature, data) {
await assertVerificationCapabilityIsAvailable();
return await crypto.subtle.verify("Ed25519", key, signature, data);
}
export { assertIsBase58EncodedAddress, getBase58EncodedAddressCodec, getBase58EncodedAddressComparator };
export { generateKeyPair, signBytes, verifySignature };
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.node.js.map

@@ -5,10 +5,14 @@ this.globalThis = this.globalThis || {};

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}
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.
exports.assertIsBase58EncodedAddress = Je;
exports.getBase58EncodedAddressCodec = Qe;
exports.getBase58EncodedAddressComparator = We;
Install and import \`@solana/webcrypto-ed25519-polyfill\` before generating keys in environments that do not support Ed25519.
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)}
exports.generateKeyPair = d;
exports.signBytes = m;
exports.verifySignature = w;
return exports;
})({});

@@ -1,2 +0,3 @@

export * from './base58';
export * from './key-pair';
export * from './signatures';
//# sourceMappingURL=index.d.ts.map
{
"name": "@solana/keys",
"version": "2.0.0-experimental.ca5fcbd",
"version": "2.0.0-experimental.ca7c151",
"description": "Helpers for generating and transforming key material",

@@ -48,16 +48,17 @@ "exports": {

],
"engine": {
"node": ">=17.4"
},
"dependencies": {
"@metaplex-foundation/umi-serializers": "^0.8.2"
"@solana/assertions": "2.0.0-experimental.ca7c151"
},
"devDependencies": {
"@solana/eslint-config-solana": "^1.0.1",
"@swc/core": "^1.3.18",
"@swc/jest": "^0.2.26",
"@types/jest": "^29.5.2",
"@typescript-eslint/eslint-plugin": "^5.57.1",
"@typescript-eslint/parser": "^5.57.1",
"@solana/eslint-config-solana": "^1.0.2",
"@swc/jest": "^0.2.27",
"@types/jest": "^29.5.3",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"agadoo": "^3.0.0",
"eslint": "^8.37.0",
"eslint-plugin-jest": "^27.1.5",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint": "^8.45.0",
"eslint-plugin-jest": "^27.2.3",
"eslint-plugin-sort-keys-fix": "^1.1.2",

@@ -68,7 +69,5 @@ "jest": "^29.6.1",

"jest-runner-prettier": "^1.0.0",
"postcss": "^8.4.12",
"prettier": "^2.8.8",
"ts-node": "^10.9.1",
"tsup": "6.7.0",
"typescript": "^5.0.4",
"tsup": "7.2.0",
"typescript": "^5.1.6",
"version-from-git": "^1.1.1",

@@ -75,0 +74,0 @@ "build-scripts": "0.0.0",

@@ -21,33 +21,42 @@ [![npm][npm-image]][npm-url]

### `Base58EncodedAddress`
### `Ed25519Signature`
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.
This type represents a 64-byte Ed25519 signature of some data with a private key.
Whenever you need to validate an arbitrary string as a base58-encoded address, use the `assertIsBase58EncodedAddress()` function in this package.
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.
## Functions
### `assertIsBase58EncodedAddress()`
### `generateKeyPair()`
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.
Generates an Ed25519 public/private key pair for use with other methods in this package that accept `CryptoKey` objects.
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.
```ts
import { generateKeyPair } from '@solana/keys';
const { privateKey, publicKey } = await generateKeyPair();
```
### `signBytes()`
Given a private `CryptoKey` and a `Uint8Array` of bytes, this method will return the 64-byte Ed25519 signature of that data as a `Uint8Array`.
```ts
import { assertIsBase58EncodedAddress } from '@solana/web3.js`;
import { signBytes } from '@solana/keys';
// Imagine a function that fetches an account's balance when a user submits a form.
function handleSubmit() {
// We know only that what the user typed conforms to the `string` type.
const address: string = accountAddressInput.value;
try {
// If this type assertion function doesn't throw, then
// Typescript will upcast `address` to `Base58EncodedAddress`.
assertIsBase58EncodedAddress(address);
// At this point, `address` is a `Base58EncodedAddress` that can be used with the RPC.
const balanceInLamports = await rpc.getBalance(address).send();
} catch (e) {
// `address` turned out not to be a base58-encoded address
}
const data = new Uint8Array([1, 2, 3]);
const signature = await signBytes(privateKey, data);
```
### `verifySignature()`
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.
```ts
import { verifySignature } from '@solana/keys';
const data = new Uint8Array([1, 2, 3]);
if (!(await verifySignature(publicKey, signature, data))) {
throw new Error('The data were *not* signed by the private key associated with `publicKey`');
}
```

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc