@solana/addresses 2.0.0-experimental.f8b14a7 → 2.0.0-experimental.fa2293f
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +127 -20
- package/dist/index.browser.cjs +139 -54
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.js +129 -51
- package/dist/index.browser.js.map +1 -1
- package/dist/index.native.js +129 -51
- package/dist/index.native.js.map +1 -1
- package/dist/index.node.cjs +139 -54
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.js +129 -51
- package/dist/index.node.js.map +1 -1
- package/dist/types/address.d.ts +12 -0
- package/dist/types/address.d.ts.map +1 -0
- package/dist/types/index.d.ts +3 -3
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/program-derived-address.d.ts +34 -8
- package/dist/types/program-derived-address.d.ts.map +1 -1
- package/dist/types/public-key.d.ts +2 -2
- package/dist/types/public-key.d.ts.map +1 -1
- package/package.json +17 -35
- package/dist/index.development.js +0 -517
- package/dist/index.development.js.map +0 -1
- package/dist/index.production.min.js +0 -15
- package/dist/types/base58.d.ts +0 -10
- package/dist/types/base58.d.ts.map +0 -1
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -18,22 +18,51 @@ This package contains utilities for generating account addresses. It can be used
|
|
|
18
18
|
|
|
19
19
|
## Types
|
|
20
20
|
|
|
21
|
-
### `
|
|
21
|
+
### `Address`
|
|
22
22
|
|
|
23
23
|
This type represents a string that validates as a Solana address. Functions that require well-formed addresses should specify their inputs in terms of this type.
|
|
24
24
|
|
|
25
|
-
Whenever you need to validate an arbitrary string as a base58-encoded address, use the `
|
|
25
|
+
Whenever you need to validate an arbitrary string as a base58-encoded address, use the `address()`, `assertIsAddress()`, or `isAddress()` functions in this package.
|
|
26
|
+
|
|
27
|
+
### `ProgramDerivedAddress`
|
|
28
|
+
|
|
29
|
+
This type represents the tuple of a program derived address and the bump seed used to ensure that the address, as derived, is not found on the Ed25519 curve.
|
|
30
|
+
|
|
31
|
+
Whenever you need to validate an arbitrary tuple as one that represents a program derived address, use the `assertIsProgramDerivedAddress()` or `isProgramDerivedAddress()` functions in this package.
|
|
32
|
+
|
|
33
|
+
### `ProgramDerivedAddressBump`
|
|
34
|
+
|
|
35
|
+
This type represents an integer between 0-255 used as a seed when deriving a program derived address. The purpose of this value is to modify the derivation enough to ensure that the derived address does not find itself on the Ed25519 curve.
|
|
26
36
|
|
|
27
37
|
## Functions
|
|
28
38
|
|
|
29
|
-
### `
|
|
39
|
+
### `address()`
|
|
40
|
+
|
|
41
|
+
This helper combines _asserting_ that a string is an address with _coercing_ it to the `Address` type. It's best used with untrusted input.
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { address } from '@solana/addresses';
|
|
45
|
+
|
|
46
|
+
await transfer(address(fromAddress), address(toAddress), lamports(100000n));
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
When starting from a known-good address as a string, it's more efficient to typecast it rather than to use the `address()` helper, because the helper unconditionally performs validation on its input.
|
|
30
50
|
|
|
31
|
-
|
|
51
|
+
```ts
|
|
52
|
+
import { Address } from '@solana/addresses';
|
|
53
|
+
|
|
54
|
+
const MEMO_PROGRAM_ADDRESS =
|
|
55
|
+
'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr' as Address<'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'>;
|
|
56
|
+
```
|
|
32
57
|
|
|
33
|
-
|
|
58
|
+
### `assertIsAddress()`
|
|
59
|
+
|
|
60
|
+
Client applications primarily deal with addresses and public keys in the form of base58-encoded strings. Addresses returned from the RPC API conform to the type `Address`. You can use a value of that type wherever a base58-encoded address is expected.
|
|
61
|
+
|
|
62
|
+
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 `assertIsAddress` function.
|
|
34
63
|
|
|
35
64
|
```ts
|
|
36
|
-
import {
|
|
65
|
+
import { assertIsAddress } from '@solana/addresses';
|
|
37
66
|
|
|
38
67
|
// Imagine a function that fetches an account's balance when a user submits a form.
|
|
39
68
|
function handleSubmit() {
|
|
@@ -41,9 +70,9 @@ function handleSubmit() {
|
|
|
41
70
|
const address: string = accountAddressInput.value;
|
|
42
71
|
try {
|
|
43
72
|
// If this type assertion function doesn't throw, then
|
|
44
|
-
// Typescript will upcast `address` to `
|
|
45
|
-
|
|
46
|
-
// At this point, `address` is
|
|
73
|
+
// Typescript will upcast `address` to `Address`.
|
|
74
|
+
assertIsAddress(address);
|
|
75
|
+
// At this point, `address` is an `Address` that can be used with the RPC.
|
|
47
76
|
const balanceInLamports = await rpc.getBalance(address).send();
|
|
48
77
|
} catch (e) {
|
|
49
78
|
// `address` turned out not to be a base58-encoded address
|
|
@@ -51,33 +80,111 @@ function handleSubmit() {
|
|
|
51
80
|
}
|
|
52
81
|
```
|
|
53
82
|
|
|
54
|
-
### `
|
|
83
|
+
### `assertIsProgramDerivedAddress()`
|
|
84
|
+
|
|
85
|
+
In the event that you receive an address/bump-seed tuple from some untrusted source, you can assert that such a tuple conforms to the `ProgramDerivedAddress` type using this function.
|
|
86
|
+
|
|
87
|
+
See [`assertIsAddress()`](#assertisaddress) for an example of how to use an assertion function.
|
|
88
|
+
|
|
89
|
+
### `createAddressWithSeed()`
|
|
90
|
+
|
|
91
|
+
Returns a base58-encoded address derived from some base address, some program address, and a seed string or byte array.
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { createAddressWithSeed } from '@solana/addresses';
|
|
95
|
+
|
|
96
|
+
const derivedAddress = await createAddressWithSeed({
|
|
97
|
+
// The private key associated with this address will be able to sign for `derivedAddress`.
|
|
98
|
+
baseAddress: 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address,
|
|
99
|
+
// Only this program will be able to write data to this account.
|
|
100
|
+
programAddress: '445erYq578p2aERrGW9mn9KiYe3fuG6uHdcJ2LPPShGw' as Address,
|
|
101
|
+
seed: 'data-account',
|
|
102
|
+
});
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### `getAddressDecoder()`
|
|
106
|
+
|
|
107
|
+
Returns a decoder that you can use to convert an array of 32 bytes representing an address to the base58-encoded representation of that address. Returns a tuple of the `Address` and the offset within the byte array at which the decoder stopped reading.
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
import { getAddressDecoder } from '@solana/addresses';
|
|
111
|
+
|
|
112
|
+
const addressBytes = new Uint8Array([
|
|
113
|
+
150, 183, 190, 48, 171, 8, 39, 156, 122, 213, 172, 108, 193, 95, 26, 158, 149, 243, 115, 254, 20, 200, 36, 30, 248,
|
|
114
|
+
179, 178, 232, 220, 89, 53, 127,
|
|
115
|
+
]);
|
|
116
|
+
const addressDecoder = getAddressDecoder();
|
|
117
|
+
const address = addressDecoder.decode(address); // B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### `getAddressEncoder()`
|
|
121
|
+
|
|
122
|
+
Returns an encoder that you can use to encode a base58-encoded address to a byte array.
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import { getAddressEncoder } from '@solana/addresses';
|
|
126
|
+
|
|
127
|
+
const address = 'B9Lf9z5BfNPT4d5KMeaBFx8x1G4CULZYR1jA2kmxRDka' as Address;
|
|
128
|
+
const addressEncoder = getAddressEncoder();
|
|
129
|
+
const addressBytes = addressEncoder.encode(address);
|
|
130
|
+
// Uint8Array(32) [
|
|
131
|
+
// 150, 183, 190, 48, 171, 8, 39, 156,
|
|
132
|
+
// 122, 213, 172, 108, 193, 95, 26, 158,
|
|
133
|
+
// 149, 243, 115, 254, 20, 200, 36, 30,
|
|
134
|
+
// 248, 179, 178, 232, 220, 89, 53, 127
|
|
135
|
+
// ]
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### `getAddressFromPublicKey()`
|
|
55
139
|
|
|
56
|
-
Given a public `CryptoKey`, this method will return its associated `
|
|
140
|
+
Given a public `CryptoKey`, this method will return its associated `Address`.
|
|
57
141
|
|
|
58
142
|
```ts
|
|
59
|
-
import {
|
|
143
|
+
import { getAddressFromPublicKey } from '@solana/addresses';
|
|
60
144
|
|
|
61
|
-
const address = await
|
|
145
|
+
const address = await getAddressFromPublicKey(publicKey);
|
|
62
146
|
```
|
|
63
147
|
|
|
64
148
|
### `getProgramDerivedAddress()`
|
|
65
149
|
|
|
66
|
-
Given a program's `
|
|
150
|
+
Given a program's `Address` and up to 16 `Seeds`, this method will return the program derived address (PDA) associated with each.
|
|
67
151
|
|
|
68
152
|
```ts
|
|
69
|
-
import {
|
|
153
|
+
import { getAddressEncoder, getProgramDerivedAddress } from '@solana/addresses';
|
|
70
154
|
|
|
71
|
-
const
|
|
155
|
+
const addressEncoder = getAddressEncoder();
|
|
72
156
|
const { bumpSeed, pda } = await getProgramDerivedAddress({
|
|
73
|
-
programAddress: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as
|
|
157
|
+
programAddress: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address,
|
|
74
158
|
seeds: [
|
|
75
159
|
// Owner
|
|
76
|
-
|
|
160
|
+
addressEncoder.encode('9fYLFVoVqwH37C3dyPi6cpeobfbQ2jtLpN5HgAYDDdkm' as Address),
|
|
77
161
|
// Token program
|
|
78
|
-
|
|
162
|
+
addressEncoder.encode('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address),
|
|
79
163
|
// Mint
|
|
80
|
-
|
|
164
|
+
addressEncoder.encode('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' as Address),
|
|
81
165
|
],
|
|
82
166
|
});
|
|
83
167
|
```
|
|
168
|
+
|
|
169
|
+
### `isAddress()`
|
|
170
|
+
|
|
171
|
+
This is a type guard that accepts a string as input. It will both return `true` if the string conforms to the `Address` type and will refine the type for use in your program.
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
import { isAddress } from '@solana/addresses';
|
|
175
|
+
|
|
176
|
+
if (isAddress(ownerAddress)) {
|
|
177
|
+
// At this point, `ownerAddress` has been refined to a
|
|
178
|
+
// `Address` that can be used with the RPC.
|
|
179
|
+
const { value: lamports } = await rpc.getBalance(ownerAddress).send();
|
|
180
|
+
setBalanceLamports(lamports);
|
|
181
|
+
} else {
|
|
182
|
+
setError(`${ownerAddress} is not an address`);
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### `isProgramDerivedAddress()`
|
|
187
|
+
|
|
188
|
+
This is a type guard that accepts a tuple as input. It will both return `true` if the tuple conforms to the `ProgramDerivedAddress` type and will refine the type for use in your program.
|
|
189
|
+
|
|
190
|
+
See [`isAddress()`](#isaddress) for an example of how to use a type guard.
|
package/dist/index.browser.cjs
CHANGED
|
@@ -1,38 +1,75 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var codecsCore = require('@solana/codecs-core');
|
|
4
|
+
var codecsStrings = require('@solana/codecs-strings');
|
|
5
|
+
var errors = require('@solana/errors');
|
|
4
6
|
var assertions = require('@solana/assertions');
|
|
5
7
|
|
|
6
|
-
//
|
|
7
|
-
var
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
8
|
+
// src/address.ts
|
|
9
|
+
var memoizedBase58Encoder;
|
|
10
|
+
var memoizedBase58Decoder;
|
|
11
|
+
function getMemoizedBase58Encoder() {
|
|
12
|
+
if (!memoizedBase58Encoder)
|
|
13
|
+
memoizedBase58Encoder = codecsStrings.getBase58Encoder();
|
|
14
|
+
return memoizedBase58Encoder;
|
|
15
|
+
}
|
|
16
|
+
function getMemoizedBase58Decoder() {
|
|
17
|
+
if (!memoizedBase58Decoder)
|
|
18
|
+
memoizedBase58Decoder = codecsStrings.getBase58Decoder();
|
|
19
|
+
return memoizedBase58Decoder;
|
|
20
|
+
}
|
|
21
|
+
function isAddress(putativeAddress) {
|
|
22
|
+
if (
|
|
23
|
+
// Lowest address (32 bytes of zeroes)
|
|
24
|
+
putativeAddress.length < 32 || // Highest address (32 bytes of 255)
|
|
25
|
+
putativeAddress.length > 44
|
|
26
|
+
) {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
const base58Encoder = getMemoizedBase58Encoder();
|
|
30
|
+
const bytes = base58Encoder.encode(putativeAddress);
|
|
31
|
+
const numBytes = bytes.byteLength;
|
|
32
|
+
if (numBytes !== 32) {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
function assertIsAddress(putativeAddress) {
|
|
38
|
+
if (
|
|
39
|
+
// Lowest address (32 bytes of zeroes)
|
|
40
|
+
putativeAddress.length < 32 || // Highest address (32 bytes of 255)
|
|
41
|
+
putativeAddress.length > 44
|
|
42
|
+
) {
|
|
43
|
+
throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, {
|
|
44
|
+
actualLength: putativeAddress.length
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
const base58Encoder = getMemoizedBase58Encoder();
|
|
48
|
+
const bytes = base58Encoder.encode(putativeAddress);
|
|
49
|
+
const numBytes = bytes.byteLength;
|
|
50
|
+
if (numBytes !== 32) {
|
|
51
|
+
throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, {
|
|
52
|
+
actualLength: numBytes
|
|
25
53
|
});
|
|
26
54
|
}
|
|
27
55
|
}
|
|
28
|
-
function
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
56
|
+
function address(putativeAddress) {
|
|
57
|
+
assertIsAddress(putativeAddress);
|
|
58
|
+
return putativeAddress;
|
|
59
|
+
}
|
|
60
|
+
function getAddressEncoder() {
|
|
61
|
+
return codecsCore.mapEncoder(
|
|
62
|
+
codecsStrings.getStringEncoder({ encoding: getMemoizedBase58Encoder(), size: 32 }),
|
|
63
|
+
(putativeAddress) => address(putativeAddress)
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
function getAddressDecoder() {
|
|
67
|
+
return codecsStrings.getStringDecoder({ encoding: getMemoizedBase58Decoder(), size: 32 });
|
|
34
68
|
}
|
|
35
|
-
function
|
|
69
|
+
function getAddressCodec() {
|
|
70
|
+
return codecsCore.combineCodec(getAddressEncoder(), getAddressDecoder());
|
|
71
|
+
}
|
|
72
|
+
function getAddressComparator() {
|
|
36
73
|
return new Intl.Collator("en", {
|
|
37
74
|
caseFirst: "lower",
|
|
38
75
|
ignorePunctuation: false,
|
|
@@ -134,6 +171,21 @@ async function compressedPointBytesAreOnCurve(bytes) {
|
|
|
134
171
|
}
|
|
135
172
|
|
|
136
173
|
// src/program-derived-address.ts
|
|
174
|
+
function isProgramDerivedAddress(value) {
|
|
175
|
+
return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number" && value[1] >= 0 && value[1] <= 255 && isAddress(value[0]);
|
|
176
|
+
}
|
|
177
|
+
function assertIsProgramDerivedAddress(value) {
|
|
178
|
+
const validFormat = Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number";
|
|
179
|
+
if (!validFormat) {
|
|
180
|
+
throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__MALFORMED_PDA);
|
|
181
|
+
}
|
|
182
|
+
if (value[1] < 0 || value[1] > 255) {
|
|
183
|
+
throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE, {
|
|
184
|
+
bump: value[1]
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
assertIsAddress(value[0]);
|
|
188
|
+
}
|
|
137
189
|
var MAX_SEED_LENGTH = 32;
|
|
138
190
|
var MAX_SEEDS = 16;
|
|
139
191
|
var PDA_MARKER_BYTES = [
|
|
@@ -160,69 +212,102 @@ var PDA_MARKER_BYTES = [
|
|
|
160
212
|
115,
|
|
161
213
|
115
|
|
162
214
|
];
|
|
163
|
-
var PointOnCurveError = class extends Error {
|
|
164
|
-
};
|
|
165
215
|
async function createProgramDerivedAddress({ programAddress, seeds }) {
|
|
166
216
|
await assertions.assertDigestCapabilityIsAvailable();
|
|
167
217
|
if (seeds.length > MAX_SEEDS) {
|
|
168
|
-
throw new
|
|
218
|
+
throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, {
|
|
219
|
+
actual: seeds.length,
|
|
220
|
+
maxSeeds: MAX_SEEDS
|
|
221
|
+
});
|
|
169
222
|
}
|
|
170
223
|
let textEncoder;
|
|
171
224
|
const seedBytes = seeds.reduce((acc, seed, ii) => {
|
|
172
|
-
const bytes = typeof seed === "string" ? (textEncoder
|
|
225
|
+
const bytes = typeof seed === "string" ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;
|
|
173
226
|
if (bytes.byteLength > MAX_SEED_LENGTH) {
|
|
174
|
-
throw new
|
|
227
|
+
throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {
|
|
228
|
+
actual: bytes.byteLength,
|
|
229
|
+
index: ii,
|
|
230
|
+
maxSeedLength: MAX_SEED_LENGTH
|
|
231
|
+
});
|
|
175
232
|
}
|
|
176
233
|
acc.push(...bytes);
|
|
177
234
|
return acc;
|
|
178
235
|
}, []);
|
|
179
|
-
const base58EncodedAddressCodec =
|
|
180
|
-
const programAddressBytes = base58EncodedAddressCodec.
|
|
236
|
+
const base58EncodedAddressCodec = getAddressCodec();
|
|
237
|
+
const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);
|
|
181
238
|
const addressBytesBuffer = await crypto.subtle.digest(
|
|
182
239
|
"SHA-256",
|
|
183
240
|
new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])
|
|
184
241
|
);
|
|
185
242
|
const addressBytes = new Uint8Array(addressBytesBuffer);
|
|
186
243
|
if (await compressedPointBytesAreOnCurve(addressBytes)) {
|
|
187
|
-
throw new
|
|
244
|
+
throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE);
|
|
188
245
|
}
|
|
189
|
-
return base58EncodedAddressCodec.
|
|
246
|
+
return base58EncodedAddressCodec.decode(addressBytes);
|
|
190
247
|
}
|
|
191
|
-
async function getProgramDerivedAddress({
|
|
248
|
+
async function getProgramDerivedAddress({
|
|
249
|
+
programAddress,
|
|
250
|
+
seeds
|
|
251
|
+
}) {
|
|
192
252
|
let bumpSeed = 255;
|
|
193
253
|
while (bumpSeed > 0) {
|
|
194
254
|
try {
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
})
|
|
201
|
-
};
|
|
255
|
+
const address2 = await createProgramDerivedAddress({
|
|
256
|
+
programAddress,
|
|
257
|
+
seeds: [...seeds, new Uint8Array([bumpSeed])]
|
|
258
|
+
});
|
|
259
|
+
return [address2, bumpSeed];
|
|
202
260
|
} catch (e) {
|
|
203
|
-
if (e
|
|
261
|
+
if (errors.isSolanaError(e, errors.SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE)) {
|
|
204
262
|
bumpSeed--;
|
|
205
263
|
} else {
|
|
206
264
|
throw e;
|
|
207
265
|
}
|
|
208
266
|
}
|
|
209
267
|
}
|
|
210
|
-
throw new
|
|
268
|
+
throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED);
|
|
269
|
+
}
|
|
270
|
+
async function createAddressWithSeed({ baseAddress, programAddress, seed }) {
|
|
271
|
+
const { encode, decode } = getAddressCodec();
|
|
272
|
+
const seedBytes = typeof seed === "string" ? new TextEncoder().encode(seed) : seed;
|
|
273
|
+
if (seedBytes.byteLength > MAX_SEED_LENGTH) {
|
|
274
|
+
throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {
|
|
275
|
+
actual: seedBytes.byteLength,
|
|
276
|
+
index: 0,
|
|
277
|
+
maxSeedLength: MAX_SEED_LENGTH
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
const programAddressBytes = encode(programAddress);
|
|
281
|
+
if (programAddressBytes.length >= PDA_MARKER_BYTES.length && programAddressBytes.slice(-PDA_MARKER_BYTES.length).every((byte, index) => byte === PDA_MARKER_BYTES[index])) {
|
|
282
|
+
throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER);
|
|
283
|
+
}
|
|
284
|
+
const addressBytesBuffer = await crypto.subtle.digest(
|
|
285
|
+
"SHA-256",
|
|
286
|
+
new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes])
|
|
287
|
+
);
|
|
288
|
+
const addressBytes = new Uint8Array(addressBytesBuffer);
|
|
289
|
+
return decode(addressBytes);
|
|
211
290
|
}
|
|
212
|
-
async function
|
|
291
|
+
async function getAddressFromPublicKey(publicKey) {
|
|
213
292
|
await assertions.assertKeyExporterIsAvailable();
|
|
214
293
|
if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") {
|
|
215
|
-
throw new
|
|
294
|
+
throw new errors.SolanaError(errors.SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY);
|
|
216
295
|
}
|
|
217
296
|
const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
|
|
218
|
-
|
|
219
|
-
return base58EncodedAddress;
|
|
297
|
+
return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));
|
|
220
298
|
}
|
|
221
299
|
|
|
222
|
-
exports.
|
|
223
|
-
exports.
|
|
224
|
-
exports.
|
|
225
|
-
exports.
|
|
300
|
+
exports.address = address;
|
|
301
|
+
exports.assertIsAddress = assertIsAddress;
|
|
302
|
+
exports.assertIsProgramDerivedAddress = assertIsProgramDerivedAddress;
|
|
303
|
+
exports.createAddressWithSeed = createAddressWithSeed;
|
|
304
|
+
exports.getAddressCodec = getAddressCodec;
|
|
305
|
+
exports.getAddressComparator = getAddressComparator;
|
|
306
|
+
exports.getAddressDecoder = getAddressDecoder;
|
|
307
|
+
exports.getAddressEncoder = getAddressEncoder;
|
|
308
|
+
exports.getAddressFromPublicKey = getAddressFromPublicKey;
|
|
226
309
|
exports.getProgramDerivedAddress = getProgramDerivedAddress;
|
|
310
|
+
exports.isAddress = isAddress;
|
|
311
|
+
exports.isProgramDerivedAddress = isProgramDerivedAddress;
|
|
227
312
|
//# sourceMappingURL=out.js.map
|
|
228
313
|
//# sourceMappingURL=index.browser.cjs.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,KA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cAAc;AAC9E,QAAM,qBAAqB,MAAM,OAAO,OAAO;AAAA,IAC3C;AAAA,IACA,IAAI,WAAW,CAAC,GAAG,WAAW,GAAG,qBAAqB,GAAG,gBAAgB,CAAC;AAAA,EAC9E;AACA,QAAM,eAAe,IAAI,WAAW,kBAAkB;AACtD,MAAI,MAAM,+BAA+B,YAAY,GAAG;AAEpD,UAAM,IAAI,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,qCAAqC,WAAqD;AAC5G,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 getBase58EncodedAddressFromPublicKey(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":["../src/address.ts","../src/program-derived-address.ts","../src/vendor/noble/ed25519.ts","../src/curve.ts","../src/public-key.ts"],"names":["SolanaError","address"],"mappings":";AAAA;AAAA,EACI;AAAA,EAMA;AAAA,OACG;AACP,SAAS,kBAAkB,kBAAkB,kBAAkB,wBAAwB;AACvF;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAMP,IAAI;AACJ,IAAI;AAEJ,SAAS,2BAA4C;AACjD,MAAI,CAAC;AAAuB,4BAAwB,iBAAiB;AACrE,SAAO;AACX;AAEA,SAAS,2BAA4C;AACjD,MAAI,CAAC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AAE,aAAa,gBAAgB,KAAK,GAAgC;AAC5G,QAAM,EAAE,QAAQ,OAAO,IAAI,gBAAgB;AAE3C,QAAM,YAAY,OAAO,SAAS,WAAW,IAAI,YAAY,EAAE,OAAO,IAAI,IAAI;AAC9E,MAAI,UAAU,aAAa,iBAAiB;AACxC,UAAM,IAAIA,aAAY,uDAAuD;AAAA,MACzE,QAAQ,UAAU;AAAA,MAClB,OAAO;AAAA,MACP,eAAe;AAAA,IACnB,CAAC;AAAA,EACL;AAEA,QAAM,sBAAsB,OAAO,cAAc;AACjD,MACI,oBAAoB,UAAU,iBAAiB,UAC/C,oBAAoB,MAAM,CAAC,iBAAiB,MAAM,EAAE,MAAM,CAAC,MAAM,UAAU,SAAS,iBAAiB,KAAK,CAAC,GAC7G;AACE,UAAM,IAAIA,aAAY,iDAAiD;AAAA,EAC3E;AAEA,QAAM,qBAAqB,MAAM,OAAO,OAAO;AAAA,IAC3C;AAAA,IACA,IAAI,WAAW,CAAC,GAAG,OAAO,WAAW,GAAG,GAAG,WAAW,GAAG,mBAAmB,CAAC;AAAA,EACjF;AACA,QAAM,eAAe,IAAI,WAAW,kBAAkB;AAEtD,SAAO,OAAO,YAAY;AAC9B;;;AG5KA,SAAS,oCAAoC;AAC7C,SAAS,qDAAqD,eAAAA,oBAAmB;AAIjF,eAAsB,wBAAwB,WAAwC;AAClF,QAAM,6BAA6B;AACnC,MAAI,UAAU,SAAS,YAAY,UAAU,UAAU,SAAS,WAAW;AACvE,UAAM,IAAIA,aAAY,mDAAmD;AAAA,EAC7E;AACA,QAAM,iBAAiB,MAAM,OAAO,OAAO,UAAU,OAAO,SAAS;AACrE,SAAO,kBAAkB,EAAE,OAAO,IAAI,WAAW,cAAc,CAAC;AACpE","sourcesContent":["import {\n combineCodec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n mapEncoder,\n} from '@solana/codecs-core';\nimport { getBase58Decoder, getBase58Encoder, getStringDecoder, getStringEncoder } from '@solana/codecs-strings';\nimport {\n SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,\n SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,\n SolanaError,\n} from '@solana/errors';\n\nexport type Address<TAddress extends string = string> = TAddress & {\n readonly __brand: unique symbol;\n};\n\nlet memoizedBase58Encoder: Encoder<string> | undefined;\nlet memoizedBase58Decoder: Decoder<string> | undefined;\n\nfunction getMemoizedBase58Encoder(): Encoder<string> {\n if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();\n return memoizedBase58Encoder;\n}\n\nfunction getMemoizedBase58Decoder(): Decoder<string> {\n if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();\n return memoizedBase58Decoder;\n}\n\nexport function isAddress(putativeAddress: string): putativeAddress is Address<typeof putativeAddress> {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n return false;\n }\n return true;\n}\n\nexport function assertIsAddress(putativeAddress: string): asserts putativeAddress is Address<typeof putativeAddress> {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeAddress.length > 44\n ) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, {\n actualLength: putativeAddress.length,\n });\n }\n // Slow-path; actually attempt to decode the input string.\n const base58Encoder = getMemoizedBase58Encoder();\n const bytes = base58Encoder.encode(putativeAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, {\n actualLength: numBytes,\n });\n }\n}\n\nexport function address<TAddress extends string = string>(putativeAddress: TAddress): Address<TAddress> {\n assertIsAddress(putativeAddress);\n return putativeAddress as Address<TAddress>;\n}\n\nexport function getAddressEncoder(): FixedSizeEncoder<Address, 32> {\n return mapEncoder(getStringEncoder({ encoding: getMemoizedBase58Encoder(), size: 32 }), putativeAddress =>\n address(putativeAddress),\n );\n}\n\nexport function getAddressDecoder(): FixedSizeDecoder<Address, 32> {\n return getStringDecoder({ encoding: getMemoizedBase58Decoder(), size: 32 }) as FixedSizeDecoder<Address, 32>;\n}\n\nexport function getAddressCodec(): FixedSizeCodec<Address, Address, 32> {\n return combineCodec(getAddressEncoder(), getAddressDecoder());\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';\nimport {\n isSolanaError,\n SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,\n SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,\n SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,\n SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,\n SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,\n SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,\n SolanaError,\n} from '@solana/errors';\n\nimport { Address, assertIsAddress, 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 [Address<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 throw new SolanaError(SOLANA_ERROR__ADDRESSES__MALFORMED_PDA);\n }\n if (value[1] < 0 || value[1] > 255) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE, {\n bump: value[1],\n });\n }\n assertIsAddress(value[0]);\n}\n\ntype ProgramDerivedAddressInput = Readonly<{\n programAddress: Address;\n seeds: Seed[];\n}>;\n\ntype SeedInput = Readonly<{\n baseAddress: Address;\n programAddress: Address;\n seed: Seed;\n}>;\n\ntype Seed = Uint8Array | string;\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\nasync function createProgramDerivedAddress({ programAddress, seeds }: ProgramDerivedAddressInput): Promise<Address> {\n await assertDigestCapabilityIsAvailable();\n if (seeds.length > MAX_SEEDS) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, {\n actual: seeds.length,\n maxSeeds: MAX_SEEDS,\n });\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 throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {\n actual: bytes.byteLength,\n index: ii,\n maxSeedLength: MAX_SEED_LENGTH,\n });\n }\n acc.push(...bytes);\n return acc;\n }, [] as number[]);\n const base58EncodedAddressCodec = getAddressCodec();\n const programAddressBytes = base58EncodedAddressCodec.encode(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 throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE);\n }\n return base58EncodedAddressCodec.decode(addressBytes);\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 (isSolanaError(e, SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE)) {\n bumpSeed--;\n } else {\n throw e;\n }\n }\n }\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED);\n}\n\nexport async function createAddressWithSeed({ baseAddress, programAddress, seed }: SeedInput): Promise<Address> {\n const { encode, decode } = getAddressCodec();\n\n const seedBytes = typeof seed === 'string' ? new TextEncoder().encode(seed) : seed;\n if (seedBytes.byteLength > MAX_SEED_LENGTH) {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {\n actual: seedBytes.byteLength,\n index: 0,\n maxSeedLength: MAX_SEED_LENGTH,\n });\n }\n\n const programAddressBytes = encode(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 throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER);\n }\n\n const addressBytesBuffer = await crypto.subtle.digest(\n 'SHA-256',\n new Uint8Array([...encode(baseAddress), ...seedBytes, ...programAddressBytes]),\n );\n const addressBytes = new Uint8Array(addressBytesBuffer);\n\n return decode(addressBytes);\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';\nimport { SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY, SolanaError } from '@solana/errors';\n\nimport { Address, getAddressDecoder } from './address';\n\nexport async function getAddressFromPublicKey(publicKey: CryptoKey): Promise<Address> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY);\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));\n}\n"]}
|