@solana/addresses 6.3.1 → 6.3.2-canary-20260313112147

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solana/addresses",
3
- "version": "6.3.1",
3
+ "version": "6.3.2-canary-20260313112147",
4
4
  "description": "Helpers for generating account addresses",
5
5
  "homepage": "https://www.solanakit.com/api#solanaaddresses",
6
6
  "exports": {
@@ -33,7 +33,8 @@
33
33
  "types": "./dist/types/index.d.ts",
34
34
  "type": "commonjs",
35
35
  "files": [
36
- "./dist/"
36
+ "./dist/",
37
+ "./src/"
37
38
  ],
38
39
  "sideEffects": false,
39
40
  "keywords": [
@@ -55,11 +56,11 @@
55
56
  "maintained node versions"
56
57
  ],
57
58
  "dependencies": {
58
- "@solana/assertions": "6.3.1",
59
- "@solana/codecs-strings": "6.3.1",
60
- "@solana/nominal-types": "6.3.1",
61
- "@solana/codecs-core": "6.3.1",
62
- "@solana/errors": "6.3.1"
59
+ "@solana/assertions": "6.3.2-canary-20260313112147",
60
+ "@solana/codecs-core": "6.3.2-canary-20260313112147",
61
+ "@solana/codecs-strings": "6.3.2-canary-20260313112147",
62
+ "@solana/errors": "6.3.2-canary-20260313112147",
63
+ "@solana/nominal-types": "6.3.2-canary-20260313112147"
63
64
  },
64
65
  "peerDependencies": {
65
66
  "typescript": "^5.0.0"
package/src/address.ts ADDED
@@ -0,0 +1,220 @@
1
+ import {
2
+ combineCodec,
3
+ Decoder,
4
+ Encoder,
5
+ fixDecoderSize,
6
+ FixedSizeCodec,
7
+ FixedSizeDecoder,
8
+ FixedSizeEncoder,
9
+ fixEncoderSize,
10
+ transformEncoder,
11
+ } from '@solana/codecs-core';
12
+ import { getBase58Decoder, getBase58Encoder } from '@solana/codecs-strings';
13
+ import {
14
+ SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,
15
+ SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,
16
+ SolanaError,
17
+ } from '@solana/errors';
18
+ import { Brand, EncodedString } from '@solana/nominal-types';
19
+
20
+ /**
21
+ * Represents a string that validates as a Solana address. Functions that require well-formed
22
+ * addresses should specify their inputs in terms of this type.
23
+ *
24
+ * Whenever you need to validate an arbitrary string as a base58-encoded address, use the
25
+ * {@link address}, {@link assertIsAddress}, or {@link isAddress} functions in this package.
26
+ */
27
+ export type Address<TAddress extends string = string> = Brand<EncodedString<TAddress, 'base58'>, 'Address'>;
28
+
29
+ let memoizedBase58Encoder: Encoder<string> | undefined;
30
+ let memoizedBase58Decoder: Decoder<string> | undefined;
31
+
32
+ function getMemoizedBase58Encoder(): Encoder<string> {
33
+ if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();
34
+ return memoizedBase58Encoder;
35
+ }
36
+
37
+ function getMemoizedBase58Decoder(): Decoder<string> {
38
+ if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();
39
+ return memoizedBase58Decoder;
40
+ }
41
+
42
+ /**
43
+ * A type guard that returns `true` if the input string conforms to the {@link Address} type, and
44
+ * refines its type for use in your program.
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * import { isAddress } from '@solana/addresses';
49
+ *
50
+ * if (isAddress(ownerAddress)) {
51
+ * // At this point, `ownerAddress` has been refined to a
52
+ * // `Address` that can be used with the RPC.
53
+ * const { value: lamports } = await rpc.getBalance(ownerAddress).send();
54
+ * setBalanceLamports(lamports);
55
+ * } else {
56
+ * setError(`${ownerAddress} is not an address`);
57
+ * }
58
+ * ```
59
+ */
60
+ export function isAddress(putativeAddress: string): putativeAddress is Address<typeof putativeAddress> {
61
+ // Fast-path; see if the input string is of an acceptable length.
62
+ if (
63
+ // Lowest address (32 bytes of zeroes)
64
+ putativeAddress.length < 32 ||
65
+ // Highest address (32 bytes of 255)
66
+ putativeAddress.length > 44
67
+ ) {
68
+ return false;
69
+ }
70
+ // Slow-path; actually attempt to decode the input string.
71
+ const base58Encoder = getMemoizedBase58Encoder();
72
+ try {
73
+ return base58Encoder.encode(putativeAddress).byteLength === 32;
74
+ } catch {
75
+ return false;
76
+ }
77
+ }
78
+
79
+ /**
80
+ * From time to time you might acquire a string, that you expect to validate as an address or public
81
+ * key, from an untrusted network API or user input. Use this function to assert that such an
82
+ * arbitrary string is a base58-encoded address.
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * import { assertIsAddress } from '@solana/addresses';
87
+ *
88
+ * // Imagine a function that fetches an account's balance when a user submits a form.
89
+ * function handleSubmit() {
90
+ * // We know only that what the user typed conforms to the `string` type.
91
+ * const address: string = accountAddressInput.value;
92
+ * try {
93
+ * // If this type assertion function doesn't throw, then
94
+ * // Typescript will upcast `address` to `Address`.
95
+ * assertIsAddress(address);
96
+ * // At this point, `address` is an `Address` that can be used with the RPC.
97
+ * const balanceInLamports = await rpc.getBalance(address).send();
98
+ * } catch (e) {
99
+ * // `address` turned out not to be a base58-encoded address
100
+ * }
101
+ * }
102
+ * ```
103
+ */
104
+ export function assertIsAddress(putativeAddress: string): asserts putativeAddress is Address<typeof putativeAddress> {
105
+ // Fast-path; see if the input string is of an acceptable length.
106
+ if (
107
+ // Lowest address (32 bytes of zeroes)
108
+ putativeAddress.length < 32 ||
109
+ // Highest address (32 bytes of 255)
110
+ putativeAddress.length > 44
111
+ ) {
112
+ throw new SolanaError(SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, {
113
+ actualLength: putativeAddress.length,
114
+ });
115
+ }
116
+ // Slow-path; actually attempt to decode the input string.
117
+ const base58Encoder = getMemoizedBase58Encoder();
118
+ const bytes = base58Encoder.encode(putativeAddress);
119
+ const numBytes = bytes.byteLength;
120
+ if (numBytes !== 32) {
121
+ throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, {
122
+ actualLength: numBytes,
123
+ });
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Combines _asserting_ that a string is an address with _coercing_ it to the {@link Address} type.
129
+ * It's most useful with untrusted input.
130
+ *
131
+ * @example
132
+ * ```ts
133
+ * import { address } from '@solana/addresses';
134
+ *
135
+ * await transfer(address(fromAddress), address(toAddress), lamports(100000n));
136
+ * ```
137
+ *
138
+ * > [!TIP]
139
+ * > When starting from a known-good address as a string, it's more efficient to typecast it rather
140
+ * than to use the {@link address} helper, because the helper unconditionally performs validation on
141
+ * its input.
142
+ * >
143
+ * > ```ts
144
+ * > import { Address } from '@solana/addresses';
145
+ * >
146
+ * > const MEMO_PROGRAM_ADDRESS =
147
+ * > 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr' as Address<'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'>;
148
+ * > ```
149
+ */
150
+ export function address<TAddress extends string = string>(putativeAddress: TAddress): Address<TAddress> {
151
+ assertIsAddress(putativeAddress);
152
+ return putativeAddress as Address<TAddress>;
153
+ }
154
+
155
+ /**
156
+ * Returns an encoder that you can use to encode a base58-encoded address to a byte array.
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * import { getAddressEncoder } from '@solana/addresses';
161
+ *
162
+ * const address = 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address;
163
+ * const addressEncoder = getAddressEncoder();
164
+ * const addressBytes = addressEncoder.encode(address);
165
+ * // Uint8Array(32) [
166
+ * // 150, 183, 190, 48, 171, 8, 39, 156,
167
+ * // 122, 213, 172, 108, 193, 95, 26, 158,
168
+ * // 149, 243, 115, 254, 20, 200, 36, 30,
169
+ * // 248, 179, 178, 232, 220, 89, 53, 127
170
+ * // ]
171
+ * ```
172
+ */
173
+ export function getAddressEncoder(): FixedSizeEncoder<Address, 32> {
174
+ return transformEncoder(fixEncoderSize(getMemoizedBase58Encoder(), 32), putativeAddress =>
175
+ address(putativeAddress),
176
+ );
177
+ }
178
+
179
+ /**
180
+ * Returns a decoder that you can use to convert an array of 32 bytes representing an address to the
181
+ * base58-encoded representation of that address.
182
+ *
183
+ * @example
184
+ * ```ts
185
+ * import { getAddressDecoder } from '@solana/addresses';
186
+ *
187
+ * const addressBytes = new Uint8Array([
188
+ * 150, 183, 190, 48, 171, 8, 39, 156,
189
+ * 122, 213, 172, 108, 193, 95, 26, 158,
190
+ * 149, 243, 115, 254, 20, 200, 36, 30,
191
+ * 248, 179, 178, 232, 220, 89, 53, 127
192
+ * ]);
193
+ * const addressDecoder = getAddressDecoder();
194
+ * const address = addressDecoder.decode(addressBytes); // B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka
195
+ * ```
196
+ */
197
+ export function getAddressDecoder(): FixedSizeDecoder<Address, 32> {
198
+ return fixDecoderSize(getMemoizedBase58Decoder(), 32) as FixedSizeDecoder<Address, 32>;
199
+ }
200
+
201
+ /**
202
+ * Returns a codec that you can use to encode from or decode to a base-58 encoded address.
203
+ *
204
+ * @see {@link getAddressDecoder}
205
+ * @see {@link getAddressEncoder}
206
+ */
207
+ export function getAddressCodec(): FixedSizeCodec<Address, Address, 32> {
208
+ return combineCodec(getAddressEncoder(), getAddressDecoder());
209
+ }
210
+
211
+ export function getAddressComparator(): (x: string, y: string) => number {
212
+ return new Intl.Collator('en', {
213
+ caseFirst: 'lower',
214
+ ignorePunctuation: false,
215
+ localeMatcher: 'best fit',
216
+ numeric: false,
217
+ sensitivity: 'variant',
218
+ usage: 'sort',
219
+ }).compare;
220
+ }
@@ -0,0 +1,26 @@
1
+ import { ReadonlyUint8Array } from '@solana/codecs-core';
2
+
3
+ import { pointIsOnCurve } from './vendor/noble/ed25519';
4
+
5
+ function byteToHex(byte: number): string {
6
+ const hexString = byte.toString(16);
7
+ if (hexString.length === 1) {
8
+ return `0${hexString}`;
9
+ } else {
10
+ return hexString;
11
+ }
12
+ }
13
+
14
+ function decompressPointBytes(bytes: ReadonlyUint8Array): bigint {
15
+ const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & ~0x80 : byte)}${acc}`, '');
16
+ const integerLiteralString = `0x${hexString}`;
17
+ return BigInt(integerLiteralString);
18
+ }
19
+
20
+ export function compressedPointBytesAreOnCurve(bytes: ReadonlyUint8Array): boolean {
21
+ if (bytes.byteLength !== 32) {
22
+ return false;
23
+ }
24
+ const y = decompressPointBytes(bytes);
25
+ return pointIsOnCurve(y, bytes[31]);
26
+ }
package/src/curve.ts ADDED
@@ -0,0 +1,85 @@
1
+ import { SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS, SolanaError } from '@solana/errors';
2
+ import type { AffinePoint } from '@solana/nominal-types';
3
+
4
+ import { type Address, getAddressCodec } from './address';
5
+ import { compressedPointBytesAreOnCurve } from './curve-internal';
6
+
7
+ /**
8
+ * Represents an {@link Address} that validates as being off-curve. Functions that require off-curve
9
+ * addresses should specify their inputs in terms of this type.
10
+ *
11
+ * Whenever you need to validate an address as being off-curve, use the {@link offCurveAddress},
12
+ * {@link assertIsOffCurveAddress}, or {@link isOffCurveAddress} functions in this package.
13
+ */
14
+ export type OffCurveAddress<TAddress extends string = string> = AffinePoint<Address<TAddress>, 'invalid'>;
15
+
16
+ /**
17
+ * A type guard that returns `true` if the input address conforms to the {@link OffCurveAddress}
18
+ * type, and refines its type for use in your application.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { isOffCurveAddress } from '@solana/addresses';
23
+ *
24
+ * if (isOffCurveAddress(accountAddress)) {
25
+ * // At this point, `accountAddress` has been refined to a
26
+ * // `OffCurveAddress` that can be used within your business logic.
27
+ * const { value: account } = await rpc.getAccountInfo(accountAddress).send();
28
+ * } else {
29
+ * setError(`${accountAddress} is not off-curve`);
30
+ * }
31
+ * ```
32
+ */
33
+ export function isOffCurveAddress<TAddress extends Address>(
34
+ putativeOffCurveAddress: TAddress,
35
+ ): putativeOffCurveAddress is OffCurveAddress<TAddress> {
36
+ const addressBytes = getAddressCodec().encode(putativeOffCurveAddress);
37
+ return compressedPointBytesAreOnCurve(addressBytes) === false;
38
+ }
39
+
40
+ /**
41
+ * From time to time you might acquire an {@link Address}, that you expect to validate as an
42
+ * off-curve address, from an untrusted source. Use this function to assert that such an address is
43
+ * off-curve.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * import { assertIsOffCurveAddress } from '@solana/addresses';
48
+ *
49
+ * // Imagine a function that fetches an account's balance when a user submits a form.
50
+ * function handleSubmit() {
51
+ * // We know only that the input conforms to the `string` type.
52
+ * const address: string = accountAddressInput.value;
53
+ * try {
54
+ * // If this type assertion function doesn't throw, then
55
+ * // Typescript will upcast `address` to `Address`.
56
+ * assertIsAddress(address);
57
+ * // If this type assertion function doesn't throw, then
58
+ * // Typescript will upcast `address` to `OffCurveAddress`.
59
+ * assertIsOffCurveAddress(address);
60
+ * // At this point, `address` is an `OffCurveAddress` that can be used with the RPC.
61
+ * const balanceInLamports = await rpc.getBalance(address).send();
62
+ * } catch (e) {
63
+ * // `address` turned out to NOT be a base58-encoded off-curve address
64
+ * }
65
+ * }
66
+ * ```
67
+ */
68
+ export function assertIsOffCurveAddress<TAddress extends Address>(
69
+ putativeOffCurveAddress: TAddress,
70
+ ): asserts putativeOffCurveAddress is OffCurveAddress<TAddress> {
71
+ if (!isOffCurveAddress(putativeOffCurveAddress)) {
72
+ throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS);
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Combines _asserting_ that an {@link Address} is off-curve with _coercing_ it to the
78
+ * {@link OffCurveAddress} type. It's most useful with untrusted input.
79
+ */
80
+ export function offCurveAddress<TAddress extends Address>(
81
+ putativeOffCurveAddress: TAddress,
82
+ ): OffCurveAddress<TAddress> {
83
+ assertIsOffCurveAddress(putativeOffCurveAddress);
84
+ return putativeOffCurveAddress;
85
+ }
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * This package contains utilities for generating account addresses. It can be used standalone, but
3
+ * it is also exported as part of Kit
4
+ * [`@solana/kit`](https://github.com/anza-xyz/kit/tree/main/packages/kit).
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ export * from './address';
9
+ export * from './curve';
10
+ export * from './program-derived-address';
11
+ export * from './public-key';
@@ -0,0 +1,223 @@
1
+ import { assertDigestCapabilityIsAvailable } from '@solana/assertions';
2
+ import { bytesEqual, type ReadonlyUint8Array } from '@solana/codecs-core';
3
+ import {
4
+ isSolanaError,
5
+ SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,
6
+ SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,
7
+ SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,
8
+ SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,
9
+ SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,
10
+ SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,
11
+ SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,
12
+ SolanaError,
13
+ } from '@solana/errors';
14
+ import { Brand } from '@solana/nominal-types';
15
+
16
+ import { Address, assertIsAddress, getAddressCodec, isAddress } from './address';
17
+ import { compressedPointBytesAreOnCurve } from './curve-internal';
18
+
19
+ /**
20
+ * A tuple representing a program derived address (derived from the address of some program and a
21
+ * set of seeds) and the associated bump seed used to ensure that the address, as derived, does not
22
+ * fall on the Ed25519 curve.
23
+ *
24
+ * Whenever you need to validate an arbitrary tuple as one that represents a program derived
25
+ * address, use the {@link assertIsProgramDerivedAddress} or {@link isProgramDerivedAddress}
26
+ * functions in this package.
27
+ */
28
+ export type ProgramDerivedAddress<TAddress extends string = string> = Readonly<
29
+ [Address<TAddress>, ProgramDerivedAddressBump]
30
+ >;
31
+
32
+ /**
33
+ * Represents an integer in the range [0,255] used in the derivation of a program derived address to
34
+ * ensure that it does not fall on the Ed25519 curve.
35
+ */
36
+ export type ProgramDerivedAddressBump = Brand<number, 'ProgramDerivedAddressBump'>;
37
+
38
+ /**
39
+ * A type guard that returns `true` if the input tuple conforms to the {@link ProgramDerivedAddress}
40
+ * type, and refines its type for use in your program.
41
+ *
42
+ * @see The {@link isAddress} function for an example of how to use a type guard.
43
+ */
44
+ export function isProgramDerivedAddress<TAddress extends string = string>(
45
+ value: unknown,
46
+ ): value is ProgramDerivedAddress<TAddress> {
47
+ return (
48
+ Array.isArray(value) &&
49
+ value.length === 2 &&
50
+ typeof value[0] === 'string' &&
51
+ typeof value[1] === 'number' &&
52
+ value[1] >= 0 &&
53
+ value[1] <= 255 &&
54
+ isAddress(value[0])
55
+ );
56
+ }
57
+
58
+ /**
59
+ * In the event that you receive an address/bump-seed tuple from some untrusted source, use this
60
+ * function to assert that it conforms to the {@link ProgramDerivedAddress} interface.
61
+ *
62
+ * @see The {@link assertIsAddress} function for an example of how to use an assertion function.
63
+ */
64
+ export function assertIsProgramDerivedAddress<TAddress extends string = string>(
65
+ value: unknown,
66
+ ): asserts value is ProgramDerivedAddress<TAddress> {
67
+ const validFormat =
68
+ Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number';
69
+ if (!validFormat) {
70
+ throw new SolanaError(SOLANA_ERROR__ADDRESSES__MALFORMED_PDA);
71
+ }
72
+ if (value[1] < 0 || value[1] > 255) {
73
+ throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE, {
74
+ bump: value[1],
75
+ });
76
+ }
77
+ assertIsAddress(value[0]);
78
+ }
79
+
80
+ type ProgramDerivedAddressInput = Readonly<{
81
+ programAddress: Address;
82
+ seeds: Seed[];
83
+ }>;
84
+
85
+ type SeedInput = Readonly<{
86
+ baseAddress: Address;
87
+ programAddress: Address;
88
+ seed: Seed;
89
+ }>;
90
+
91
+ type Seed = ReadonlyUint8Array | string;
92
+
93
+ const MAX_SEED_LENGTH = 32;
94
+ const MAX_SEEDS = 16;
95
+ const PDA_MARKER_BYTES = [
96
+ // The string 'ProgramDerivedAddress'
97
+ 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115,
98
+ ] as const;
99
+
100
+ async function createProgramDerivedAddress({ programAddress, seeds }: ProgramDerivedAddressInput): Promise<Address> {
101
+ assertDigestCapabilityIsAvailable();
102
+ if (seeds.length > MAX_SEEDS) {
103
+ throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, {
104
+ actual: seeds.length,
105
+ maxSeeds: MAX_SEEDS,
106
+ });
107
+ }
108
+ let textEncoder: TextEncoder;
109
+ const seedBytes = seeds.reduce((acc, seed, ii) => {
110
+ const bytes = typeof seed === 'string' ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;
111
+ if (bytes.byteLength > MAX_SEED_LENGTH) {
112
+ throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {
113
+ actual: bytes.byteLength,
114
+ index: ii,
115
+ maxSeedLength: MAX_SEED_LENGTH,
116
+ });
117
+ }
118
+ acc.push(...bytes);
119
+ return acc;
120
+ }, [] as number[]);
121
+ const base58EncodedAddressCodec = getAddressCodec();
122
+ const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);
123
+ const addressBytesBuffer = await crypto.subtle.digest(
124
+ 'SHA-256',
125
+ new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES]),
126
+ );
127
+ const addressBytes = new Uint8Array(addressBytesBuffer);
128
+ if (compressedPointBytesAreOnCurve(addressBytes)) {
129
+ throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE);
130
+ }
131
+ return base58EncodedAddressCodec.decode(addressBytes);
132
+ }
133
+
134
+ /**
135
+ * Given a program's {@link Address} and up to 16 {@link Seed | Seeds}, this method will return the
136
+ * program derived address (PDA) associated with each.
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * import { getAddressEncoder, getProgramDerivedAddress } from '@solana/addresses';
141
+ *
142
+ * const addressEncoder = getAddressEncoder();
143
+ * const [pda, bumpSeed] = await getProgramDerivedAddress({
144
+ * programAddress: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address,
145
+ * seeds: [
146
+ * // Owner
147
+ * addressEncoder.encode('9fYLFVoVqwH37C3dyPi6cpeobfbQ2jtLpN5HgAYDDdkm' as Address),
148
+ * // Token program
149
+ * addressEncoder.encode('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address),
150
+ * // Mint
151
+ * addressEncoder.encode('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' as Address),
152
+ * ],
153
+ * });
154
+ * ```
155
+ */
156
+ export async function getProgramDerivedAddress({
157
+ programAddress,
158
+ seeds,
159
+ }: ProgramDerivedAddressInput): Promise<ProgramDerivedAddress> {
160
+ let bumpSeed = 255;
161
+ while (bumpSeed > 0) {
162
+ try {
163
+ const address = await createProgramDerivedAddress({
164
+ programAddress,
165
+ seeds: [...seeds, new Uint8Array([bumpSeed])],
166
+ });
167
+ return [address, bumpSeed as ProgramDerivedAddressBump];
168
+ } catch (e) {
169
+ if (isSolanaError(e, SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE)) {
170
+ bumpSeed--;
171
+ } else {
172
+ throw e;
173
+ }
174
+ }
175
+ }
176
+ throw new SolanaError(SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED);
177
+ }
178
+
179
+ /**
180
+ * Returns a base58-encoded address derived from some base address, some program address, and a seed
181
+ * string or byte array.
182
+ *
183
+ * @example
184
+ * ```ts
185
+ * import { createAddressWithSeed } from '@solana/addresses';
186
+ *
187
+ * const derivedAddress = await createAddressWithSeed({
188
+ * // The private key associated with this address will be able to sign for `derivedAddress`.
189
+ * baseAddress: 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address,
190
+ * // Only this program will be able to write data to this account.
191
+ * programAddress: '445erYq578p2aERrGW9mn9KiYe3fuG6uHdcJ2LPPShGw' as Address,
192
+ * seed: 'data-account',
193
+ * });
194
+ * ```
195
+ */
196
+ export async function createAddressWithSeed({ baseAddress, programAddress, seed }: SeedInput): Promise<Address> {
197
+ const { encode, decode } = getAddressCodec();
198
+
199
+ const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;
200
+ if (seedBytes.byteLength > MAX_SEED_LENGTH) {
201
+ throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {
202
+ actual: seedBytes.byteLength,
203
+ index: 0,
204
+ maxSeedLength: MAX_SEED_LENGTH,
205
+ });
206
+ }
207
+
208
+ const programAddressBytes = encode(programAddress);
209
+ if (
210
+ programAddressBytes.length >= PDA_MARKER_BYTES.length &&
211
+ bytesEqual(programAddressBytes.slice(-PDA_MARKER_BYTES.length), new Uint8Array(PDA_MARKER_BYTES))
212
+ ) {
213
+ throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER);
214
+ }
215
+
216
+ const addressBytesBuffer = await crypto.subtle.digest(
217
+ 'SHA-256',
218
+ new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes]),
219
+ );
220
+ const addressBytes = new Uint8Array(addressBytesBuffer);
221
+
222
+ return decode(addressBytes);
223
+ }
@@ -0,0 +1,38 @@
1
+ import { assertKeyExporterIsAvailable } from '@solana/assertions';
2
+ import { SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY, SolanaError } from '@solana/errors';
3
+
4
+ import { Address, getAddressDecoder, getAddressEncoder } from './address';
5
+
6
+ /**
7
+ * Given a public {@link CryptoKey}, this method will return its associated {@link Address}.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { getAddressFromPublicKey } from '@solana/addresses';
12
+ *
13
+ * const address = await getAddressFromPublicKey(publicKey);
14
+ * ```
15
+ */
16
+ export async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Address> {
17
+ assertKeyExporterIsAvailable();
18
+ if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {
19
+ throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY);
20
+ }
21
+ const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);
22
+ return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));
23
+ }
24
+
25
+ /**
26
+ * Given an {@link Address}, return a {@link CryptoKey} that can be used to verify signatures.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { getAddressFromPublicKey } from '@solana/addresses';
31
+ *
32
+ * const publicKey = await getPublicKeyFromAddress(address);
33
+ * ```
34
+ */
35
+ export async function getPublicKeyFromAddress(address: Address) {
36
+ const addressBytes = getAddressEncoder().encode(address);
37
+ return await crypto.subtle.importKey('raw', addressBytes, { name: 'Ed25519' }, true /* extractable */, ['verify']);
38
+ }
@@ -0,0 +1,94 @@
1
+ /**!
2
+ * noble-ed25519
3
+ *
4
+ * The MIT License (MIT)
5
+ *
6
+ * Copyright (c) 2019 Paul Miller (https://paulmillr.com)
7
+ *
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the “Software”), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in
16
+ * all copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
+ * THE SOFTWARE.
25
+ */
26
+ const D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;
27
+ const P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; // 2n ** 255n - 19n; ed25519 is twisted edwards curve
28
+ const RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // √-1
29
+
30
+ // mod division
31
+ function mod(a: bigint): bigint {
32
+ const r = a % P;
33
+ return r >= 0n ? r : P + r;
34
+ }
35
+ function pow2(x: bigint, power: bigint): bigint {
36
+ // pow2(x, 4) == x^(2^4)
37
+ let r = x;
38
+ while (power-- > 0n) {
39
+ r *= r;
40
+ r %= P;
41
+ }
42
+ return r;
43
+ }
44
+ function pow_2_252_3(x: bigint): bigint {
45
+ // x^(2^252-3) unrolled util for square root
46
+ const x2 = (x * x) % P; // x^2, bits 1
47
+ const b2 = (x2 * x) % P; // x^3, bits 11
48
+ const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111
49
+ const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111
50
+ const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)
51
+ const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)
52
+ const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)
53
+ const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)
54
+ const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)
55
+ const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)
56
+ const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)
57
+ const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.
58
+ return pow_p_5_8;
59
+ }
60
+ function uvRatio(u: bigint, v: bigint): bigint | null {
61
+ // for sqrt comp
62
+ const v3 = mod(v * v * v); // v³
63
+ const v7 = mod(v3 * v3 * v); // v⁷
64
+ const pow = pow_2_252_3(u * v7); // (uv⁷)^(p-5)/8
65
+ let x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8
66
+ const vx2 = mod(v * x * x); // vx²
67
+ const root1 = x; // First root candidate
68
+ const root2 = mod(x * RM1); // Second root candidate; RM1 is √-1
69
+ const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root
70
+ const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)
71
+ const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1
72
+ if (useRoot1) x = root1;
73
+ if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time
74
+ if ((mod(x) & 1n) === 1n) x = mod(-x); // edIsNegative
75
+ if (!useRoot1 && !useRoot2) {
76
+ return null;
77
+ }
78
+ return x;
79
+ }
80
+ // https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.3
81
+ export function pointIsOnCurve(y: bigint, lastByte: number): boolean {
82
+ const y2 = mod(y * y); // y²
83
+ const u = mod(y2 - 1n); // u=y²-1
84
+ const v = mod(D * y2 + 1n);
85
+ const x = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root
86
+ if (x === null) {
87
+ return false;
88
+ }
89
+ const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
90
+ if (x === 0n && isLastByteOdd) {
91
+ return false;
92
+ }
93
+ return true;
94
+ }