@solana/addresses 2.0.0-experimental.f4281a5 → 2.0.0-experimental.f57da91

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.
@@ -3,7 +3,22 @@ import { assertKeyExporterIsAvailable, assertDigestCapabilityIsAvailable } from
3
3
 
4
4
  // ../build-scripts/env-shim.ts
5
5
  var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
6
- function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
6
+ function isAddress(putativeBase58EncodedAddress) {
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
+ return false;
13
+ }
14
+ const bytes = base58.serialize(putativeBase58EncodedAddress);
15
+ const numBytes = bytes.byteLength;
16
+ if (numBytes !== 32) {
17
+ return false;
18
+ }
19
+ return true;
20
+ }
21
+ function assertIsAddress(putativeBase58EncodedAddress) {
7
22
  try {
8
23
  if (
9
24
  // Lowest address (32 bytes of zeroes)
@@ -23,14 +38,18 @@ function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
23
38
  });
24
39
  }
25
40
  }
26
- function getBase58EncodedAddressCodec(config) {
41
+ function address(putativeBase58EncodedAddress) {
42
+ assertIsAddress(putativeBase58EncodedAddress);
43
+ return putativeBase58EncodedAddress;
44
+ }
45
+ function getAddressCodec(config) {
27
46
  return string({
28
47
  description: config?.description ?? (__DEV__ ? "A 32-byte account address" : ""),
29
48
  encoding: base58,
30
49
  size: 32
31
50
  });
32
51
  }
33
- function getBase58EncodedAddressComparator() {
52
+ function getAddressComparator() {
34
53
  return new Intl.Collator("en", {
35
54
  caseFirst: "lower",
36
55
  ignorePunctuation: false,
@@ -132,6 +151,21 @@ async function compressedPointBytesAreOnCurve(bytes) {
132
151
  }
133
152
 
134
153
  // src/program-derived-address.ts
154
+ function isProgramDerivedAddress(value) {
155
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number" && value[1] >= 0 && value[1] <= 255 && isAddress(value[0]);
156
+ }
157
+ function assertIsProgramDerivedAddress(value) {
158
+ const validFormat = Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number";
159
+ if (!validFormat) {
160
+ throw new Error(
161
+ `Expected given program derived address to have the following format: [Base58EncodedAddress, ProgramDerivedAddressBump].`
162
+ );
163
+ }
164
+ if (value[1] < 0 || value[1] > 255) {
165
+ throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);
166
+ }
167
+ assertIsAddress(value[0]);
168
+ }
135
169
  var MAX_SEED_LENGTH = 32;
136
170
  var MAX_SEEDS = 16;
137
171
  var PDA_MARKER_BYTES = [
@@ -160,7 +194,10 @@ var PDA_MARKER_BYTES = [
160
194
  ];
161
195
  var PointOnCurveError = class extends Error {
162
196
  };
163
- async function createProgramDerivedAddress({ programAddress, seeds }) {
197
+ async function createProgramDerivedAddress({
198
+ programAddress,
199
+ seeds
200
+ }) {
164
201
  await assertDigestCapabilityIsAvailable();
165
202
  if (seeds.length > MAX_SEEDS) {
166
203
  throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);
@@ -174,7 +211,7 @@ async function createProgramDerivedAddress({ programAddress, seeds }) {
174
211
  acc.push(...bytes);
175
212
  return acc;
176
213
  }, []);
177
- const base58EncodedAddressCodec = getBase58EncodedAddressCodec();
214
+ const base58EncodedAddressCodec = getAddressCodec();
178
215
  const programAddressBytes = base58EncodedAddressCodec.serialize(programAddress);
179
216
  const addressBytesBuffer = await crypto.subtle.digest(
180
217
  "SHA-256",
@@ -186,17 +223,18 @@ async function createProgramDerivedAddress({ programAddress, seeds }) {
186
223
  }
187
224
  return base58EncodedAddressCodec.deserialize(addressBytes)[0];
188
225
  }
189
- async function getProgramDerivedAddress({ programAddress, seeds }) {
226
+ async function getProgramDerivedAddress({
227
+ programAddress,
228
+ seeds
229
+ }) {
190
230
  let bumpSeed = 255;
191
231
  while (bumpSeed > 0) {
192
232
  try {
193
- return {
194
- bumpSeed,
195
- pda: await createProgramDerivedAddress({
196
- programAddress,
197
- seeds: [...seeds, new Uint8Array([bumpSeed])]
198
- })
199
- };
233
+ const address2 = await createProgramDerivedAddress({
234
+ programAddress,
235
+ seeds: [...seeds, new Uint8Array([bumpSeed])]
236
+ });
237
+ return [address2, bumpSeed];
200
238
  } catch (e) {
201
239
  if (e instanceof PointOnCurveError) {
202
240
  bumpSeed--;
@@ -207,16 +245,37 @@ async function getProgramDerivedAddress({ programAddress, seeds }) {
207
245
  }
208
246
  throw new Error("Unable to find a viable program address bump seed");
209
247
  }
248
+ async function createAddressWithSeed({
249
+ baseAddress,
250
+ programAddress,
251
+ seed
252
+ }) {
253
+ const { serialize, deserialize } = getAddressCodec();
254
+ const seedBytes = typeof seed === "string" ? new TextEncoder().encode(seed) : seed;
255
+ if (seedBytes.byteLength > MAX_SEED_LENGTH) {
256
+ throw new Error(`The seed exceeds the maximum length of 32 bytes`);
257
+ }
258
+ const programAddressBytes = serialize(programAddress);
259
+ if (programAddressBytes.length >= PDA_MARKER_BYTES.length && programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])) {
260
+ throw new Error(`programAddress cannot end with the PDA marker`);
261
+ }
262
+ const addressBytesBuffer = await crypto.subtle.digest(
263
+ "SHA-256",
264
+ new Uint8Array([...serialize(baseAddress), ...seedBytes, ...programAddressBytes])
265
+ );
266
+ const addressBytes = new Uint8Array(addressBytesBuffer);
267
+ return deserialize(addressBytes)[0];
268
+ }
210
269
  async function getAddressFromPublicKey(publicKey) {
211
270
  await assertKeyExporterIsAvailable();
212
271
  if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") {
213
272
  throw new Error("The `CryptoKey` must be an `Ed25519` public key");
214
273
  }
215
274
  const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
216
- const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));
275
+ const [base58EncodedAddress] = getAddressCodec().deserialize(new Uint8Array(publicKeyBytes));
217
276
  return base58EncodedAddress;
218
277
  }
219
278
 
220
- export { assertIsBase58EncodedAddress, getAddressFromPublicKey, getBase58EncodedAddressCodec, getBase58EncodedAddressComparator, getProgramDerivedAddress };
279
+ export { address, assertIsAddress, assertIsProgramDerivedAddress, createAddressWithSeed, getAddressCodec, getAddressComparator, getAddressFromPublicKey, getProgramDerivedAddress, isAddress, isProgramDerivedAddress };
221
280
  //# sourceMappingURL=out.js.map
222
281
  //# sourceMappingURL=index.node.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../build-scripts/env-shim.ts","../src/base58.ts","../src/program-derived-address.ts","../src/vendor/noble/ed25519.ts","../src/curve.ts","../src/public-key.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,QAAQ,EAAE;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAG;AACR,UAAM,IAAI,MAAM,KAAK,4BAA4B,uCAAuC;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;A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kBAAkB,sDAAsD;AAAA,EACtF;AACA,SAAO,0BAA0B,YAAY,YAAY,EAAE,CAAC;AAChE;AAEA,eAAsB,yBAAyB,EAAE,gBAAgB,MAAM,GAKrE;AACE,MAAI,WAAW;AACf,SAAO,WAAW,GAAG;AACjB,QAAI;AACA,aAAO;AAAA,QACH;AAAA,QACA,KAAK,MAAM,4BAA4B;AAAA,UACnC;AAAA,UACA,OAAO,CAAC,GAAG,OAAO,IAAI,WAAW,CAAC,QAAQ,CAAC,CAAC;AAAA,QAChD,CAAC;AAAA,MACL;AAAA,IACJ,SAAS,GAAG;AACR,UAAI,aAAa,mBAAmB;AAChC;AAAA,MACJ,OAAO;AACH,cAAM;AAAA,MACV;AAAA,IACJ;AAAA,EACJ;AAEA,QAAM,IAAI,MAAM,mDAAmD;AACvE;;;AG7EA,SAAS,oCAAoC;AAI7C,eAAsB,wBAAwB,WAAqD;AAC/F,QAAM,6BAA6B;AACnC,MAAI,UAAU,SAAS,YAAY,UAAU,UAAU,SAAS,WAAW;AAEvE,UAAM,IAAI,MAAM,iDAAiD;AAAA,EACrE;AACA,QAAM,iBAAiB,MAAM,OAAO,OAAO,UAAU,OAAO,SAAS;AACrE,QAAM,CAAC,oBAAoB,IAAI,6BAA6B,EAAE,YAAY,IAAI,WAAW,cAAc,CAAC;AACxG,SAAO;AACX","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","import { assertDigestCapabilityIsAvailable } from '@solana/assertions';\n\nimport { Base58EncodedAddress, getBase58EncodedAddressCodec } from './base58';\nimport { compressedPointBytesAreOnCurve } from './curve';\n\ntype PDAInput = Readonly<{\n programAddress: Base58EncodedAddress;\n seeds: Seed[];\n}>;\ntype Seed = string | Uint8Array;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\n// TODO: Coded error.\nclass PointOnCurveError extends Error {}\n\nasync function createProgramDerivedAddress({ programAddress, seeds }: PDAInput): Promise<Base58EncodedAddress> {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n // TODO: Coded error.\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getBase58EncodedAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.serialize(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (await compressedPointBytesAreOnCurve(addressBytes)) {\n // TODO: Coded error.\n throw new PointOnCurveError('Invalid seeds; point must fall off the Ed25519 curve');\n }\n return base58EncodedAddressCodec.deserialize(addressBytes)[0];\n}\n\nexport async function getProgramDerivedAddress({ programAddress, seeds }: PDAInput): Promise<\n Readonly<{\n bumpSeed: number;\n pda: Base58EncodedAddress;\n }>\n> {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n return {\n bumpSeed,\n pda: await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])],\n }),\n };\n } catch (e) {\n if (e instanceof PointOnCurveError) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n // TODO: Coded error.\n throw new Error('Unable to find a viable program address bump seed');\n}\n","/**!\n * noble-ed25519\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Paul Miller (https://paulmillr.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the “Software”), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nconst D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nconst P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; // 2n ** 255n - 19n; ed25519 is twisted edwards curve\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1\n\n// mod division\nfunction mod(a: bigint): bigint {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x: bigint, power: bigint): bigint {\n // pow2(x, 4) == x^(2^4)\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x: bigint): bigint {\n // x^(2^252-3) unrolled util for square root\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return pow_p_5_8;\n}\nfunction uvRatio(u: bigint, v: bigint): bigint | null {\n // for sqrt comp\n const v3 = mod(v * v * v); // v³\n const v7 = mod(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7); // (uv⁷)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n) x = mod(-x); // edIsNegative\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\n// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.3\nexport function pointIsOnCurve(y: bigint, lastByte: number): boolean {\n const y2 = mod(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n","import { pointIsOnCurve } from './vendor/noble/ed25519';\n\nfunction byteToHex(byte: number): string {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\n\nfunction decompressPointBytes(bytes: Uint8Array): bigint {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~0x80 : byte)}${acc}`, '');\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\n\nexport async function compressedPointBytesAreOnCurve(bytes: Uint8Array): Promise<boolean> {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\n\nimport { Base58EncodedAddress, getBase58EncodedAddressCodec } from './base58';\n\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Base58EncodedAddress> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n // TODO: Coded error.\n throw new Error('The `CryptoKey` must be an `Ed25519` public key');\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n"]}
1
+ {"version":3,"sources":["../../build-scripts/env-shim.ts","../src/address.ts","../src/program-derived-address.ts","../src/vendor/noble/ed25519.ts","../src/curve.ts","../src/public-key.ts"],"names":["address"],"mappings":";AACO,IAAM,UAA2B,uBAAO,QAAgB,KAAU,EAAE,aAAa,eAAe;;;ACDvG,SAAS,QAAoB,cAAc;AAMpC,SAAS,UACZ,8BACyF;AAEzF;AAAA;AAAA,IAEI,6BAA6B,SAAS;AAAA,IAEtC,6BAA6B,SAAS;AAAA,IACxC;AACE,WAAO;AAAA,EACX;AAEA,QAAM,QAAQ,OAAO,UAAU,4BAA4B;AAC3D,QAAM,WAAW,MAAM;AACvB,MAAI,aAAa,IAAI;AACjB,WAAO;AAAA,EACX;AACA,SAAO;AACX;AAEO,SAAS,gBACZ,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,OA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AAM,IAAI,MAAM,iDAAiD;AAAA,EACrE;AACA,QAAM,iBAAiB,MAAM,OAAO,OAAO,UAAU,OAAO,SAAS;AACrE,QAAM,CAAC,oBAAoB,IAAI,gBAAgB,EAAE,YAAY,IAAI,WAAW,cAAc,CAAC;AAC3F,SAAO;AACX","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 __brand: unique symbol;\n};\n\nexport function isAddress(\n putativeBase58EncodedAddress: string\n): putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\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 return false;\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 return false;\n }\n return true;\n}\n\nexport function assertIsAddress(\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 address<TAddress extends string = string>(\n putativeBase58EncodedAddress: TAddress\n): Base58EncodedAddress<TAddress> {\n assertIsAddress(putativeBase58EncodedAddress);\n return putativeBase58EncodedAddress as Base58EncodedAddress<TAddress>;\n}\n\nexport function getAddressCodec(\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 getAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","import { assertDigestCapabilityIsAvailable } from '@solana/assertions';\n\nimport { assertIsAddress, Base58EncodedAddress, getAddressCodec, isAddress } from './address';\nimport { compressedPointBytesAreOnCurve } from './curve';\n\n/**\n * An address derived from a program address and a set of seeds.\n * It includes the bump seed used to derive the address and\n * ensure the address is not on the Ed25519 curve.\n */\nexport type ProgramDerivedAddress<TAddress extends string = string> = Readonly<\n [Base58EncodedAddress<TAddress>, ProgramDerivedAddressBump]\n>;\n\n/**\n * A number between 0 and 255, inclusive.\n */\nexport type ProgramDerivedAddressBump = number & {\n readonly __brand: unique symbol;\n};\n\n/**\n * Returns true if the input value is a program derived address.\n */\nexport function isProgramDerivedAddress<TAddress extends string = string>(\n value: unknown\n): value is ProgramDerivedAddress<TAddress> {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'string' &&\n typeof value[1] === 'number' &&\n value[1] >= 0 &&\n value[1] <= 255 &&\n isAddress(value[0])\n );\n}\n\n/**\n * Fails if the input value is not a program derived address.\n */\nexport function assertIsProgramDerivedAddress<TAddress extends string = string>(\n value: unknown\n): asserts value is ProgramDerivedAddress<TAddress> {\n const validFormat =\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number';\n if (!validFormat) {\n // TODO: Coded error.\n throw new Error(\n `Expected given program derived address to have the following format: [Base58EncodedAddress, ProgramDerivedAddressBump].`\n );\n }\n if (value[1] < 0 || value[1] > 255) {\n // TODO: Coded error.\n throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${value[1]}.`);\n }\n assertIsAddress(value[0]);\n}\n\ntype ProgramDerivedAddressInput = Readonly<{\n programAddress: Base58EncodedAddress;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Base58EncodedAddress;\n programAddress: Base58EncodedAddress;\n seed: Seed;\n}>;\n\ntype Seed = string | Uint8Array;\n\nconst MAX_SEED_LENGTH = 32;\nconst MAX_SEEDS = 16;\nconst PDA_MARKER_BYTES = [\n // The string 'ProgramDerivedAddress'\n 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,\n] as const;\n\n// TODO: Coded error.\nclass PointOnCurveError extends Error {}\n\nasync function createProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise<Base58EncodedAddress> {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n // TODO: Coded error.\n throw new Error(`A maximum of ${MAX_SEEDS} seeds may be supplied when creating an address`);\n }\n let textEncoder: TextEncoder;\n const seedBytes = seeds.reduce((acc, seed, ii) => {\n const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;\n if (bytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed at index ${ii} exceeds the maximum length of 32 bytes`);\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.serialize(programAddress);\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n if (await compressedPointBytesAreOnCurve(addressBytes)) {\n // TODO: Coded error.\n throw new PointOnCurveError('Invalid seeds; point must fall off the Ed25519 curve');\n }\n return base58EncodedAddressCodec.deserialize(addressBytes)[0];\n}\n\nexport async function getProgramDerivedAddress({\n programAddress,\n seeds,\n}: ProgramDerivedAddressInput): Promise<ProgramDerivedAddress> {\n let bumpSeed = 255;\n while (bumpSeed > 0) {\n try {\n const address = await createProgramDerivedAddress({\n programAddress,\n seeds: [...seeds, new Uint8Array([bumpSeed])],\n });\n return [address, bumpSeed as ProgramDerivedAddressBump];\n } catch (e) {\n if (e instanceof PointOnCurveError) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n // TODO: Coded error.\n throw new Error('Unable to find a viable program address bump seed');\n}\n\nexport async function createAddressWithSeed({\n baseAddress,\n programAddress,\n seed,\n}: SeedInput): Promise<Base58EncodedAddress> {\n const { serialize, deserialize } = getAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n // TODO: Coded error.\n throw new Error(`The seed exceeds the maximum length of 32 bytes`);\n }\n\n const programAddressBytes = serialize(programAddress);\n if (\n programAddressBytes.length >= PDA_MARKER_BYTES.length &&\n programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])\n ) {\n // TODO: Coded error.\n throw new Error(`programAddress cannot end with the PDA marker`);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...serialize(baseAddress), ...seedBytes, ...programAddressBytes])\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return deserialize(addressBytes)[0];\n}\n","/**!\n * noble-ed25519\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Paul Miller (https://paulmillr.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the “Software”), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nconst D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;\nconst P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; // 2n ** 255n - 19n; ed25519 is twisted edwards curve\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1\n\n// mod division\nfunction mod(a: bigint): bigint {\n const r = a % P;\n return r >= 0n ? r : P + r;\n}\nfunction pow2(x: bigint, power: bigint): bigint {\n // pow2(x, 4) == x^(2^4)\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n}\nfunction pow_2_252_3(x: bigint): bigint {\n // x^(2^252-3) unrolled util for square root\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return pow_p_5_8;\n}\nfunction uvRatio(u: bigint, v: bigint): bigint | null {\n // for sqrt comp\n const v3 = mod(v * v * v); // v³\n const v7 = mod(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7); // (uv⁷)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n) x = mod(-x); // edIsNegative\n if (!useRoot1 && !useRoot2) {\n return null;\n }\n return x;\n}\n// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.3\nexport function pointIsOnCurve(y: bigint, lastByte: number): boolean {\n const y2 = mod(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = mod(D * y2 + 1n);\n const x = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (x === null) {\n return false;\n }\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (x === 0n && isLastByteOdd) {\n return false;\n }\n return true;\n}\n","import { pointIsOnCurve } from './vendor/noble/ed25519';\n\nfunction byteToHex(byte: number): string {\n const hexString = byte.toString(16);\n if (hexString.length === 1) {\n return `0${hexString}`;\n } else {\n return hexString;\n }\n}\n\nfunction decompressPointBytes(bytes: Uint8Array): bigint {\n const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~0x80 : byte)}${acc}`, '');\n const integerLiteralString = `0x${hexString}`;\n return BigInt(integerLiteralString);\n}\n\nexport async function compressedPointBytesAreOnCurve(bytes: Uint8Array): Promise<boolean> {\n if (bytes.byteLength !== 32) {\n return false;\n }\n const y = decompressPointBytes(bytes);\n return pointIsOnCurve(y, bytes[31]);\n}\n","import { assertKeyExporterIsAvailable } from '@solana/assertions';\n\nimport { Base58EncodedAddress, getAddressCodec } from './address';\n\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Base58EncodedAddress> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n // TODO: Coded error.\n throw new Error('The `CryptoKey` must be an `Ed25519` public key');\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n const [base58EncodedAddress] = getAddressCodec().deserialize(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n"]}
@@ -2,13 +2,18 @@ this.globalThis = this.globalThis || {};
2
2
  this.globalThis.solanaWeb3 = (function (exports) {
3
3
  'use strict';
4
4
 
5
- var X=Object.defineProperty;var M=(e,r,t)=>r in e?X(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var x=(e,r,t)=>(M(e,typeof r!="symbol"?r+"":r,t),t);var v=e=>{let r=e.reduce((i,o)=>i+o.length,0),t=new Uint8Array(r),n=0;return e.forEach(i=>{t.set(i,n),n+=i.length;}),t},_=(e,r)=>{if(e.length>=r)return e;let t=new Uint8Array(r).fill(0);return t.set(e),t},h=(e,r)=>_(e.slice(0,r),r);var b=class extends Error{constructor(t){super(`Serializer [${t}] cannot deserialize empty buffers.`);x(this,"name","DeserializingEmptyBufferError");}},y=class extends Error{constructor(t,n,i){super(`Serializer [${t}] expected ${n} bytes, got ${i}.`);x(this,"name","NotEnoughBytesError");}};function I(e,r,t){return {description:t??`fixed(${r}, ${e.description})`,fixedSize:r,maxSize:r,serialize:n=>h(e.serialize(n),r),deserialize:(n,i=0)=>{if(n=n.slice(i,i+r),n.length<r)throw new y("fixSerializer",r,n.length);e.fixedSize!==null&&(n=h(n,e.fixedSize));let[o]=e.deserialize(n,0);return [o,i+r]}}}var E=class extends Error{constructor(t,n,i){let o=`Expected a string of base ${n}, got [${t}].`;super(o);x(this,"name","InvalidBaseStringError");this.cause=i;}};var $=e=>{let r=e.length,t=BigInt(r);return {description:`base${r}`,fixedSize:null,maxSize:null,serialize(n){if(!n.match(new RegExp(`^[${e}]*$`)))throw new E(n,r);if(n==="")return new Uint8Array;let i=[...n],o=i.findIndex(d=>d!==e[0]);o=o===-1?i.length:o;let s=Array(o).fill(0);if(o===i.length)return Uint8Array.from(s);let f=i.slice(o),c=0n,l=1n;for(let d=f.length-1;d>=0;d-=1)c+=l*BigInt(e.indexOf(f[d])),l*=t;let u=[];for(;c>0n;)u.unshift(Number(c%256n)),c/=256n;return Uint8Array.from(s.concat(u))},deserialize(n,i=0){if(n.length===0)return ["",0];let o=n.slice(i),s=o.findIndex(u=>u!==0);s=s===-1?o.length:s;let f=e[0].repeat(s);if(s===o.length)return [f,n.length];let c=o.slice(s).reduce((u,d)=>u*256n+BigInt(d),0n),l=[];for(;c>0n;)l.unshift(e[Number(c%t)]),c/=t;return [f+l.join(""),n.length]}}};var w=$("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var T=e=>e.replace(/\u0000/g,"");var C={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 [T(t),e.length]}};var z;(function(e){e.Little="le",e.Big="be";})(z||(z={}));var S=class extends RangeError{constructor(t,n,i,o){super(`Serializer [${t}] expected number to be between ${n} and ${i}, got ${o}.`);x(this,"name","NumberOutOfRangeError");}};function U(e){let r,t=e.name;return e.size>1&&(r=!("endian"in e.options)||e.options.endian===z.Little,t+=r?"(le)":"(be)"),{description:e.options.description??t,fixedSize:e.size,maxSize:e.size,serialize(n){e.range&&H(e.name,e.range[0],e.range[1],n);let i=new ArrayBuffer(e.size);return e.set(new DataView(i),n,r),new Uint8Array(i)},deserialize(n,i=0){let o=n.slice(i,i+e.size);W("i8",o,e.size);let s=G(o);return [e.get(s,r),i+e.size]}}}var j=e=>e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset),G=e=>new DataView(j(e)),H=(e,r,t,n)=>{if(n<r||n>t)throw new S(e,r,t,n)},W=(e,r,t)=>{if(r.length===0)throw new b(e);if(r.length<t)throw new y(e,t,r.length)};var D=(e={})=>U({name:"u32",size:4,range:[0,+"0xffffffff"],set:(r,t,n)=>r.setUint32(0,Number(t),n),get:(r,t)=>r.getUint32(0,t),options:e});function R(e){return typeof e=="object"?e.description:`${e}`}function N(e={}){let r=e.size??D(),t=e.encoding??C,n=e.description??`string(${t.description}; ${R(r)})`;return r==="variable"?{...t,description:n}:typeof r=="number"?I(t,r,n):{description:n,fixedSize:null,maxSize:null,serialize:i=>{let o=t.serialize(i),s=r.serialize(o.length);return v([s,o])},deserialize:(i,o=0)=>{if(i.slice(o).length===0)throw new b("string");let[s,f]=r.deserialize(i,o),c=Number(s);o=f;let l=i.slice(o,o+c);if(l.length<c)throw new y("string",c,l.length);let[u,d]=t.deserialize(l);return o+=d,[u,o]}}}function xr(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=w.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 A(e){return N({description:e?.description??"",encoding:w,size:32})}function br(){return new Intl.Collator("en",{caseFirst:"lower",ignorePunctuation:!1,localeMatcher:"best fit",numeric:!1,sensitivity:"variant",usage:"sort"}).compare}function P(){if(!globalThis.isSecureContext)throw new Error("Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts")}async function O(){if(P(),typeof globalThis.crypto>"u"||typeof globalThis.crypto.subtle?.digest!="function")throw new Error("No digest implementation could be found")}async function L(){if(P(),typeof globalThis.crypto>"u"||typeof globalThis.crypto.subtle?.exportKey!="function")throw new Error("No key export implementation could be found")}var Z=37095705934669439343138083508754565189542113879843219016388785533085940283555n,p=57896044618658097711785492504343953926634992332820282019728792003956564819949n,K=19681161376707505956807079304988542015446066515923890162744021073123829784752n;function m(e){let r=e%p;return r>=0n?r:p+r}function g(e,r){let t=e;for(;r-- >0n;)t*=t,t%=p;return t}function q(e){let t=e*e%p*e%p,n=g(t,2n)*t%p,i=g(n,1n)*e%p,o=g(i,5n)*i%p,s=g(o,10n)*o%p,f=g(s,20n)*s%p,c=g(f,40n)*f%p,l=g(c,80n)*c%p,u=g(l,80n)*c%p,d=g(u,10n)*o%p;return g(d,2n)*e%p}function Y(e,r){let t=m(r*r*r),n=m(t*t*r),i=q(e*n),o=m(e*t*i),s=m(r*o*o),f=o,c=m(o*K),l=s===e,u=s===m(-e),d=s===m(-e*K);return l&&(o=f),(u||d)&&(o=c),(m(o)&1n)===1n&&(o=m(-o)),!l&&!u?null:o}function k(e,r){let t=m(e*e),n=m(t-1n),i=m(Z*t+1n),o=Y(n,i);if(o===null)return !1;let s=(r&128)!==0;return !(o===0n&&s)}function J(e){let r=e.toString(16);return r.length===1?`0${r}`:r}function Q(e){let t=`0x${e.reduce((n,i,o)=>`${J(o===31?i&-129:i)}${n}`,"")}`;return BigInt(t)}async function V(e){if(e.byteLength!==32)return !1;let r=Q(e);return k(r,e[31])}var ee=32,F=16,re=[80,114,111,103,114,97,109,68,101,114,105,118,101,100,65,100,100,114,101,115,115],B=class extends Error{};async function te({programAddress:e,seeds:r}){if(await O(),r.length>F)throw new Error(`A maximum of ${F} seeds may be supplied when creating an address`);let t,n=r.reduce((c,l,u)=>{let d=typeof l=="string"?(t||(t=new TextEncoder)).encode(l):l;if(d.byteLength>ee)throw new Error(`The seed at index ${u} exceeds the maximum length of 32 bytes`);return c.push(...d),c},[]),i=A(),o=i.serialize(e),s=await crypto.subtle.digest("SHA-256",new Uint8Array([...n,...o,...re])),f=new Uint8Array(s);if(await V(f))throw new B("Invalid seeds; point must fall off the Ed25519 curve");return i.deserialize(f)[0]}async function $r({programAddress:e,seeds:r}){let t=255;for(;t>0;)try{return {bumpSeed:t,pda:await te({programAddress:e,seeds:[...r,new Uint8Array([t])]})}}catch(n){if(n instanceof B)t--;else throw n}throw new Error("Unable to find a viable program address bump seed")}async function Lr(e){if(await L(),e.type!=="public"||e.algorithm.name!=="Ed25519")throw new Error("The `CryptoKey` must be an `Ed25519` public key");let r=await crypto.subtle.exportKey("raw",e),[t]=A().deserialize(new Uint8Array(r));return t}
5
+ var G=Object.defineProperty;var W=(e,r,t)=>r in e?G(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var x=(e,r,t)=>(W(e,typeof r!="symbol"?r+"":r,t),t);var I=e=>{let r=e.reduce((s,o)=>s+o.length,0),t=new Uint8Array(r),n=0;return e.forEach(s=>{t.set(s,n),n+=s.length;}),t},_=(e,r)=>{if(e.length>=r)return e;let t=new Uint8Array(r).fill(0);return t.set(e),t},E=(e,r)=>_(e.slice(0,r),r);var h=class extends Error{constructor(t){super(`Serializer [${t}] cannot deserialize empty buffers.`);x(this,"name","DeserializingEmptyBufferError");}},y=class extends Error{constructor(t,n,s){super(`Serializer [${t}] expected ${n} bytes, got ${s}.`);x(this,"name","NotEnoughBytesError");}};function D(e,r,t){return {description:t??`fixed(${r}, ${e.description})`,fixedSize:r,maxSize:r,serialize:n=>E(e.serialize(n),r),deserialize:(n,s=0)=>{if(n=n.slice(s,s+r),n.length<r)throw new y("fixSerializer",r,n.length);e.fixedSize!==null&&(n=E(n,e.fixedSize));let[o]=e.deserialize(n,0);return [o,s+r]}}}var A=class extends Error{constructor(t,n,s){let o=`Expected a string of base ${n}, got [${t}].`;super(o);x(this,"name","InvalidBaseStringError");this.cause=s;}};var $=e=>{let r=e.length,t=BigInt(r);return {description:`base${r}`,fixedSize:null,maxSize:null,serialize(n){if(!n.match(new RegExp(`^[${e}]*$`)))throw new A(n,r);if(n==="")return new Uint8Array;let s=[...n],o=s.findIndex(p=>p!==e[0]);o=o===-1?s.length:o;let i=Array(o).fill(0);if(o===s.length)return Uint8Array.from(i);let l=s.slice(o),d=0n,c=1n;for(let p=l.length-1;p>=0;p-=1)d+=c*BigInt(e.indexOf(l[p])),c*=t;let f=[];for(;d>0n;)f.unshift(Number(d%256n)),d/=256n;return Uint8Array.from(i.concat(f))},deserialize(n,s=0){if(n.length===0)return ["",0];let o=n.slice(s),i=o.findIndex(f=>f!==0);i=i===-1?o.length:i;let l=e[0].repeat(i);if(i===o.length)return [l,n.length];let d=o.slice(i).reduce((f,p)=>f*256n+BigInt(p),0n),c=[];for(;d>0n;)c.unshift(e[Number(d%t)]),d/=t;return [l+c.join(""),n.length]}}};var b=$("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var U=e=>e.replace(/\u0000/g,"");var T={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 [U(t),e.length]}};var z;(function(e){e.Little="le",e.Big="be";})(z||(z={}));var S=class extends RangeError{constructor(t,n,s,o){super(`Serializer [${t}] expected number to be between ${n} and ${s}, got ${o}.`);x(this,"name","NumberOutOfRangeError");}};function R(e){let r,t=e.name;return e.size>1&&(r=!("endian"in e.options)||e.options.endian===z.Little,t+=r?"(le)":"(be)"),{description:e.options.description??t,fixedSize:e.size,maxSize:e.size,serialize(n){e.range&&Y(e.name,e.range[0],e.range[1],n);let s=new ArrayBuffer(e.size);return e.set(new DataView(s),n,r),new Uint8Array(s)},deserialize(n,s=0){let o=n.slice(s,s+e.size);J("i8",o,e.size);let i=Z(o);return [e.get(i,r),s+e.size]}}}var q=e=>e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset),Z=e=>new DataView(q(e)),Y=(e,r,t,n)=>{if(n<r||n>t)throw new S(e,r,t,n)},J=(e,r,t)=>{if(r.length===0)throw new h(e);if(r.length<t)throw new y(e,t,r.length)};var P=(e={})=>R({name:"u32",size:4,range:[0,+"0xffffffff"],set:(r,t,n)=>r.setUint32(0,Number(t),n),get:(r,t)=>r.getUint32(0,t),options:e});function L(e){return typeof e=="object"?e.description:`${e}`}function C(e={}){let r=e.size??P(),t=e.encoding??T,n=e.description??`string(${t.description}; ${L(r)})`;return r==="variable"?{...t,description:n}:typeof r=="number"?D(t,r,n):{description:n,fixedSize:null,maxSize:null,serialize:s=>{let o=t.serialize(s),i=r.serialize(o.length);return I([i,o])},deserialize:(s,o=0)=>{if(s.slice(o).length===0)throw new h("string");let[i,l]=r.deserialize(s,o),d=Number(i);o=l;let c=s.slice(o,o+d);if(c.length<d)throw new y("string",d,c.length);let[f,p]=t.deserialize(c);return o+=p,[f,o]}}}function O(e){return !(e.length<32||e.length>44||b.serialize(e).byteLength!==32)}function N(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=b.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 br(e){return N(e),e}function w(e){return C({description:e?.description??"",encoding:b,size:32})}function wr(){return new Intl.Collator("en",{caseFirst:"lower",ignorePunctuation:!1,localeMatcher:"best fit",numeric:!1,sensitivity:"variant",usage:"sort"}).compare}function k(){if(!globalThis.isSecureContext)throw new Error("Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts")}async function K(){if(k(),typeof globalThis.crypto>"u"||typeof globalThis.crypto.subtle?.digest!="function")throw new Error("No digest implementation could be found")}async function F(){if(k(),typeof globalThis.crypto>"u"||typeof globalThis.crypto.subtle?.exportKey!="function")throw new Error("No key export implementation could be found")}var Q=37095705934669439343138083508754565189542113879843219016388785533085940283555n,m=57896044618658097711785492504343953926634992332820282019728792003956564819949n,V=19681161376707505956807079304988542015446066515923890162744021073123829784752n;function u(e){let r=e%m;return r>=0n?r:m+r}function g(e,r){let t=e;for(;r-- >0n;)t*=t,t%=m;return t}function ee(e){let t=e*e%m*e%m,n=g(t,2n)*t%m,s=g(n,1n)*e%m,o=g(s,5n)*s%m,i=g(o,10n)*o%m,l=g(i,20n)*i%m,d=g(l,40n)*l%m,c=g(d,80n)*d%m,f=g(c,80n)*d%m,p=g(f,10n)*o%m;return g(p,2n)*e%m}function re(e,r){let t=u(r*r*r),n=u(t*t*r),s=ee(e*n),o=u(e*t*s),i=u(r*o*o),l=o,d=u(o*V),c=i===e,f=i===u(-e),p=i===u(-e*V);return c&&(o=l),(f||p)&&(o=d),(u(o)&1n)===1n&&(o=u(-o)),!c&&!f?null:o}function X(e,r){let t=u(e*e),n=u(t-1n),s=u(Q*t+1n),o=re(n,s);if(o===null)return !1;let i=(r&128)!==0;return !(o===0n&&i)}function te(e){let r=e.toString(16);return r.length===1?`0${r}`:r}function ne(e){let t=`0x${e.reduce((n,s,o)=>`${te(o===31?s&-129:s)}${n}`,"")}`;return BigInt(t)}async function M(e){if(e.byteLength!==32)return !1;let r=ne(e);return X(r,e[31])}function $r(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&typeof e[1]=="number"&&e[1]>=0&&e[1]<=255&&O(e[0])}function Ur(e){if(!(Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&typeof e[1]=="number"))throw new Error("Expected given program derived address to have the following format: [Base58EncodedAddress, ProgramDerivedAddressBump].");if(e[1]<0||e[1]>255)throw new Error(`Expected program derived address bump to be in the range [0, 255], got: ${e[1]}.`);N(e[0]);}var H=32,j=16,B=[80,114,111,103,114,97,109,68,101,114,105,118,101,100,65,100,100,114,101,115,115],v=class extends Error{};async function oe({programAddress:e,seeds:r}){if(await K(),r.length>j)throw new Error(`A maximum of ${j} seeds may be supplied when creating an address`);let t,n=r.reduce((d,c,f)=>{let p=typeof c=="string"?(t||(t=new TextEncoder)).encode(c):c;if(p.byteLength>H)throw new Error(`The seed at index ${f} exceeds the maximum length of 32 bytes`);return d.push(...p),d},[]),s=w(),o=s.serialize(e),i=await crypto.subtle.digest("SHA-256",new Uint8Array([...n,...o,...B])),l=new Uint8Array(i);if(await M(l))throw new v("Invalid seeds; point must fall off the Ed25519 curve");return s.deserialize(l)[0]}async function Rr({programAddress:e,seeds:r}){let t=255;for(;t>0;)try{return [await oe({programAddress:e,seeds:[...r,new Uint8Array([t])]}),t]}catch(n){if(n instanceof v)t--;else throw n}throw new Error("Unable to find a viable program address bump seed")}async function Lr({baseAddress:e,programAddress:r,seed:t}){let{serialize:n,deserialize:s}=w(),o=typeof t=="string"?new TextEncoder().encode(t):t;if(o.byteLength>H)throw new Error("The seed exceeds the maximum length of 32 bytes");let i=n(r);if(i.length>=B.length&&i.slice(-B.length).every((c,f)=>c===B[f]))throw new Error("programAddress cannot end with the PDA marker");let l=await crypto.subtle.digest("SHA-256",new Uint8Array([...n(e),...o,...i])),d=new Uint8Array(l);return s(d)[0]}async function Xr(e){if(await F(),e.type!=="public"||e.algorithm.name!=="Ed25519")throw new Error("The `CryptoKey` must be an `Ed25519` public key");let r=await crypto.subtle.exportKey("raw",e),[t]=w().deserialize(new Uint8Array(r));return t}
6
6
 
7
- exports.assertIsBase58EncodedAddress = xr;
8
- exports.getAddressFromPublicKey = Lr;
9
- exports.getBase58EncodedAddressCodec = A;
10
- exports.getBase58EncodedAddressComparator = br;
11
- exports.getProgramDerivedAddress = $r;
7
+ exports.address = br;
8
+ exports.assertIsAddress = N;
9
+ exports.assertIsProgramDerivedAddress = Ur;
10
+ exports.createAddressWithSeed = Lr;
11
+ exports.getAddressCodec = w;
12
+ exports.getAddressComparator = wr;
13
+ exports.getAddressFromPublicKey = Xr;
14
+ exports.getProgramDerivedAddress = Rr;
15
+ exports.isAddress = O;
16
+ exports.isProgramDerivedAddress = $r;
12
17
 
13
18
  return exports;
14
19
 
@@ -0,0 +1,12 @@
1
+ import { Serializer } from '@metaplex-foundation/umi-serializers';
2
+ export type Base58EncodedAddress<TAddress extends string = string> = TAddress & {
3
+ readonly __brand: unique symbol;
4
+ };
5
+ export declare function isAddress(putativeBase58EncodedAddress: string): putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress>;
6
+ export declare function assertIsAddress(putativeBase58EncodedAddress: string): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress>;
7
+ export declare function address<TAddress extends string = string>(putativeBase58EncodedAddress: TAddress): Base58EncodedAddress<TAddress>;
8
+ export declare function getAddressCodec(config?: Readonly<{
9
+ description: string;
10
+ }>): Serializer<Base58EncodedAddress>;
11
+ export declare function getAddressComparator(): (x: string, y: string) => number;
12
+ //# sourceMappingURL=address.d.ts.map
@@ -1,4 +1,4 @@
1
- export * from './base58';
1
+ export * from './address';
2
2
  export * from './program-derived-address';
3
3
  export * from './public-key';
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -1,12 +1,38 @@
1
- import { Base58EncodedAddress } from './base58';
2
- type PDAInput = Readonly<{
1
+ import { Base58EncodedAddress } from './address';
2
+ /**
3
+ * An address derived from a program address and a set of seeds.
4
+ * It includes the bump seed used to derive the address and
5
+ * ensure the address is not on the Ed25519 curve.
6
+ */
7
+ export type ProgramDerivedAddress<TAddress extends string = string> = Readonly<[
8
+ Base58EncodedAddress<TAddress>,
9
+ ProgramDerivedAddressBump
10
+ ]>;
11
+ /**
12
+ * A number between 0 and 255, inclusive.
13
+ */
14
+ export type ProgramDerivedAddressBump = number & {
15
+ readonly __brand: unique symbol;
16
+ };
17
+ /**
18
+ * Returns true if the input value is a program derived address.
19
+ */
20
+ export declare function isProgramDerivedAddress<TAddress extends string = string>(value: unknown): value is ProgramDerivedAddress<TAddress>;
21
+ /**
22
+ * Fails if the input value is not a program derived address.
23
+ */
24
+ export declare function assertIsProgramDerivedAddress<TAddress extends string = string>(value: unknown): asserts value is ProgramDerivedAddress<TAddress>;
25
+ type ProgramDerivedAddressInput = Readonly<{
3
26
  programAddress: Base58EncodedAddress;
4
27
  seeds: Seed[];
5
28
  }>;
29
+ type SeedInput = Readonly<{
30
+ baseAddress: Base58EncodedAddress;
31
+ programAddress: Base58EncodedAddress;
32
+ seed: Seed;
33
+ }>;
6
34
  type Seed = string | Uint8Array;
7
- export declare function getProgramDerivedAddress({ programAddress, seeds }: PDAInput): Promise<Readonly<{
8
- bumpSeed: number;
9
- pda: Base58EncodedAddress;
10
- }>>;
35
+ export declare function getProgramDerivedAddress({ programAddress, seeds, }: ProgramDerivedAddressInput): Promise<ProgramDerivedAddress>;
36
+ export declare function createAddressWithSeed({ baseAddress, programAddress, seed, }: SeedInput): Promise<Base58EncodedAddress>;
11
37
  export {};
12
38
  //# sourceMappingURL=program-derived-address.d.ts.map
@@ -1,3 +1,3 @@
1
- import { Base58EncodedAddress } from './base58';
1
+ import { Base58EncodedAddress } from './address';
2
2
  export declare function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Base58EncodedAddress>;
3
3
  //# sourceMappingURL=public-key.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solana/addresses",
3
- "version": "2.0.0-experimental.f4281a5",
3
+ "version": "2.0.0-experimental.f57da91",
4
4
  "description": "Helpers for generating account addresses",
5
5
  "exports": {
6
6
  "browser": {
@@ -49,26 +49,26 @@
49
49
  "node": ">=17.4"
50
50
  },
51
51
  "dependencies": {
52
- "@metaplex-foundation/umi-serializers": "^0.8.5",
53
- "@solana/assertions": "2.0.0-experimental.f4281a5"
52
+ "@metaplex-foundation/umi-serializers": "^0.8.9",
53
+ "@solana/assertions": "2.0.0-experimental.f57da91"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@solana/eslint-config-solana": "^1.0.2",
57
57
  "@swc/jest": "^0.2.28",
58
- "@types/jest": "^29.5.3",
59
- "@typescript-eslint/eslint-plugin": "^6.3.0",
58
+ "@types/jest": "^29.5.5",
59
+ "@typescript-eslint/eslint-plugin": "^6.7.0",
60
60
  "@typescript-eslint/parser": "^6.3.0",
61
61
  "agadoo": "^3.0.0",
62
62
  "eslint": "^8.45.0",
63
63
  "eslint-plugin-jest": "^27.2.3",
64
64
  "eslint-plugin-sort-keys-fix": "^1.1.2",
65
- "jest": "^29.6.1",
65
+ "jest": "^29.7.0",
66
66
  "jest-environment-jsdom": "^29.6.4",
67
67
  "jest-runner-eslint": "^2.1.0",
68
68
  "jest-runner-prettier": "^1.0.0",
69
69
  "prettier": "^2.8",
70
70
  "tsup": "7.2.0",
71
- "typescript": "^5.1.6",
71
+ "typescript": "^5.2.2",
72
72
  "version-from-git": "^1.1.1",
73
73
  "build-scripts": "0.0.0",
74
74
  "test-config": "0.0.0",
@@ -87,11 +87,12 @@
87
87
  "compile:typedefs": "tsc -p ./tsconfig.declarations.json",
88
88
  "dev": "jest -c node_modules/test-config/jest-dev.config.ts --rootDir . --watch",
89
89
  "publish-packages": "pnpm publish --tag experimental --access public --no-git-checks",
90
+ "style:fix": "pnpm eslint --fix src/* && pnpm prettier -w src/*",
90
91
  "test:lint": "jest -c node_modules/test-config/jest-lint.config.ts --rootDir . --silent",
91
92
  "test:prettier": "jest -c node_modules/test-config/jest-prettier.config.ts --rootDir . --silent",
92
93
  "test:treeshakability:browser": "agadoo dist/index.browser.js",
93
- "test:treeshakability:native": "agadoo dist/index.node.js",
94
- "test:treeshakability:node": "agadoo dist/index.native.js",
94
+ "test:treeshakability:native": "agadoo dist/index.native.js",
95
+ "test:treeshakability:node": "agadoo dist/index.node.js",
95
96
  "test:typecheck": "tsc --noEmit",
96
97
  "test:unit:browser": "jest -c node_modules/test-config/jest-unit.config.browser.ts --rootDir . --silent",
97
98
  "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