@solana/accounts 2.0.0-development
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 +20 -0
- package/README.md +313 -0
- package/dist/index.browser.cjs +114 -0
- package/dist/index.browser.cjs.map +1 -0
- package/dist/index.browser.js +100 -0
- package/dist/index.browser.js.map +1 -0
- package/dist/index.native.js +100 -0
- package/dist/index.native.js.map +1 -0
- package/dist/index.node.cjs +114 -0
- package/dist/index.node.cjs.map +1 -0
- package/dist/index.node.js +100 -0
- package/dist/index.node.js.map +1 -0
- package/dist/types/account.d.ts +18 -0
- package/dist/types/account.d.ts.map +1 -0
- package/dist/types/decode-account.d.ts +13 -0
- package/dist/types/decode-account.d.ts.map +1 -0
- package/dist/types/fetch-account.d.ts +59 -0
- package/dist/types/fetch-account.d.ts.map +1 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/maybe-account.d.ts +20 -0
- package/dist/types/maybe-account.d.ts.map +1 -0
- package/dist/types/parse-account.d.ts +20 -0
- package/dist/types/parse-account.d.ts.map +1 -0
- package/dist/types/rpc-api/common.d.ts +42 -0
- package/dist/types/rpc-api/common.d.ts.map +1 -0
- package/dist/types/rpc-api/getAccountInfo.d.ts +34 -0
- package/dist/types/rpc-api/getAccountInfo.d.ts.map +1 -0
- package/dist/types/rpc-api/getMultipleAccounts.d.ts +44 -0
- package/dist/types/rpc-api/getMultipleAccounts.d.ts.map +1 -0
- package/dist/types/rpc-api/index.d.ts +4 -0
- package/dist/types/rpc-api/index.d.ts.map +1 -0
- package/package.json +98 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Copyright (c) 2023 Solana Labs, Inc
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
4
|
+
a copy of this software and associated documentation files (the
|
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
9
|
+
the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be
|
|
12
|
+
included in all copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
[![npm][npm-image]][npm-url]
|
|
2
|
+
[![npm-downloads][npm-downloads-image]][npm-url]
|
|
3
|
+
[![semantic-release][semantic-release-image]][semantic-release-url]
|
|
4
|
+
<br />
|
|
5
|
+
[![code-style-prettier][code-style-prettier-image]][code-style-prettier-url]
|
|
6
|
+
|
|
7
|
+
[code-style-prettier-image]: https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square
|
|
8
|
+
[code-style-prettier-url]: https://github.com/prettier/prettier
|
|
9
|
+
[npm-downloads-image]: https://img.shields.io/npm/dm/@solana/accounts/experimental.svg?style=flat
|
|
10
|
+
[npm-image]: https://img.shields.io/npm/v/@solana/accounts/experimental.svg?style=flat
|
|
11
|
+
[npm-url]: https://www.npmjs.com/package/@solana/accounts/v/experimental
|
|
12
|
+
[semantic-release-image]: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg
|
|
13
|
+
[semantic-release-url]: https://github.com/semantic-release/semantic-release
|
|
14
|
+
|
|
15
|
+
# @solana/accounts
|
|
16
|
+
|
|
17
|
+
This package contains types and helper methods for representing, fetching and decoding Solana accounts. It can be used standalone, but it is also exported as part of the Solana JavaScript SDK [`@solana/web3.js@experimental`](https://github.com/solana-labs/solana-web3.js/tree/master/packages/library).
|
|
18
|
+
|
|
19
|
+
It provides a unified definition of a Solana account regardless of how it was retrieved and can represent both encoded and decoded accounts. It also introduces the concept of a `MaybeAccount` which represents a fetched account that may or may not exist on-chain whilst keeping track of its address in both cases.
|
|
20
|
+
|
|
21
|
+
Helper functions are provided for fetching, parsing and decoding accounts as well as asserting that an account exists.
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
// Fetch.
|
|
25
|
+
const myAddress = address('1234..5678');
|
|
26
|
+
const myAccount = fetchAccount(rpc, myAddress);
|
|
27
|
+
myAccount satisfies MaybeEncodedAccount<'1234..5678'>;
|
|
28
|
+
|
|
29
|
+
// Assert.
|
|
30
|
+
assertAccountExists(myAccount);
|
|
31
|
+
myAccount satisfies EncodedAccount<'1234..5678'>;
|
|
32
|
+
|
|
33
|
+
// Decode.
|
|
34
|
+
type MyAccountData = { name: string; age: number };
|
|
35
|
+
const myDecoder: Decoder<MyAccountData> = getStructDecoder([
|
|
36
|
+
['name', getStringDecoder({ size: getU32Decoder() })],
|
|
37
|
+
['age', getU32Decoder()],
|
|
38
|
+
]);
|
|
39
|
+
const myDecodedAccount = decodeAccount(myAccount, myDecoder);
|
|
40
|
+
myDecodedAccount satisfies Account<MyAccountData, '1234..5678'>;
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Types
|
|
44
|
+
|
|
45
|
+
### `BaseAccount`
|
|
46
|
+
|
|
47
|
+
The `BaseAccount` type defines the attributes common to all Solana accounts. Namely, it contains everything stored on-chain except the account data itself.
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
const BaseAccount: BaseAccount = {
|
|
51
|
+
executable: false,
|
|
52
|
+
lamports: lamports(1_000_000_000n),
|
|
53
|
+
programAddress: address('1111..1111'),
|
|
54
|
+
};
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
This package also exports a `BASE_ACCOUNT_SIZE` constant representing the size of the `BaseAccount` attributes in bytes.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
const myTotalAccountSize = myAccountDataSize + BASE_ACCOUNT_SIZE;
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### `Account` and `EncodedAccount`
|
|
64
|
+
|
|
65
|
+
The `Account` type contains all the information relevant to a Solana account. It contains the `BaseAccount` described above as well as the account data and the address of the account.
|
|
66
|
+
|
|
67
|
+
The account data can be represented as either a `Uint8Array` — meaning the account is encoded — or a custom data type — meaning the account is decoded.
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
// Encoded.
|
|
71
|
+
const myEncodedAccount: Account<Uint8Array, '1234..5678'> = {
|
|
72
|
+
address: address('1234..5678'),
|
|
73
|
+
data: new Uint8Array([1, 2, 3]),
|
|
74
|
+
executable: false,
|
|
75
|
+
lamports: lamports(1_000_000_000n),
|
|
76
|
+
programAddress: address('1111..1111'),
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
// Decoded.
|
|
80
|
+
type MyAccountData = { name: string; age: number };
|
|
81
|
+
const myDecodedAccount: Account<MyAccountData, '1234..5678'> = {
|
|
82
|
+
address: address('1234..5678'),
|
|
83
|
+
data: { name: 'Alice', age: 30 },
|
|
84
|
+
executable: false,
|
|
85
|
+
lamports: lamports(1_000_000_000n),
|
|
86
|
+
programAddress: address('1111..1111'),
|
|
87
|
+
};
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
The `EncodedAccount` type can also be used to represent an encoded account and is equivalent to an `Account` with a `Uint8Array` account data.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
myEncodedAccount satisfies EncodedAccount<'1234..5678'>;
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### `MaybeAccount` and `MaybeEncodedAccount`
|
|
97
|
+
|
|
98
|
+
The `MaybeAccount` type is a union type representing an account that may or may not exist on-chain. When the account exists, it is represented as an `Account` type with an additional `exists` attribute set to `true`. When it does not exist, it is represented by an object containing only the address of the account and an `exists` attribute set to `false`.
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
// Account exists.
|
|
102
|
+
const myExistingAccount: MaybeAccount<MyAccountData, '1234..5678'> = {
|
|
103
|
+
exists: true,
|
|
104
|
+
address: address('1234..5678'),
|
|
105
|
+
data: { name: 'Alice', age: 30 },
|
|
106
|
+
executable: false,
|
|
107
|
+
lamports: lamports(1_000_000_000n),
|
|
108
|
+
programAddress: address('1111..1111'),
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// Account does not exist.
|
|
112
|
+
const myMissingAccount: MaybeAccount<MyAccountData, '8765..4321'> = {
|
|
113
|
+
exists: false,
|
|
114
|
+
address: address('8765..4321'),
|
|
115
|
+
};
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Similarly to the `Account` type, the `MaybeAccount` type can be used to represent an encoded account by using the `Uint8Array` data type or by using the `MaybeEncodedAccount` helper type.
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
// Encoded account exists.
|
|
122
|
+
const myExistingAccount: MaybeEncodedAccount<'1234..5678'> = {
|
|
123
|
+
exists: true,
|
|
124
|
+
address: address('1234..5678'),
|
|
125
|
+
data: new Uint8Array([1, 2, 3]),
|
|
126
|
+
// ...
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
// Encoded account does not exist.
|
|
130
|
+
const myMissingAccount: MaybeEncodedAccount<'8765..4321'> = {
|
|
131
|
+
exists: false,
|
|
132
|
+
address: address('8765..4321'),
|
|
133
|
+
};
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Functions
|
|
137
|
+
|
|
138
|
+
### `assertAccountExists()`
|
|
139
|
+
|
|
140
|
+
Given a `MaybeAccount`, this function asserts that the account exists and allows it to be used as an `Account` type going forward.
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
const myAccount: MaybeEncodedAccount<'1234..5678'>;
|
|
144
|
+
assertAccountExists(myAccount);
|
|
145
|
+
|
|
146
|
+
// Now we can use myAccount as an Account.
|
|
147
|
+
myAccount satisfies EncodedAccount<'1234..5678'>;
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### `assertAccountsExist()`
|
|
151
|
+
|
|
152
|
+
Given an array of `MaybeAccount`s, this function asserts that all the accounts
|
|
153
|
+
exist and allows them to be used as an array of `Account`s going forward.
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
const myAccounts: MaybeEncodedAccount<Address>[];
|
|
157
|
+
assertAccountsExist(myAccounts);
|
|
158
|
+
|
|
159
|
+
// Now we can use them as an array of accounts
|
|
160
|
+
for (const a of myAccounts) {
|
|
161
|
+
a satisfies EncodedAccount<Address>;
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
### `parseBase64RpcAccount()`
|
|
166
|
+
|
|
167
|
+
This function parses a base64-encoded account provided by the RPC client into an `EncodedAccount` type or a `MaybeEncodedAccount` type if the raw data can be set to `null`.
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
const myAddress = address('1234..5678');
|
|
171
|
+
const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base64' }).send();
|
|
172
|
+
const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase64RpcAccount(myRpcAccount);
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### `parseBase58RpcAccount()`
|
|
176
|
+
|
|
177
|
+
This function parses a base58-encoded account provided by the RPC client into an `EncodedAccount` type or a `MaybeEncodedAccount` type if the raw data can be set to `null`.
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
const myAddress = address('1234..5678');
|
|
181
|
+
const myRpcAccount = await rpc.getAccountInfo(myAddress, { encoding: 'base58' }).send();
|
|
182
|
+
const myAccount: MaybeEncodedAccount<'1234..5678'> = parseBase58RpcAccount(myRpcAccount);
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### `parseJsonRpcAccount()`
|
|
186
|
+
|
|
187
|
+
This function parses an arbitrary `jsonParsed` account provided by the RPC client into an `Account` type or a `MaybeAccount` type if the raw data can be set to `null`. The expected data type should be explicitly provided as the first type parameter.
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
const myAccount: Account<MyData> = parseJsonRpcAccount<MyData>(myJsonRpcAccount);
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
### `fetchEncodedAccount()`
|
|
194
|
+
|
|
195
|
+
This function fetches a `MaybeEncodedAccount` from the provided RPC client and address. It uses the `getAccountInfo` RPC method under the hood with base64 encoding and an additional configuration object can be provided to customize the behavior of the RPC call.
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
const myAddress = address('1234..5678');
|
|
199
|
+
const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress);
|
|
200
|
+
|
|
201
|
+
// With custom configuration.
|
|
202
|
+
const myAccount: MaybeEncodedAccount<'1234..5678'> = await fetchEncodedAccount(rpc, myAddress, {
|
|
203
|
+
abortSignal: myAbortController.signal,
|
|
204
|
+
commitment: 'confirmed',
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### `fetchEncodedAccounts()`
|
|
209
|
+
|
|
210
|
+
This function fetches an array of `MaybeEncodedAccount` from the provided RPC client and an array of addresses. It uses the `getMultipleAccounts` RPC method under the hood with base64 encodings and an additional configuration object can be provided to customize the behavior of the RPC call.
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
const myAddressA = address('1234..5678');
|
|
214
|
+
const myAddressB = address('8765..4321');
|
|
215
|
+
const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB]);
|
|
216
|
+
myAccountA satisfies MaybeEncodedAccount<'1234..5678'>;
|
|
217
|
+
myAccountB satisfies MaybeEncodedAccount<'8765..4321'>;
|
|
218
|
+
|
|
219
|
+
// With custom configuration.
|
|
220
|
+
const [myAccountA, myAccountB] = await fetchEncodedAccounts(rpc, [myAddressA, myAddressB], {
|
|
221
|
+
abortSignal: myAbortController.signal,
|
|
222
|
+
commitment: 'confirmed',
|
|
223
|
+
});
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
### `fetchJsonParsedAccount()`
|
|
227
|
+
|
|
228
|
+
This function fetches a `MaybeAccount` from the provided RPC client and address by using `getAccountInfo` under the hood with the `jsonParsed` encoding. It may also return a `MaybeEncodedAccount` if the RPC client does not know how to parse the account at the requested address. In any case, the expected data type should be explicitly provided as the first type parameter.
|
|
229
|
+
|
|
230
|
+
```ts
|
|
231
|
+
type TokenData = { mint: Address; owner: Address };
|
|
232
|
+
const myAccount = await fetchJsonParsedAccount<TokenData>(rpc, myAddress);
|
|
233
|
+
myAccount satisfies MaybeAccount<TokenData> | MaybeEncodedAccount;
|
|
234
|
+
|
|
235
|
+
// With custom configuration.
|
|
236
|
+
const myAccount = await fetchJsonParsedAccount<TokenData>(rpc, myAddress, {
|
|
237
|
+
abortSignal: myAbortController.signal,
|
|
238
|
+
commitment: 'confirmed',
|
|
239
|
+
});
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
### `fetchJsonParsedAccounts()`
|
|
243
|
+
|
|
244
|
+
Similarly to the `fetchJsonParsedAccount` method, this method fetches an array of `MaybeAccount` from a provided RPC client and an array of addresses. It uses the `getMultipleAccounts` RPC method under the hood with the `jsonParsed` encoding. It may also return a `MaybeEncodedAccount` instead of the expected `MaybeAccount` if the RPC client does not know how to parse some of the requested accounts. In any case, the array of expected data types should be explicitly provided as the first type parameter.
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
type TokenData = { mint: Address; owner: Address };
|
|
248
|
+
type MintData = { supply: bigint };
|
|
249
|
+
const [myAccountA, myAccountB] = await fetchJsonParsedAccounts<[TokenData, MintData]>(rpc, [myAddressA, myAddressB]);
|
|
250
|
+
myAccountA satisfies MaybeAccount<TokenData> | MaybeEncodedAccount;
|
|
251
|
+
myAccountB satisfies MaybeAccount<MintData> | MaybeEncodedAccount;
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
### `decodeAccount()`
|
|
255
|
+
|
|
256
|
+
This function transforms an `EncodedAccount` into an `Account` (or a `MaybeEncodedAccount` into a `MaybeAccount`) by decoding the account data using the provided `Decoder` instance.
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
type MyAccountData = { name: string; age: number };
|
|
260
|
+
|
|
261
|
+
const myAccount: EncodedAccount<'1234..5678'>;
|
|
262
|
+
const myDecoder: Decoder<MyAccountData> = getStructDecoder([
|
|
263
|
+
['name', getStringDecoder({ size: getU32Decoder() })],
|
|
264
|
+
['age', getU32Decoder()],
|
|
265
|
+
]);
|
|
266
|
+
|
|
267
|
+
const myDecodedAccount = decodeAccount(myAccount, myDecoder);
|
|
268
|
+
myDecodedAccount satisfies Account<MyAccountData, '1234..5678'>;
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
### `assertAccountDecoded()`
|
|
272
|
+
|
|
273
|
+
This function asserts that an account stores decoded data, ie not a Uint8Array. Note that it does not check the shape of the data matches the decoded type, only that it is not a Uint8Array.
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
type MyAccountData = { name: string; age: number };
|
|
277
|
+
|
|
278
|
+
const myAccount: Account<MyAccountData | Uint8Array, '1234..5678'>;
|
|
279
|
+
assertAccountDecoded(myAccount);
|
|
280
|
+
|
|
281
|
+
// now the account data can be used as MyAccountData
|
|
282
|
+
account.data satisfies MyAccountData;
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
This is particularly useful for narrowing the result of fetching a JSON parsed account.
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
```ts
|
|
289
|
+
const account: MaybeAccount<MockData | Uint8Array> = await fetchJsonParsedAccount<MockData>(
|
|
290
|
+
rpc,
|
|
291
|
+
'1234..5678' as Address,
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
assertAccountDecoded(account);
|
|
295
|
+
// now we have a MaybeAccount<MockData>
|
|
296
|
+
account satisfies MaybeAccount<MockData>
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
### `assertAccountsDecoded`
|
|
300
|
+
|
|
301
|
+
This function asserts that all input accounts store decoded data, ie not a Uint8Array. As with `assertAccountDecoded` it does not check the shape of the data matches the decoded type, only that it is not a Uint8Array.
|
|
302
|
+
|
|
303
|
+
```ts
|
|
304
|
+
type MyAccountData = { name: string; age: number };
|
|
305
|
+
|
|
306
|
+
const myAccounts: Account<MyAccountData | Uint8Array, Address>[];
|
|
307
|
+
assertAccountsDecoded(myAccounts);
|
|
308
|
+
|
|
309
|
+
// now the account data can be used as MyAccountData
|
|
310
|
+
for(const a of account) {
|
|
311
|
+
account.data satisfies MyAccountData;
|
|
312
|
+
}
|
|
313
|
+
```
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var codecsStrings = require('@solana/codecs-strings');
|
|
4
|
+
|
|
5
|
+
// src/account.ts
|
|
6
|
+
var BASE_ACCOUNT_SIZE = 128;
|
|
7
|
+
|
|
8
|
+
// src/decode-account.ts
|
|
9
|
+
function decodeAccount(encodedAccount, decoder) {
|
|
10
|
+
try {
|
|
11
|
+
if ("exists" in encodedAccount && !encodedAccount.exists) {
|
|
12
|
+
return encodedAccount;
|
|
13
|
+
}
|
|
14
|
+
return Object.freeze({ ...encodedAccount, data: decoder.decode(encodedAccount.data) });
|
|
15
|
+
} catch (error) {
|
|
16
|
+
const newError = new Error(`Failed to decode account [${encodedAccount.address}].`);
|
|
17
|
+
newError.cause = error;
|
|
18
|
+
throw newError;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function accountExists(account) {
|
|
22
|
+
return !("exists" in account) || "exists" in account && account.exists;
|
|
23
|
+
}
|
|
24
|
+
function assertAccountDecoded(account) {
|
|
25
|
+
if (accountExists(account) && account.data instanceof Uint8Array) {
|
|
26
|
+
throw new Error(`Expected account [${account.address}] to be decoded.`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function assertAccountsDecoded(accounts) {
|
|
30
|
+
const encoded = accounts.filter((a) => accountExists(a) && a.data instanceof Uint8Array);
|
|
31
|
+
if (encoded.length > 0) {
|
|
32
|
+
const encodedAddresses = encoded.map((a) => a.address).join(", ");
|
|
33
|
+
throw new Error(`Expected accounts [${encodedAddresses}] to be decoded.`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function parseBase64RpcAccount(address, rpcAccount) {
|
|
37
|
+
if (!rpcAccount)
|
|
38
|
+
return Object.freeze({ address, exists: false });
|
|
39
|
+
const data = codecsStrings.getBase64Encoder().encode(rpcAccount.data[0]);
|
|
40
|
+
return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });
|
|
41
|
+
}
|
|
42
|
+
function parseBase58RpcAccount(address, rpcAccount) {
|
|
43
|
+
if (!rpcAccount)
|
|
44
|
+
return Object.freeze({ address, exists: false });
|
|
45
|
+
const data = codecsStrings.getBase58Encoder().encode(typeof rpcAccount.data === "string" ? rpcAccount.data : rpcAccount.data[0]);
|
|
46
|
+
return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });
|
|
47
|
+
}
|
|
48
|
+
function parseJsonRpcAccount(address, rpcAccount) {
|
|
49
|
+
if (!rpcAccount)
|
|
50
|
+
return Object.freeze({ address, exists: false });
|
|
51
|
+
const data = rpcAccount.data.parsed.info;
|
|
52
|
+
return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });
|
|
53
|
+
}
|
|
54
|
+
function parseBaseAccount(rpcAccount) {
|
|
55
|
+
return Object.freeze({
|
|
56
|
+
executable: rpcAccount.executable,
|
|
57
|
+
lamports: rpcAccount.lamports,
|
|
58
|
+
programAddress: rpcAccount.owner
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/fetch-account.ts
|
|
63
|
+
async function fetchEncodedAccount(rpc, address, config = {}) {
|
|
64
|
+
const { abortSignal, ...rpcConfig } = config;
|
|
65
|
+
const response = await rpc.getAccountInfo(address, { ...rpcConfig, encoding: "base64" }).send({ abortSignal });
|
|
66
|
+
return parseBase64RpcAccount(address, response.value);
|
|
67
|
+
}
|
|
68
|
+
async function fetchJsonParsedAccount(rpc, address, config = {}) {
|
|
69
|
+
const { abortSignal, ...rpcConfig } = config;
|
|
70
|
+
const { value: account } = await rpc.getAccountInfo(address, { ...rpcConfig, encoding: "jsonParsed" }).send({ abortSignal });
|
|
71
|
+
return !!account && typeof account === "object" && "parsed" in account.data ? parseJsonRpcAccount(address, account) : parseBase64RpcAccount(address, account);
|
|
72
|
+
}
|
|
73
|
+
async function fetchEncodedAccounts(rpc, addresses, config = {}) {
|
|
74
|
+
const { abortSignal, ...rpcConfig } = config;
|
|
75
|
+
const response = await rpc.getMultipleAccounts(addresses, { ...rpcConfig, encoding: "base64" }).send({ abortSignal });
|
|
76
|
+
return response.value.map((account, index) => parseBase64RpcAccount(addresses[index], account));
|
|
77
|
+
}
|
|
78
|
+
async function fetchJsonParsedAccounts(rpc, addresses, config = {}) {
|
|
79
|
+
const { abortSignal, ...rpcConfig } = config;
|
|
80
|
+
const response = await rpc.getMultipleAccounts(addresses, { ...rpcConfig, encoding: "jsonParsed" }).send({ abortSignal });
|
|
81
|
+
return response.value.map((account, index) => {
|
|
82
|
+
return !!account && typeof account === "object" && "parsed" in account.data ? parseJsonRpcAccount(addresses[index], account) : parseBase64RpcAccount(addresses[index], account);
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// src/maybe-account.ts
|
|
87
|
+
function assertAccountExists(account) {
|
|
88
|
+
if (!account.exists) {
|
|
89
|
+
throw new Error(`Expected account [${account.address}] to exist.`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function assertAccountsExist(accounts) {
|
|
93
|
+
const missingAccounts = accounts.filter((a) => !a.exists);
|
|
94
|
+
if (missingAccounts.length > 0) {
|
|
95
|
+
const missingAddresses = missingAccounts.map((a) => a.address);
|
|
96
|
+
throw new Error(`Expected accounts [${missingAddresses.join(", ")}] to exist.`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
exports.BASE_ACCOUNT_SIZE = BASE_ACCOUNT_SIZE;
|
|
101
|
+
exports.assertAccountDecoded = assertAccountDecoded;
|
|
102
|
+
exports.assertAccountExists = assertAccountExists;
|
|
103
|
+
exports.assertAccountsDecoded = assertAccountsDecoded;
|
|
104
|
+
exports.assertAccountsExist = assertAccountsExist;
|
|
105
|
+
exports.decodeAccount = decodeAccount;
|
|
106
|
+
exports.fetchEncodedAccount = fetchEncodedAccount;
|
|
107
|
+
exports.fetchEncodedAccounts = fetchEncodedAccounts;
|
|
108
|
+
exports.fetchJsonParsedAccount = fetchJsonParsedAccount;
|
|
109
|
+
exports.fetchJsonParsedAccounts = fetchJsonParsedAccounts;
|
|
110
|
+
exports.parseBase58RpcAccount = parseBase58RpcAccount;
|
|
111
|
+
exports.parseBase64RpcAccount = parseBase64RpcAccount;
|
|
112
|
+
exports.parseJsonRpcAccount = parseJsonRpcAccount;
|
|
113
|
+
//# sourceMappingURL=out.js.map
|
|
114
|
+
//# sourceMappingURL=index.browser.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/account.ts","../src/decode-account.ts","../src/parse-account.ts","../src/fetch-account.ts","../src/maybe-account.ts"],"names":[],"mappings":";AAIO,IAAM,oBAAoB;;;ACU1B,SAAS,cACZ,gBACA,SACwD;AACxD,MAAI;AACA,QAAI,YAAY,kBAAkB,CAAC,eAAe,QAAQ;AACtD,aAAO;AAAA,IACX;AACA,WAAO,OAAO,OAAO,EAAE,GAAG,gBAAgB,MAAM,QAAQ,O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,CAAC,SAAS,UAAU,sBAAsB,UAAU,KAAK,GAAG,OAAO,CAAC;AAGlG;AAGA,eAAsB,wBAMpB,KAAkC,WAA8B,SAA8B,CAAC,GAAG;AAChG,QAAM,EAAE,aAAa,GAAG,UAAU,IAAI;AACtC,QAAM,WAAW,MAAM,IAClB,oBAAoB,WAAW,EAAE,GAAG,WAAW,UAAU,aAAa,CAAC,EACvE,KAAK,EAAE,YAAY,CAAC;AACzB,SAAO,SAAS,MAAM,IAAI,CAAC,SAAS,UAAU;AAC1C,WAAO,CAAC,CAAC,WAAW,OAAO,YAAY,YAAY,YAAY,QAAQ,OACjE,oBAAoB,UAAU,KAAK,GAAG,OAAoD,IAC1F,sBAAsB,UAAU,KAAK,GAAG,OAAsD;AAAA,EACxG,CAAC;AASL;;;AC3EO,SAAS,oBACZ,SAC8D;AAC9D,MAAI,CAAC,QAAQ,QAAQ;AAEjB,UAAM,IAAI,MAAM,qBAAqB,QAAQ,OAAO,aAAa;AAAA,EACrE;AACJ;AAGO,SAAS,oBACZ,UACmE;AACnE,QAAM,kBAAkB,SAAS,OAAO,OAAK,CAAC,EAAE,MAAM;AACtD,MAAI,gBAAgB,SAAS,GAAG;AAC5B,UAAM,mBAAmB,gBAAgB,IAAI,OAAK,EAAE,OAAO;AAE3D,UAAM,IAAI,MAAM,sBAAsB,iBAAiB,KAAK,IAAI,CAAC,aAAa;AAAA,EAClF;AACJ","sourcesContent":["import type { Address } from '@solana/addresses';\nimport type { LamportsUnsafeBeyond2Pow53Minus1 } from '@solana/rpc-types';\n\n/** The amount of bytes required to store the base account information without its data. */\nexport const BASE_ACCOUNT_SIZE = 128;\n\n/** Describe the generic account details applicable to every account. */\nexport type BaseAccount = {\n readonly programAddress: Address;\n readonly executable: boolean;\n readonly lamports: LamportsUnsafeBeyond2Pow53Minus1;\n};\n\n/** Defines a Solana account with its generic details and parsed or encoded data. */\nexport type Account<TData extends object | Uint8Array, TAddress extends string = string> = BaseAccount & {\n readonly address: Address<TAddress>;\n readonly data: TData;\n};\n\n/** Defines a Solana account with its generic details and encoded data. */\nexport type EncodedAccount<TAddress extends string = string> = Account<Uint8Array, TAddress>;\n","import type { Decoder } from '@solana/codecs-core';\n\nimport type { Account, EncodedAccount } from './account';\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\n\n/** Decodes the data of a given account using the provided decoder. */\nexport function decodeAccount<TData extends object, TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>,\n decoder: Decoder<TData>,\n): Account<TData, TAddress>;\nexport function decodeAccount<TData extends object, TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>,\n decoder: Decoder<TData>,\n): MaybeAccount<TData, TAddress>;\nexport function decodeAccount<TData extends object, TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>,\n decoder: Decoder<TData>,\n): Account<TData, TAddress> | MaybeAccount<TData, TAddress> {\n try {\n if ('exists' in encodedAccount && !encodedAccount.exists) {\n return encodedAccount;\n }\n return Object.freeze({ ...encodedAccount, data: decoder.decode(encodedAccount.data) });\n } catch (error) {\n // TODO: Coded error.\n const newError = new Error(`Failed to decode account [${encodedAccount.address}].`);\n newError.cause = error;\n throw newError;\n }\n}\n\nfunction accountExists<TData extends object>(account: Account<TData> | MaybeAccount<TData>): account is Account<TData> {\n return !('exists' in account) || ('exists' in account && account.exists);\n}\n\n/** Asserts that an account has been decoded. */\nexport function assertAccountDecoded<TData extends object, TAddress extends string = string>(\n account: Account<TData | Uint8Array, TAddress>,\n): asserts account is Account<TData, TAddress>;\nexport function assertAccountDecoded<TData extends object, TAddress extends string = string>(\n account: MaybeAccount<TData | Uint8Array, TAddress>,\n): asserts account is MaybeAccount<TData, TAddress>;\nexport function assertAccountDecoded<TData extends object, TAddress extends string = string>(\n account: Account<TData | Uint8Array, TAddress> | MaybeAccount<TData | Uint8Array, TAddress>,\n): asserts account is Account<TData, TAddress> | MaybeAccount<TData, TAddress> {\n if (accountExists(account) && account.data instanceof Uint8Array) {\n // TODO: coded error.\n throw new Error(`Expected account [${account.address}] to be decoded.`);\n }\n}\n\n/** Asserts that all accounts have been decoded. */\nexport function assertAccountsDecoded<TData extends object, TAddress extends string = string>(\n accounts: Account<TData | Uint8Array, TAddress>[],\n): asserts accounts is Account<TData, TAddress>[];\nexport function assertAccountsDecoded<TData extends object, TAddress extends string = string>(\n accounts: MaybeAccount<TData | Uint8Array, TAddress>[],\n): asserts accounts is MaybeAccount<TData, TAddress>[];\nexport function assertAccountsDecoded<TData extends object, TAddress extends string = string>(\n accounts: (Account<TData | Uint8Array, TAddress> | MaybeAccount<TData | Uint8Array, TAddress>)[],\n): asserts accounts is (Account<TData, TAddress> | MaybeAccount<TData, TAddress>)[] {\n const encoded = accounts.filter(a => accountExists(a) && a.data instanceof Uint8Array);\n if (encoded.length > 0) {\n const encodedAddresses = encoded.map(a => a.address).join(', ');\n // TODO: Coded error.\n throw new Error(`Expected accounts [${encodedAddresses}] to be decoded.`);\n }\n}\n","import type { Address } from '@solana/addresses';\nimport { getBase58Encoder, getBase64Encoder } from '@solana/codecs-strings';\n\nimport type { Account, BaseAccount, EncodedAccount } from './account';\nimport { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport type {\n AccountInfoBase,\n AccountInfoWithBase58Bytes,\n AccountInfoWithBase58EncodedData,\n AccountInfoWithBase64EncodedData,\n JsonParsedDataResponse,\n} from './rpc-api';\n\ntype Base64EncodedRpcAccount = AccountInfoBase & AccountInfoWithBase64EncodedData;\n\n/** Parse an account object received from a base64-encoded RPC call into an EncodedAccount or MaybeEncodedAccount type. */\nexport function parseBase64RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base64EncodedRpcAccount,\n): EncodedAccount<TAddress>;\nexport function parseBase64RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base64EncodedRpcAccount | null,\n): MaybeEncodedAccount<TAddress>;\nexport function parseBase64RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base64EncodedRpcAccount | null,\n): EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase64Encoder().encode(rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype Base58EncodedRpcAccount = AccountInfoBase & (AccountInfoWithBase58Bytes | AccountInfoWithBase58EncodedData);\n\n/** Parse an account object received from a base58-encoded RPC call into an EncodedAccount or MaybeEncodedAccount type. */\nexport function parseBase58RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base58EncodedRpcAccount,\n): EncodedAccount<TAddress>;\nexport function parseBase58RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base58EncodedRpcAccount | null,\n): MaybeEncodedAccount<TAddress>;\nexport function parseBase58RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base58EncodedRpcAccount | null,\n): EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase58Encoder().encode(typeof rpcAccount.data === 'string' ? rpcAccount.data : rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype JsonParsedRpcAccount = AccountInfoBase & { readonly data: JsonParsedDataResponse<unknown> };\n\n/** Parse an account object received from a json-parsed RPC call into an Account or MaybeAccount type. */\nexport function parseJsonRpcAccount<TData extends object, TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: JsonParsedRpcAccount,\n): Account<TData, TAddress>;\nexport function parseJsonRpcAccount<TData extends object, TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: JsonParsedRpcAccount | null,\n): MaybeAccount<TData, TAddress>;\nexport function parseJsonRpcAccount<TData extends object, TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: JsonParsedRpcAccount | null,\n): Account<TData, TAddress> | MaybeAccount<TData, TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = rpcAccount.data.parsed.info as TData;\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\nfunction parseBaseAccount(rpcAccount: AccountInfoBase): BaseAccount {\n return Object.freeze({\n executable: rpcAccount.executable,\n lamports: rpcAccount.lamports,\n programAddress: rpcAccount.owner,\n });\n}\n","import type { Address } from '@solana/addresses';\nimport type { Commitment, Rpc, Slot } from '@solana/rpc-types';\n\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport { parseBase64RpcAccount, parseJsonRpcAccount } from './parse-account';\nimport type { GetAccountInfoApi, GetMultipleAccountsApi } from './rpc-api';\n\n/** Optional configuration for fetching a singular account. */\nexport type FetchAccountConfig = {\n commitment?: Commitment;\n minContextSlot?: Slot;\n abortSignal?: AbortSignal;\n};\n\n/** Fetch a base64-encoded account that may or may not exist using an RPC client. */\nexport async function fetchEncodedAccount<TAddress extends string = string>(\n rpc: Rpc<GetAccountInfoApi>,\n address: Address<TAddress>,\n config: FetchAccountConfig = {},\n): Promise<MaybeEncodedAccount<TAddress>> {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc.getAccountInfo(address, { ...rpcConfig, encoding: 'base64' }).send({ abortSignal });\n return parseBase64RpcAccount(address, response.value);\n}\n\n/** Fetch a json-parsed account that may or may not exist using an RPC client. */\nexport async function fetchJsonParsedAccount<TData extends object, TAddress extends string = string>(\n rpc: Rpc<GetAccountInfoApi>,\n address: Address<TAddress>,\n config: FetchAccountConfig = {},\n): Promise<MaybeAccount<TData, TAddress> | MaybeEncodedAccount<TAddress>> {\n const { abortSignal, ...rpcConfig } = config;\n const { value: account } = await rpc\n .getAccountInfo(address, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount<TData, TAddress>(address, account as Parameters<typeof parseJsonRpcAccount>[1])\n : parseBase64RpcAccount<TAddress>(address, account as Parameters<typeof parseBase64RpcAccount>[1]);\n}\n\n/** Optional configuration for fetching multiple accounts. */\nexport type FetchAccountsConfig = {\n commitment?: Commitment;\n minContextSlot?: Slot;\n abortSignal?: AbortSignal;\n};\n\n/** Fetch multiple base64-encoded accounts that may or may not exist using an RPC client. */\nexport async function fetchEncodedAccounts<\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address<TAddresses[P]> } = {\n [P in keyof TAddresses]: Address<TAddresses[P]>;\n },\n>(rpc: Rpc<GetMultipleAccountsApi>, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'base64' })\n .send({ abortSignal });\n return response.value.map((account, index) => parseBase64RpcAccount(addresses[index], account)) as {\n [P in keyof TAddresses]: MaybeEncodedAccount<TAddresses[P]>;\n };\n}\n\n/** Fetch multiple json-parsed accounts that may or may not exist using an RPC client. */\nexport async function fetchJsonParsedAccounts<\n TData extends object[],\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address<TAddresses[P]> } = {\n [P in keyof TAddresses]: Address<TAddresses[P]>;\n },\n>(rpc: Rpc<GetMultipleAccountsApi>, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return response.value.map((account, index) => {\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount(addresses[index], account as Parameters<typeof parseJsonRpcAccount>[1])\n : parseBase64RpcAccount(addresses[index], account as Parameters<typeof parseBase64RpcAccount>[1]);\n }) as {\n [P in keyof TData]:\n | MaybeAccount<TData[P], TAddresses[P & keyof TAddresses]>\n | MaybeEncodedAccount<TAddresses[P & keyof TAddresses]>;\n } & {\n [P in keyof TAddresses]:\n | MaybeAccount<TData[P & keyof TData], TAddresses[P]>\n | MaybeEncodedAccount<TAddresses[P]>;\n };\n}\n","import { Address } from '@solana/addresses';\n\nimport { Account } from './account';\n\n/** Defines a Solana account that may or may not exist after having tried to fetch it. */\nexport type MaybeAccount<TData extends object | Uint8Array, TAddress extends string = string> =\n | ({ readonly exists: true } & Account<TData, TAddress>)\n | { readonly exists: false; readonly address: Address<TAddress> };\n\n/** Defines a Solana account with encoded data that may or may not exist after having tried to fetch it. */\nexport type MaybeEncodedAccount<TAddress extends string = string> = MaybeAccount<Uint8Array, TAddress>;\n\n/** Asserts that an account that may or may not exists, actually exists. */\nexport function assertAccountExists<TData extends object | Uint8Array, TAddress extends string = string>(\n account: MaybeAccount<TData, TAddress>,\n): asserts account is Account<TData, TAddress> & { exists: true } {\n if (!account.exists) {\n // TODO: Coded error.\n throw new Error(`Expected account [${account.address}] to exist.`);\n }\n}\n\n/** Asserts that all accounts that may or may not exist, actually all exist. */\nexport function assertAccountsExist<TData extends object | Uint8Array, TAddress extends string = string>(\n accounts: MaybeAccount<TData, TAddress>[],\n): asserts accounts is (Account<TData, TAddress> & { exists: true })[] {\n const missingAccounts = accounts.filter(a => !a.exists);\n if (missingAccounts.length > 0) {\n const missingAddresses = missingAccounts.map(a => a.address);\n // TODO: Coded error.\n throw new Error(`Expected accounts [${missingAddresses.join(', ')}] to exist.`);\n }\n}\n"]}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { getBase64Encoder, getBase58Encoder } from '@solana/codecs-strings';
|
|
2
|
+
|
|
3
|
+
// src/account.ts
|
|
4
|
+
var BASE_ACCOUNT_SIZE = 128;
|
|
5
|
+
|
|
6
|
+
// src/decode-account.ts
|
|
7
|
+
function decodeAccount(encodedAccount, decoder) {
|
|
8
|
+
try {
|
|
9
|
+
if ("exists" in encodedAccount && !encodedAccount.exists) {
|
|
10
|
+
return encodedAccount;
|
|
11
|
+
}
|
|
12
|
+
return Object.freeze({ ...encodedAccount, data: decoder.decode(encodedAccount.data) });
|
|
13
|
+
} catch (error) {
|
|
14
|
+
const newError = new Error(`Failed to decode account [${encodedAccount.address}].`);
|
|
15
|
+
newError.cause = error;
|
|
16
|
+
throw newError;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function accountExists(account) {
|
|
20
|
+
return !("exists" in account) || "exists" in account && account.exists;
|
|
21
|
+
}
|
|
22
|
+
function assertAccountDecoded(account) {
|
|
23
|
+
if (accountExists(account) && account.data instanceof Uint8Array) {
|
|
24
|
+
throw new Error(`Expected account [${account.address}] to be decoded.`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function assertAccountsDecoded(accounts) {
|
|
28
|
+
const encoded = accounts.filter((a) => accountExists(a) && a.data instanceof Uint8Array);
|
|
29
|
+
if (encoded.length > 0) {
|
|
30
|
+
const encodedAddresses = encoded.map((a) => a.address).join(", ");
|
|
31
|
+
throw new Error(`Expected accounts [${encodedAddresses}] to be decoded.`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function parseBase64RpcAccount(address, rpcAccount) {
|
|
35
|
+
if (!rpcAccount)
|
|
36
|
+
return Object.freeze({ address, exists: false });
|
|
37
|
+
const data = getBase64Encoder().encode(rpcAccount.data[0]);
|
|
38
|
+
return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });
|
|
39
|
+
}
|
|
40
|
+
function parseBase58RpcAccount(address, rpcAccount) {
|
|
41
|
+
if (!rpcAccount)
|
|
42
|
+
return Object.freeze({ address, exists: false });
|
|
43
|
+
const data = getBase58Encoder().encode(typeof rpcAccount.data === "string" ? rpcAccount.data : rpcAccount.data[0]);
|
|
44
|
+
return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });
|
|
45
|
+
}
|
|
46
|
+
function parseJsonRpcAccount(address, rpcAccount) {
|
|
47
|
+
if (!rpcAccount)
|
|
48
|
+
return Object.freeze({ address, exists: false });
|
|
49
|
+
const data = rpcAccount.data.parsed.info;
|
|
50
|
+
return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });
|
|
51
|
+
}
|
|
52
|
+
function parseBaseAccount(rpcAccount) {
|
|
53
|
+
return Object.freeze({
|
|
54
|
+
executable: rpcAccount.executable,
|
|
55
|
+
lamports: rpcAccount.lamports,
|
|
56
|
+
programAddress: rpcAccount.owner
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/fetch-account.ts
|
|
61
|
+
async function fetchEncodedAccount(rpc, address, config = {}) {
|
|
62
|
+
const { abortSignal, ...rpcConfig } = config;
|
|
63
|
+
const response = await rpc.getAccountInfo(address, { ...rpcConfig, encoding: "base64" }).send({ abortSignal });
|
|
64
|
+
return parseBase64RpcAccount(address, response.value);
|
|
65
|
+
}
|
|
66
|
+
async function fetchJsonParsedAccount(rpc, address, config = {}) {
|
|
67
|
+
const { abortSignal, ...rpcConfig } = config;
|
|
68
|
+
const { value: account } = await rpc.getAccountInfo(address, { ...rpcConfig, encoding: "jsonParsed" }).send({ abortSignal });
|
|
69
|
+
return !!account && typeof account === "object" && "parsed" in account.data ? parseJsonRpcAccount(address, account) : parseBase64RpcAccount(address, account);
|
|
70
|
+
}
|
|
71
|
+
async function fetchEncodedAccounts(rpc, addresses, config = {}) {
|
|
72
|
+
const { abortSignal, ...rpcConfig } = config;
|
|
73
|
+
const response = await rpc.getMultipleAccounts(addresses, { ...rpcConfig, encoding: "base64" }).send({ abortSignal });
|
|
74
|
+
return response.value.map((account, index) => parseBase64RpcAccount(addresses[index], account));
|
|
75
|
+
}
|
|
76
|
+
async function fetchJsonParsedAccounts(rpc, addresses, config = {}) {
|
|
77
|
+
const { abortSignal, ...rpcConfig } = config;
|
|
78
|
+
const response = await rpc.getMultipleAccounts(addresses, { ...rpcConfig, encoding: "jsonParsed" }).send({ abortSignal });
|
|
79
|
+
return response.value.map((account, index) => {
|
|
80
|
+
return !!account && typeof account === "object" && "parsed" in account.data ? parseJsonRpcAccount(addresses[index], account) : parseBase64RpcAccount(addresses[index], account);
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// src/maybe-account.ts
|
|
85
|
+
function assertAccountExists(account) {
|
|
86
|
+
if (!account.exists) {
|
|
87
|
+
throw new Error(`Expected account [${account.address}] to exist.`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function assertAccountsExist(accounts) {
|
|
91
|
+
const missingAccounts = accounts.filter((a) => !a.exists);
|
|
92
|
+
if (missingAccounts.length > 0) {
|
|
93
|
+
const missingAddresses = missingAccounts.map((a) => a.address);
|
|
94
|
+
throw new Error(`Expected accounts [${missingAddresses.join(", ")}] to exist.`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export { BASE_ACCOUNT_SIZE, assertAccountDecoded, assertAccountExists, assertAccountsDecoded, assertAccountsExist, decodeAccount, fetchEncodedAccount, fetchEncodedAccounts, fetchJsonParsedAccount, fetchJsonParsedAccounts, parseBase58RpcAccount, parseBase64RpcAccount, parseJsonRpcAccount };
|
|
99
|
+
//# sourceMappingURL=out.js.map
|
|
100
|
+
//# sourceMappingURL=index.browser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/account.ts","../src/decode-account.ts","../src/parse-account.ts","../src/fetch-account.ts","../src/maybe-account.ts"],"names":[],"mappings":";AAIO,IAAM,oBAAoB;;;ACU1B,SAAS,cACZ,gBACA,SACwD;AACxD,MAAI;AACA,QAAI,YAAY,kBAAkB,CAAC,eAAe,QAAQ;AACtD,aAAO;AAAA,IACX;AACA,WAAO,OAAO,OAAO,EAAE,GAAG,gBAAgB,MAAM,QAAQ,OAAO,eAAe,IAAI,EAAE,CAAC;AAAA,EACzF,SAAS,OAAO;AAEZ,UAAM,WAAW,IAAI,MAAM,6BAA6B,eAAe,OAAO,IAAI;AAClF,aAAS,QAAQ;AACjB,UAAM;AAAA,EACV;AACJ;AAEA,SAAS,cAAoC,SAA0E;AACn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ClB,oBAAoB,WAAW,EAAE,GAAG,WAAW,UAAU,aAAa,CAAC,EACvE,KAAK,EAAE,YAAY,CAAC;AACzB,SAAO,SAAS,MAAM,IAAI,CAAC,SAAS,UAAU;AAC1C,WAAO,CAAC,CAAC,WAAW,OAAO,YAAY,YAAY,YAAY,QAAQ,OACjE,oBAAoB,UAAU,KAAK,GAAG,OAAoD,IAC1F,sBAAsB,UAAU,KAAK,GAAG,OAAsD;AAAA,EACxG,CAAC;AASL;;;AC3EO,SAAS,oBACZ,SAC8D;AAC9D,MAAI,CAAC,QAAQ,QAAQ;AAEjB,UAAM,IAAI,MAAM,qBAAqB,QAAQ,OAAO,aAAa;AAAA,EACrE;AACJ;AAGO,SAAS,oBACZ,UACmE;AACnE,QAAM,kBAAkB,SAAS,OAAO,OAAK,CAAC,EAAE,MAAM;AACtD,MAAI,gBAAgB,SAAS,GAAG;AAC5B,UAAM,mBAAmB,gBAAgB,IAAI,OAAK,EAAE,OAAO;AAE3D,UAAM,IAAI,MAAM,sBAAsB,iBAAiB,KAAK,IAAI,CAAC,aAAa;AAAA,EAClF;AACJ","sourcesContent":["import type { Address } from '@solana/addresses';\nimport type { LamportsUnsafeBeyond2Pow53Minus1 } from '@solana/rpc-types';\n\n/** The amount of bytes required to store the base account information without its data. */\nexport const BASE_ACCOUNT_SIZE = 128;\n\n/** Describe the generic account details applicable to every account. */\nexport type BaseAccount = {\n readonly programAddress: Address;\n readonly executable: boolean;\n readonly lamports: LamportsUnsafeBeyond2Pow53Minus1;\n};\n\n/** Defines a Solana account with its generic details and parsed or encoded data. */\nexport type Account<TData extends object | Uint8Array, TAddress extends string = string> = BaseAccount & {\n readonly address: Address<TAddress>;\n readonly data: TData;\n};\n\n/** Defines a Solana account with its generic details and encoded data. */\nexport type EncodedAccount<TAddress extends string = string> = Account<Uint8Array, TAddress>;\n","import type { Decoder } from '@solana/codecs-core';\n\nimport type { Account, EncodedAccount } from './account';\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\n\n/** Decodes the data of a given account using the provided decoder. */\nexport function decodeAccount<TData extends object, TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>,\n decoder: Decoder<TData>,\n): Account<TData, TAddress>;\nexport function decodeAccount<TData extends object, TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>,\n decoder: Decoder<TData>,\n): MaybeAccount<TData, TAddress>;\nexport function decodeAccount<TData extends object, TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>,\n decoder: Decoder<TData>,\n): Account<TData, TAddress> | MaybeAccount<TData, TAddress> {\n try {\n if ('exists' in encodedAccount && !encodedAccount.exists) {\n return encodedAccount;\n }\n return Object.freeze({ ...encodedAccount, data: decoder.decode(encodedAccount.data) });\n } catch (error) {\n // TODO: Coded error.\n const newError = new Error(`Failed to decode account [${encodedAccount.address}].`);\n newError.cause = error;\n throw newError;\n }\n}\n\nfunction accountExists<TData extends object>(account: Account<TData> | MaybeAccount<TData>): account is Account<TData> {\n return !('exists' in account) || ('exists' in account && account.exists);\n}\n\n/** Asserts that an account has been decoded. */\nexport function assertAccountDecoded<TData extends object, TAddress extends string = string>(\n account: Account<TData | Uint8Array, TAddress>,\n): asserts account is Account<TData, TAddress>;\nexport function assertAccountDecoded<TData extends object, TAddress extends string = string>(\n account: MaybeAccount<TData | Uint8Array, TAddress>,\n): asserts account is MaybeAccount<TData, TAddress>;\nexport function assertAccountDecoded<TData extends object, TAddress extends string = string>(\n account: Account<TData | Uint8Array, TAddress> | MaybeAccount<TData | Uint8Array, TAddress>,\n): asserts account is Account<TData, TAddress> | MaybeAccount<TData, TAddress> {\n if (accountExists(account) && account.data instanceof Uint8Array) {\n // TODO: coded error.\n throw new Error(`Expected account [${account.address}] to be decoded.`);\n }\n}\n\n/** Asserts that all accounts have been decoded. */\nexport function assertAccountsDecoded<TData extends object, TAddress extends string = string>(\n accounts: Account<TData | Uint8Array, TAddress>[],\n): asserts accounts is Account<TData, TAddress>[];\nexport function assertAccountsDecoded<TData extends object, TAddress extends string = string>(\n accounts: MaybeAccount<TData | Uint8Array, TAddress>[],\n): asserts accounts is MaybeAccount<TData, TAddress>[];\nexport function assertAccountsDecoded<TData extends object, TAddress extends string = string>(\n accounts: (Account<TData | Uint8Array, TAddress> | MaybeAccount<TData | Uint8Array, TAddress>)[],\n): asserts accounts is (Account<TData, TAddress> | MaybeAccount<TData, TAddress>)[] {\n const encoded = accounts.filter(a => accountExists(a) && a.data instanceof Uint8Array);\n if (encoded.length > 0) {\n const encodedAddresses = encoded.map(a => a.address).join(', ');\n // TODO: Coded error.\n throw new Error(`Expected accounts [${encodedAddresses}] to be decoded.`);\n }\n}\n","import type { Address } from '@solana/addresses';\nimport { getBase58Encoder, getBase64Encoder } from '@solana/codecs-strings';\n\nimport type { Account, BaseAccount, EncodedAccount } from './account';\nimport { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport type {\n AccountInfoBase,\n AccountInfoWithBase58Bytes,\n AccountInfoWithBase58EncodedData,\n AccountInfoWithBase64EncodedData,\n JsonParsedDataResponse,\n} from './rpc-api';\n\ntype Base64EncodedRpcAccount = AccountInfoBase & AccountInfoWithBase64EncodedData;\n\n/** Parse an account object received from a base64-encoded RPC call into an EncodedAccount or MaybeEncodedAccount type. */\nexport function parseBase64RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base64EncodedRpcAccount,\n): EncodedAccount<TAddress>;\nexport function parseBase64RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base64EncodedRpcAccount | null,\n): MaybeEncodedAccount<TAddress>;\nexport function parseBase64RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base64EncodedRpcAccount | null,\n): EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase64Encoder().encode(rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype Base58EncodedRpcAccount = AccountInfoBase & (AccountInfoWithBase58Bytes | AccountInfoWithBase58EncodedData);\n\n/** Parse an account object received from a base58-encoded RPC call into an EncodedAccount or MaybeEncodedAccount type. */\nexport function parseBase58RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base58EncodedRpcAccount,\n): EncodedAccount<TAddress>;\nexport function parseBase58RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base58EncodedRpcAccount | null,\n): MaybeEncodedAccount<TAddress>;\nexport function parseBase58RpcAccount<TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: Base58EncodedRpcAccount | null,\n): EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = getBase58Encoder().encode(typeof rpcAccount.data === 'string' ? rpcAccount.data : rpcAccount.data[0]);\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\ntype JsonParsedRpcAccount = AccountInfoBase & { readonly data: JsonParsedDataResponse<unknown> };\n\n/** Parse an account object received from a json-parsed RPC call into an Account or MaybeAccount type. */\nexport function parseJsonRpcAccount<TData extends object, TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: JsonParsedRpcAccount,\n): Account<TData, TAddress>;\nexport function parseJsonRpcAccount<TData extends object, TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: JsonParsedRpcAccount | null,\n): MaybeAccount<TData, TAddress>;\nexport function parseJsonRpcAccount<TData extends object, TAddress extends string = string>(\n address: Address<TAddress>,\n rpcAccount: JsonParsedRpcAccount | null,\n): Account<TData, TAddress> | MaybeAccount<TData, TAddress> {\n if (!rpcAccount) return Object.freeze({ address, exists: false });\n const data = rpcAccount.data.parsed.info as TData;\n return Object.freeze({ ...parseBaseAccount(rpcAccount), address, data, exists: true });\n}\n\nfunction parseBaseAccount(rpcAccount: AccountInfoBase): BaseAccount {\n return Object.freeze({\n executable: rpcAccount.executable,\n lamports: rpcAccount.lamports,\n programAddress: rpcAccount.owner,\n });\n}\n","import type { Address } from '@solana/addresses';\nimport type { Commitment, Rpc, Slot } from '@solana/rpc-types';\n\nimport type { MaybeAccount, MaybeEncodedAccount } from './maybe-account';\nimport { parseBase64RpcAccount, parseJsonRpcAccount } from './parse-account';\nimport type { GetAccountInfoApi, GetMultipleAccountsApi } from './rpc-api';\n\n/** Optional configuration for fetching a singular account. */\nexport type FetchAccountConfig = {\n commitment?: Commitment;\n minContextSlot?: Slot;\n abortSignal?: AbortSignal;\n};\n\n/** Fetch a base64-encoded account that may or may not exist using an RPC client. */\nexport async function fetchEncodedAccount<TAddress extends string = string>(\n rpc: Rpc<GetAccountInfoApi>,\n address: Address<TAddress>,\n config: FetchAccountConfig = {},\n): Promise<MaybeEncodedAccount<TAddress>> {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc.getAccountInfo(address, { ...rpcConfig, encoding: 'base64' }).send({ abortSignal });\n return parseBase64RpcAccount(address, response.value);\n}\n\n/** Fetch a json-parsed account that may or may not exist using an RPC client. */\nexport async function fetchJsonParsedAccount<TData extends object, TAddress extends string = string>(\n rpc: Rpc<GetAccountInfoApi>,\n address: Address<TAddress>,\n config: FetchAccountConfig = {},\n): Promise<MaybeAccount<TData, TAddress> | MaybeEncodedAccount<TAddress>> {\n const { abortSignal, ...rpcConfig } = config;\n const { value: account } = await rpc\n .getAccountInfo(address, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount<TData, TAddress>(address, account as Parameters<typeof parseJsonRpcAccount>[1])\n : parseBase64RpcAccount<TAddress>(address, account as Parameters<typeof parseBase64RpcAccount>[1]);\n}\n\n/** Optional configuration for fetching multiple accounts. */\nexport type FetchAccountsConfig = {\n commitment?: Commitment;\n minContextSlot?: Slot;\n abortSignal?: AbortSignal;\n};\n\n/** Fetch multiple base64-encoded accounts that may or may not exist using an RPC client. */\nexport async function fetchEncodedAccounts<\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address<TAddresses[P]> } = {\n [P in keyof TAddresses]: Address<TAddresses[P]>;\n },\n>(rpc: Rpc<GetMultipleAccountsApi>, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'base64' })\n .send({ abortSignal });\n return response.value.map((account, index) => parseBase64RpcAccount(addresses[index], account)) as {\n [P in keyof TAddresses]: MaybeEncodedAccount<TAddresses[P]>;\n };\n}\n\n/** Fetch multiple json-parsed accounts that may or may not exist using an RPC client. */\nexport async function fetchJsonParsedAccounts<\n TData extends object[],\n TAddresses extends string[] = string[],\n TWrappedAddresses extends { [P in keyof TAddresses]: Address<TAddresses[P]> } = {\n [P in keyof TAddresses]: Address<TAddresses[P]>;\n },\n>(rpc: Rpc<GetMultipleAccountsApi>, addresses: TWrappedAddresses, config: FetchAccountsConfig = {}) {\n const { abortSignal, ...rpcConfig } = config;\n const response = await rpc\n .getMultipleAccounts(addresses, { ...rpcConfig, encoding: 'jsonParsed' })\n .send({ abortSignal });\n return response.value.map((account, index) => {\n return !!account && typeof account === 'object' && 'parsed' in account.data\n ? parseJsonRpcAccount(addresses[index], account as Parameters<typeof parseJsonRpcAccount>[1])\n : parseBase64RpcAccount(addresses[index], account as Parameters<typeof parseBase64RpcAccount>[1]);\n }) as {\n [P in keyof TData]:\n | MaybeAccount<TData[P], TAddresses[P & keyof TAddresses]>\n | MaybeEncodedAccount<TAddresses[P & keyof TAddresses]>;\n } & {\n [P in keyof TAddresses]:\n | MaybeAccount<TData[P & keyof TData], TAddresses[P]>\n | MaybeEncodedAccount<TAddresses[P]>;\n };\n}\n","import { Address } from '@solana/addresses';\n\nimport { Account } from './account';\n\n/** Defines a Solana account that may or may not exist after having tried to fetch it. */\nexport type MaybeAccount<TData extends object | Uint8Array, TAddress extends string = string> =\n | ({ readonly exists: true } & Account<TData, TAddress>)\n | { readonly exists: false; readonly address: Address<TAddress> };\n\n/** Defines a Solana account with encoded data that may or may not exist after having tried to fetch it. */\nexport type MaybeEncodedAccount<TAddress extends string = string> = MaybeAccount<Uint8Array, TAddress>;\n\n/** Asserts that an account that may or may not exists, actually exists. */\nexport function assertAccountExists<TData extends object | Uint8Array, TAddress extends string = string>(\n account: MaybeAccount<TData, TAddress>,\n): asserts account is Account<TData, TAddress> & { exists: true } {\n if (!account.exists) {\n // TODO: Coded error.\n throw new Error(`Expected account [${account.address}] to exist.`);\n }\n}\n\n/** Asserts that all accounts that may or may not exist, actually all exist. */\nexport function assertAccountsExist<TData extends object | Uint8Array, TAddress extends string = string>(\n accounts: MaybeAccount<TData, TAddress>[],\n): asserts accounts is (Account<TData, TAddress> & { exists: true })[] {\n const missingAccounts = accounts.filter(a => !a.exists);\n if (missingAccounts.length > 0) {\n const missingAddresses = missingAccounts.map(a => a.address);\n // TODO: Coded error.\n throw new Error(`Expected accounts [${missingAddresses.join(', ')}] to exist.`);\n }\n}\n"]}
|