@pipeline-sol/sdk 0.0.0-stage → 0.1.0

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.
Files changed (59) hide show
  1. package/README.md +201 -2
  2. package/dist/actions.d.ts +87 -0
  3. package/dist/actions.d.ts.map +1 -0
  4. package/dist/actions.js +326 -0
  5. package/dist/actions.js.map +1 -0
  6. package/dist/codecs.d.ts +188 -0
  7. package/dist/codecs.d.ts.map +1 -0
  8. package/dist/codecs.js +296 -0
  9. package/dist/codecs.js.map +1 -0
  10. package/dist/constants.d.ts +97 -0
  11. package/dist/constants.d.ts.map +1 -0
  12. package/dist/constants.js +98 -0
  13. package/dist/constants.js.map +1 -0
  14. package/dist/discovery.d.ts +17 -0
  15. package/dist/discovery.d.ts.map +1 -0
  16. package/dist/discovery.js +47 -0
  17. package/dist/discovery.js.map +1 -0
  18. package/dist/events.d.ts +106 -0
  19. package/dist/events.d.ts.map +1 -0
  20. package/dist/events.js +149 -0
  21. package/dist/events.js.map +1 -0
  22. package/dist/fees.d.ts +16 -0
  23. package/dist/fees.d.ts.map +1 -0
  24. package/dist/fees.js +60 -0
  25. package/dist/fees.js.map +1 -0
  26. package/dist/http.d.ts +23 -0
  27. package/dist/http.d.ts.map +1 -0
  28. package/dist/http.js +99 -0
  29. package/dist/http.js.map +1 -0
  30. package/dist/index.d.ts +14 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +13 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/inspect.d.ts +347 -0
  35. package/dist/inspect.d.ts.map +1 -0
  36. package/dist/inspect.js +721 -0
  37. package/dist/inspect.js.map +1 -0
  38. package/dist/instructions.d.ts +101 -0
  39. package/dist/instructions.d.ts.map +1 -0
  40. package/dist/instructions.js +201 -0
  41. package/dist/instructions.js.map +1 -0
  42. package/dist/listing.d.ts +35 -0
  43. package/dist/listing.d.ts.map +1 -0
  44. package/dist/listing.js +49 -0
  45. package/dist/listing.js.map +1 -0
  46. package/dist/metadata.d.ts +266 -0
  47. package/dist/metadata.d.ts.map +1 -0
  48. package/dist/metadata.js +515 -0
  49. package/dist/metadata.js.map +1 -0
  50. package/dist/pda.d.ts +21 -0
  51. package/dist/pda.d.ts.map +1 -0
  52. package/dist/pda.js +52 -0
  53. package/dist/pda.js.map +1 -0
  54. package/dist/quote.d.ts +63 -0
  55. package/dist/quote.d.ts.map +1 -0
  56. package/dist/quote.js +169 -0
  57. package/dist/quote.js.map +1 -0
  58. package/package.json +56 -5
  59. package/schema/strategy-metadata.v1.json +171 -0
@@ -0,0 +1,721 @@
1
+ // Read-only trust facts about strategies, markets and mints, and machine-readable flags
2
+ // for filtering on them. Facts only: no scores and no safe/unsafe judgement. Pipeline
3
+ // admits any strategy; front ends decide what to show and filter.
4
+ import { getAddressDecoder, getBase64Encoder, } from '@solana/kit';
5
+ import { decodeMarket, decodeStrategy, marketMints } from './codecs.js';
6
+ import { BPF_LOADER_UPGRADEABLE_PROGRAM_ADDRESS, PIPELINE_PROGRAM_ADDRESS, TOKEN_2022_PROGRAM_ADDRESS, TOKEN_PROGRAM_ADDRESS, } from './constants.js';
7
+ import { boundedFetch, parseJsonBody } from './http.js';
8
+ import { fetchStrategyMetadata } from './metadata.js';
9
+ import { strategyPda } from './pda.js';
10
+ // ---------------------------------------------------------------------------------------
11
+ // Flags
12
+ // ---------------------------------------------------------------------------------------
13
+ /**
14
+ * Every flag, with its exact meaning. Flag names are stable: new flags may be added, but
15
+ * existing ones keep their meaning.
16
+ */
17
+ export const FLAG_DESCRIPTIONS = {
18
+ // Strategy program
19
+ upgradeable: 'The strategy program can be upgraded: it has an upgrade authority (loader v3) or is not finalized (loader v4).',
20
+ frozen: 'The strategy program can no longer be upgraded: no upgrade authority (loader v3), finalized (loader v4), or a non-upgradeable loader.',
21
+ 'program-missing': 'No executable code at the strategy program address (never deployed, closed, or retracted).',
22
+ 'verified-build': "OtterSec's verified-builds API reports the program as built from public source, and its hash matches the deployed code. Mainnet only; needs the SDK to hash the program (the default).",
23
+ 'unverified-build': "OtterSec's verified-builds API answered but does not report a verified build of the deployed code. Not set when the API could not be reached, off mainnet, or when the program wasn't hashed.",
24
+ // Registry and metadata
25
+ unregistered: 'The program has no Strategy account in the router.',
26
+ 'metadata-missing': "The strategy's metadata URI is empty.",
27
+ 'metadata-unreachable': 'The metadata URI is unsupported, or could not be fetched (network error, timeout, HTTP error, too large).',
28
+ 'metadata-invalid': 'The metadata document was fetched but is not valid strategy metadata version 1.',
29
+ 'conformance-report': 'Valid metadata links a conformance report. The SDK does not check the report.',
30
+ // Mints
31
+ 'mint-unreadable': 'A market mint account is missing or is not an SPL Token or Token-2022 mint.',
32
+ 'token-2022': 'A mint is owned by Token-2022.',
33
+ 'mint-authority': 'A mint has a mint authority, so its supply can grow.',
34
+ 'freeze-authority': 'A mint has a freeze authority, which can freeze token accounts (including market vaults and fee accounts).',
35
+ 'transfer-hook': 'A mint has a transfer hook program set: every transfer calls it.',
36
+ 'transfer-hook-authority': "A mint's transfer hook has an authority, which can set or change the hook program.",
37
+ 'transfer-fee': 'A mint charges a non-zero transfer fee now, or from a scheduled epoch.',
38
+ 'transfer-fee-authority': "A mint's transfer fee has an authority, which can set or change the fee.",
39
+ 'permanent-delegate': 'A mint has a permanent delegate, which can transfer or burn tokens from any account.',
40
+ 'non-transferable': 'A mint is non-transferable.',
41
+ 'default-frozen': 'New token accounts for a mint start frozen (DefaultAccountState).',
42
+ pausable: 'A mint is pausable: an authority can pause minting, burning and transfers.',
43
+ paused: 'A mint is currently paused.',
44
+ 'closable-mint': 'A mint has a close authority.',
45
+ 'interest-bearing': 'A mint is interest-bearing: its UI amount differs from the raw amount.',
46
+ 'scaled-ui-amount': 'A mint scales its UI amount by a multiplier an authority can change.',
47
+ 'confidential-transfers': 'A mint supports confidential transfers.',
48
+ 'permissioned-burn': 'Burning a mint requires an authority’s approval.',
49
+ 'unknown-extension': 'A mint has a Token-2022 extension this SDK does not decode.',
50
+ };
51
+ /** All flags, in a stable order. */
52
+ export const FLAGS = Object.keys(FLAG_DESCRIPTIONS);
53
+ function orderedFlags(flags) {
54
+ const set = new Set(flags);
55
+ return FLAGS.filter((flag) => set.has(flag));
56
+ }
57
+ /**
58
+ * Keeps the items that have every `require` flag and none of the `exclude` flags. Works on
59
+ * anything with `flags`: market, strategy or mint inspections.
60
+ */
61
+ export function filterMarkets(items, filter) {
62
+ return items.filter((item) => (filter.require ?? []).every((flag) => item.flags.includes(flag)) &&
63
+ !(filter.exclude ?? []).some((flag) => item.flags.includes(flag)));
64
+ }
65
+ const base64 = getBase64Encoder();
66
+ const addressDecoder = getAddressDecoder();
67
+ async function getAccount(rpc, address, dataSlice) {
68
+ const { value } = await rpc
69
+ .getAccountInfo(address, { encoding: 'base64', ...(dataSlice ? { dataSlice } : {}) })
70
+ .send();
71
+ if (!value) {
72
+ return null;
73
+ }
74
+ return { owner: value.owner, executable: value.executable, data: base64.encode(value.data[0]) };
75
+ }
76
+ function view(data) {
77
+ return new DataView(data.buffer, data.byteOffset, data.byteLength);
78
+ }
79
+ function readAddress(data, offset) {
80
+ return addressDecoder.decode(data.subarray(offset, offset + 32));
81
+ }
82
+ /** Token-2022's `OptionalNonZeroPubkey`: all zeros means none. */
83
+ function optionalAddress(data, offset) {
84
+ const bytes = data.subarray(offset, offset + 32);
85
+ return bytes.every((b) => b === 0) ? null : readAddress(data, offset);
86
+ }
87
+ /** SPL Token's `COption<Pubkey>`: a u32 tag, then 32 bytes. */
88
+ function cOptionAddress(data, offset) {
89
+ return view(data).getUint32(offset, true) === 0 ? null : readAddress(data, offset + 4);
90
+ }
91
+ async function sha256Hex(bytes) {
92
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
93
+ return Array.from(digest, (b) => b.toString(16).padStart(2, '0')).join('');
94
+ }
95
+ /** `bytes` without trailing zero bytes, as `solana-verify` hashes them. */
96
+ function trimTrailingZeros(bytes) {
97
+ let end = bytes.length;
98
+ while (end > 0 && bytes[end - 1] === 0) {
99
+ end--;
100
+ }
101
+ return bytes.subarray(0, end);
102
+ }
103
+ // ---------------------------------------------------------------------------------------
104
+ // Programs
105
+ // ---------------------------------------------------------------------------------------
106
+ export const LOADER_ADDRESSES = {
107
+ v1: 'BPFLoader1111111111111111111111111111111111',
108
+ v2: 'BPFLoader2111111111111111111111111111111111',
109
+ upgradeable: BPF_LOADER_UPGRADEABLE_PROGRAM_ADDRESS,
110
+ v4: 'LoaderV411111111111111111111111111111111111',
111
+ native: 'NativeLoader1111111111111111111111111111111',
112
+ };
113
+ /** Bytes before the ELF in a loader-v3 ProgramData account. */
114
+ export const PROGRAMDATA_METADATA_LEN = 45;
115
+ /** Bytes before the ELF in a loader-v4 program account. */
116
+ export const LOADER_V4_METADATA_LEN = 48;
117
+ /** Loader, upgradeability, upgrade authority, last deploy slot and code hash of a program. */
118
+ export async function inspectProgram(rpc, programId, options = {}) {
119
+ const hash = options.hashExecutable ?? true;
120
+ const result = {
121
+ programId,
122
+ loader: 'none',
123
+ loaderAddress: null,
124
+ deployed: false,
125
+ upgradeable: false,
126
+ upgradeAuthority: null,
127
+ programDataAddress: null,
128
+ lastDeploySlot: null,
129
+ loaderV4Status: null,
130
+ executableSha256: null,
131
+ flags: [],
132
+ };
133
+ const account = await getAccount(rpc, programId);
134
+ if (account) {
135
+ result.loaderAddress = account.owner;
136
+ switch (account.owner) {
137
+ case LOADER_ADDRESSES.upgradeable:
138
+ result.loader = 'upgradeable';
139
+ await inspectUpgradeable(rpc, account, result, hash);
140
+ break;
141
+ case LOADER_ADDRESSES.v4:
142
+ result.loader = 'v4';
143
+ await inspectLoaderV4(account, result, hash);
144
+ break;
145
+ case LOADER_ADDRESSES.v1:
146
+ case LOADER_ADDRESSES.v2:
147
+ result.loader = account.owner === LOADER_ADDRESSES.v1 ? 'v1' : 'v2';
148
+ result.deployed = account.executable && account.data.length > 0;
149
+ if (hash && result.deployed) {
150
+ result.executableSha256 = await sha256Hex(trimTrailingZeros(account.data));
151
+ }
152
+ break;
153
+ case LOADER_ADDRESSES.native:
154
+ result.loader = 'native';
155
+ result.deployed = account.executable;
156
+ break;
157
+ default:
158
+ result.loader = 'other';
159
+ result.deployed = account.executable;
160
+ }
161
+ }
162
+ const flags = [];
163
+ if (!result.deployed) {
164
+ flags.push('program-missing');
165
+ }
166
+ else if (result.upgradeable) {
167
+ flags.push('upgradeable');
168
+ }
169
+ else if (result.loader !== 'native' && result.loader !== 'other' && result.loaderV4Status !== 'unknown') {
170
+ flags.push('frozen');
171
+ }
172
+ result.flags = orderedFlags(flags);
173
+ return result;
174
+ }
175
+ async function inspectUpgradeable(rpc, account, result, hash) {
176
+ // UpgradeableLoaderState::Program { programdata_address }: u32 tag 2, then 32 bytes.
177
+ if (account.data.length < 36 || view(account.data).getUint32(0, true) !== 2) {
178
+ return;
179
+ }
180
+ const programData = readAddress(account.data, 4);
181
+ result.programDataAddress = programData;
182
+ const data = await getAccount(rpc, programData, hash ? undefined : { offset: 0, length: PROGRAMDATA_METADATA_LEN });
183
+ // UpgradeableLoaderState::ProgramData { slot: u64, upgrade_authority: Option<Pubkey> }.
184
+ if (!data ||
185
+ data.owner !== LOADER_ADDRESSES.upgradeable ||
186
+ data.data.length < PROGRAMDATA_METADATA_LEN ||
187
+ view(data.data).getUint32(0, true) !== 3) {
188
+ return;
189
+ }
190
+ result.deployed = account.executable;
191
+ result.lastDeploySlot = view(data.data).getBigUint64(4, true);
192
+ result.upgradeAuthority = data.data[12] === 1 ? readAddress(data.data, 13) : null;
193
+ result.upgradeable = result.upgradeAuthority !== null;
194
+ if (hash) {
195
+ result.executableSha256 = await sha256Hex(trimTrailingZeros(data.data.subarray(PROGRAMDATA_METADATA_LEN)));
196
+ }
197
+ }
198
+ async function inspectLoaderV4(account, result, hash) {
199
+ // LoaderV4State { slot: u64, authority_address_or_next_version: Pubkey, status: u64 }.
200
+ if (account.data.length < LOADER_V4_METADATA_LEN) {
201
+ return;
202
+ }
203
+ const status = view(account.data).getBigUint64(40, true);
204
+ result.loaderV4Status =
205
+ status === 0n ? 'retracted' : status === 1n ? 'deployed' : status === 2n ? 'finalized' : 'unknown';
206
+ result.lastDeploySlot = view(account.data).getBigUint64(0, true);
207
+ result.deployed = result.loaderV4Status !== 'retracted';
208
+ if (result.loaderV4Status === 'retracted' || result.loaderV4Status === 'deployed') {
209
+ result.upgradeable = true;
210
+ result.upgradeAuthority = readAddress(account.data, 8);
211
+ }
212
+ if (hash && result.deployed) {
213
+ result.executableSha256 = await sha256Hex(trimTrailingZeros(account.data.subarray(LOADER_V4_METADATA_LEN)));
214
+ }
215
+ }
216
+ // ---------------------------------------------------------------------------------------
217
+ // Verified builds (OtterSec)
218
+ // ---------------------------------------------------------------------------------------
219
+ export const DEFAULT_VERIFY_API_URL = 'https://verify.osec.io';
220
+ function noVerifiedBuild(status) {
221
+ return {
222
+ status,
223
+ verified: false,
224
+ repository: null,
225
+ commit: null,
226
+ onchainHash: null,
227
+ executableHash: null,
228
+ lastVerifiedAt: null,
229
+ message: null,
230
+ };
231
+ }
232
+ function apiString(value) {
233
+ // The API reports a missing commit as the string "None", and other gaps as "".
234
+ return typeof value === 'string' && value !== '' && value !== 'None' ? value : null;
235
+ }
236
+ /**
237
+ * The program's status in OtterSec's verified-builds API
238
+ * (`GET <apiUrl>/status/<programId>`). OtterSec only covers mainnet programs: a devnet
239
+ * address is looked up as if it were on mainnet. Never throws: network or format errors
240
+ * give status `unknown`.
241
+ */
242
+ export async function fetchVerifiedBuild(programId, options = {}) {
243
+ const unknown = (error) => ({ ...noVerifiedBuild('unknown'), error });
244
+ const base = (options.apiUrl ?? DEFAULT_VERIFY_API_URL).replace(/\/+$/, '');
245
+ const response = await boundedFetch(`${base}/status/${programId}`, {
246
+ fetch: options.fetch,
247
+ maxBytes: 64 * 1024,
248
+ timeoutMs: options.timeoutMs ?? 10_000,
249
+ signal: options.signal,
250
+ });
251
+ if (!response.ok) {
252
+ return unknown(response.message);
253
+ }
254
+ const json = parseJsonBody(response.body);
255
+ if (json === null || typeof json !== 'object' || typeof json.is_verified !== 'boolean') {
256
+ return unknown('unexpected response');
257
+ }
258
+ const body = json;
259
+ const verified = body.is_verified === true;
260
+ return {
261
+ status: verified ? 'verified' : 'unverified',
262
+ verified,
263
+ repository: apiString(body.repo_url),
264
+ commit: apiString(body.commit),
265
+ onchainHash: apiString(body.on_chain_hash),
266
+ executableHash: apiString(body.executable_hash),
267
+ lastVerifiedAt: apiString(body.last_verified_at),
268
+ message: apiString(body.message),
269
+ };
270
+ }
271
+ // ---------------------------------------------------------------------------------------
272
+ // Mints
273
+ // ---------------------------------------------------------------------------------------
274
+ /** Token-2022 extension type numbers (`ExtensionType`). */
275
+ export const EXTENSION_TYPES = {
276
+ TransferFeeConfig: 1,
277
+ MintCloseAuthority: 3,
278
+ ConfidentialTransferMint: 4,
279
+ DefaultAccountState: 6,
280
+ NonTransferable: 9,
281
+ InterestBearingConfig: 10,
282
+ PermanentDelegate: 12,
283
+ TransferHook: 14,
284
+ ConfidentialTransferFeeConfig: 16,
285
+ MetadataPointer: 18,
286
+ TokenMetadata: 19,
287
+ GroupPointer: 20,
288
+ TokenGroup: 21,
289
+ GroupMemberPointer: 22,
290
+ TokenGroupMember: 23,
291
+ ConfidentialMintBurn: 24,
292
+ ScaledUiAmount: 25,
293
+ Pausable: 26,
294
+ PermissionedBurn: 28,
295
+ };
296
+ const MINT_LEN = 82;
297
+ /** Token-2022 pads mints with extensions to the token account length before the account type. */
298
+ const ACCOUNT_TYPE_OFFSET = 165;
299
+ const ACCOUNT_TYPE_MINT = 1;
300
+ /** Token program, supply, authorities and decoded Token-2022 extensions of a mint. `null` if not a mint. */
301
+ export async function inspectMint(rpc, mint, options = {}) {
302
+ const account = await getAccount(rpc, mint);
303
+ if (!account) {
304
+ return null;
305
+ }
306
+ const epoch = options.epoch ?? (hasTransferFee(account) ? (await rpc.getEpochInfo().send()).epoch : undefined);
307
+ return decodeMint(mint, account.owner, account.data, epoch ?? 0n);
308
+ }
309
+ function hasTransferFee(account) {
310
+ return (account.owner === TOKEN_2022_PROGRAM_ADDRESS &&
311
+ tlvEntries(account.data).some((entry) => entry.type === EXTENSION_TYPES.TransferFeeConfig));
312
+ }
313
+ function tlvEntries(data) {
314
+ const entries = [];
315
+ if (data.length <= ACCOUNT_TYPE_OFFSET) {
316
+ return entries;
317
+ }
318
+ const dv = view(data);
319
+ let offset = ACCOUNT_TYPE_OFFSET + 1;
320
+ while (offset + 4 <= data.length) {
321
+ const type = dv.getUint16(offset, true);
322
+ const length = dv.getUint16(offset + 2, true);
323
+ if (type === 0) {
324
+ break;
325
+ }
326
+ const value = data.subarray(offset + 4, offset + 4 + length);
327
+ if (value.length < length) {
328
+ break;
329
+ }
330
+ entries.push({ type, value });
331
+ offset += 4 + length;
332
+ }
333
+ return entries;
334
+ }
335
+ /**
336
+ * Decodes mint account bytes owned by `tokenProgram`. `epoch` picks the transfer fee in
337
+ * force. `null` if the bytes are not an initialized mint.
338
+ */
339
+ export function decodeMint(mint, tokenProgram, data, epoch = 0n) {
340
+ if (tokenProgram !== TOKEN_PROGRAM_ADDRESS && tokenProgram !== TOKEN_2022_PROGRAM_ADDRESS) {
341
+ return null;
342
+ }
343
+ if (data.length < MINT_LEN || data[45] !== 1) {
344
+ return null;
345
+ }
346
+ if (data.length > MINT_LEN) {
347
+ if (tokenProgram !== TOKEN_2022_PROGRAM_ADDRESS || data[ACCOUNT_TYPE_OFFSET] !== ACCOUNT_TYPE_MINT) {
348
+ return null;
349
+ }
350
+ }
351
+ const result = {
352
+ mint,
353
+ tokenProgram,
354
+ mintAuthority: cOptionAddress(data, 0),
355
+ supply: view(data).getBigUint64(36, true),
356
+ decimals: data[44],
357
+ freezeAuthority: cOptionAddress(data, 46),
358
+ extensions: {},
359
+ extensionTypes: [],
360
+ unknownExtensions: [],
361
+ flags: [],
362
+ };
363
+ for (const { type, value } of tlvEntries(data)) {
364
+ result.extensionTypes.push(type);
365
+ if (!decodeExtension(result.extensions, type, value, epoch)) {
366
+ result.unknownExtensions.push(type);
367
+ }
368
+ }
369
+ result.flags = mintFlags(result);
370
+ return result;
371
+ }
372
+ const textDecoder = new TextDecoder();
373
+ function readTransferFee(value, offset) {
374
+ const dv = view(value);
375
+ return {
376
+ epoch: dv.getBigUint64(offset, true),
377
+ maximumFee: dv.getBigUint64(offset + 8, true),
378
+ basisPoints: dv.getUint16(offset + 16, true),
379
+ };
380
+ }
381
+ function decodeTokenMetadata(value) {
382
+ const dv = view(value);
383
+ let offset = 64;
384
+ const readString = () => {
385
+ const length = dv.getUint32(offset, true);
386
+ const bytes = value.subarray(offset + 4, offset + 4 + length);
387
+ if (bytes.length !== length) {
388
+ throw new RangeError('truncated string');
389
+ }
390
+ offset += 4 + length;
391
+ return textDecoder.decode(bytes);
392
+ };
393
+ const name = readString();
394
+ const symbol = readString();
395
+ const uri = readString();
396
+ const count = dv.getUint32(offset, true);
397
+ offset += 4;
398
+ const additionalMetadata = [];
399
+ for (let i = 0; i < count; i++) {
400
+ additionalMetadata.push([readString(), readString()]);
401
+ }
402
+ return {
403
+ updateAuthority: optionalAddress(value, 0),
404
+ mint: readAddress(value, 32),
405
+ name,
406
+ symbol,
407
+ uri,
408
+ additionalMetadata,
409
+ };
410
+ }
411
+ /** Decodes one extension into `out`. Returns `false` for unknown or malformed ones. */
412
+ function decodeExtension(out, type, value, epoch) {
413
+ const dv = view(value);
414
+ const need = (length) => value.length >= length;
415
+ try {
416
+ switch (type) {
417
+ case EXTENSION_TYPES.TransferFeeConfig: {
418
+ if (!need(108))
419
+ return false;
420
+ const older = readTransferFee(value, 72);
421
+ const newer = readTransferFee(value, 90);
422
+ out.transferFee = {
423
+ authority: optionalAddress(value, 0),
424
+ withdrawWithheldAuthority: optionalAddress(value, 32),
425
+ withheldAmount: dv.getBigUint64(64, true),
426
+ older,
427
+ newer,
428
+ current: epoch >= newer.epoch ? newer : older,
429
+ };
430
+ return true;
431
+ }
432
+ case EXTENSION_TYPES.MintCloseAuthority:
433
+ if (!need(32))
434
+ return false;
435
+ out.mintCloseAuthority = { closeAuthority: optionalAddress(value, 0) };
436
+ return true;
437
+ case EXTENSION_TYPES.ConfidentialTransferMint:
438
+ if (!need(33))
439
+ return false;
440
+ out.confidentialTransfer = {
441
+ authority: optionalAddress(value, 0),
442
+ autoApproveNewAccounts: value[32] === 1,
443
+ };
444
+ return true;
445
+ case EXTENSION_TYPES.ConfidentialTransferFeeConfig:
446
+ if (!need(32))
447
+ return false;
448
+ out.confidentialTransferFee = { authority: optionalAddress(value, 0) };
449
+ return true;
450
+ case EXTENSION_TYPES.ConfidentialMintBurn:
451
+ out.confidentialMintBurn = true;
452
+ return true;
453
+ case EXTENSION_TYPES.DefaultAccountState: {
454
+ if (!need(1))
455
+ return false;
456
+ const state = ['uninitialized', 'initialized', 'frozen'][value[0]];
457
+ if (!state)
458
+ return false;
459
+ out.defaultAccountState = { state };
460
+ return true;
461
+ }
462
+ case EXTENSION_TYPES.NonTransferable:
463
+ out.nonTransferable = true;
464
+ return true;
465
+ case EXTENSION_TYPES.InterestBearingConfig:
466
+ if (!need(52))
467
+ return false;
468
+ out.interestBearing = {
469
+ rateAuthority: optionalAddress(value, 0),
470
+ initializationTimestamp: dv.getBigInt64(32, true),
471
+ preUpdateAverageRateBps: dv.getInt16(40, true),
472
+ lastUpdateTimestamp: dv.getBigInt64(42, true),
473
+ currentRateBps: dv.getInt16(50, true),
474
+ };
475
+ return true;
476
+ case EXTENSION_TYPES.PermanentDelegate:
477
+ if (!need(32))
478
+ return false;
479
+ out.permanentDelegate = { delegate: optionalAddress(value, 0) };
480
+ return true;
481
+ case EXTENSION_TYPES.TransferHook:
482
+ if (!need(64))
483
+ return false;
484
+ out.transferHook = { authority: optionalAddress(value, 0), programId: optionalAddress(value, 32) };
485
+ return true;
486
+ case EXTENSION_TYPES.MetadataPointer:
487
+ if (!need(64))
488
+ return false;
489
+ out.metadataPointer = {
490
+ authority: optionalAddress(value, 0),
491
+ metadataAddress: optionalAddress(value, 32),
492
+ };
493
+ return true;
494
+ case EXTENSION_TYPES.TokenMetadata:
495
+ if (!need(64))
496
+ return false;
497
+ out.tokenMetadata = decodeTokenMetadata(value);
498
+ return true;
499
+ case EXTENSION_TYPES.GroupPointer:
500
+ if (!need(64))
501
+ return false;
502
+ out.groupPointer = { authority: optionalAddress(value, 0), groupAddress: optionalAddress(value, 32) };
503
+ return true;
504
+ case EXTENSION_TYPES.TokenGroup:
505
+ if (!need(80))
506
+ return false;
507
+ out.tokenGroup = {
508
+ updateAuthority: optionalAddress(value, 0),
509
+ mint: readAddress(value, 32),
510
+ size: dv.getBigUint64(64, true),
511
+ maxSize: dv.getBigUint64(72, true),
512
+ };
513
+ return true;
514
+ case EXTENSION_TYPES.GroupMemberPointer:
515
+ if (!need(64))
516
+ return false;
517
+ out.groupMemberPointer = {
518
+ authority: optionalAddress(value, 0),
519
+ memberAddress: optionalAddress(value, 32),
520
+ };
521
+ return true;
522
+ case EXTENSION_TYPES.TokenGroupMember:
523
+ if (!need(72))
524
+ return false;
525
+ out.tokenGroupMember = {
526
+ mint: readAddress(value, 0),
527
+ group: readAddress(value, 32),
528
+ memberNumber: dv.getBigUint64(64, true),
529
+ };
530
+ return true;
531
+ case EXTENSION_TYPES.ScaledUiAmount:
532
+ if (!need(56))
533
+ return false;
534
+ out.scaledUiAmount = {
535
+ authority: optionalAddress(value, 0),
536
+ multiplier: dv.getFloat64(32, true),
537
+ newMultiplierEffectiveTimestamp: dv.getBigInt64(40, true),
538
+ newMultiplier: dv.getFloat64(48, true),
539
+ };
540
+ return true;
541
+ case EXTENSION_TYPES.Pausable:
542
+ if (!need(33))
543
+ return false;
544
+ out.pausable = { authority: optionalAddress(value, 0), paused: value[32] === 1 };
545
+ return true;
546
+ case EXTENSION_TYPES.PermissionedBurn:
547
+ if (!need(32))
548
+ return false;
549
+ out.permissionedBurn = { authority: optionalAddress(value, 0) };
550
+ return true;
551
+ default:
552
+ return false;
553
+ }
554
+ }
555
+ catch {
556
+ return false;
557
+ }
558
+ }
559
+ function mintFlags(mint) {
560
+ const flags = [];
561
+ const e = mint.extensions;
562
+ if (mint.tokenProgram === TOKEN_2022_PROGRAM_ADDRESS)
563
+ flags.push('token-2022');
564
+ if (mint.mintAuthority)
565
+ flags.push('mint-authority');
566
+ if (mint.freezeAuthority)
567
+ flags.push('freeze-authority');
568
+ if (e.transferHook?.programId)
569
+ flags.push('transfer-hook');
570
+ if (e.transferHook?.authority)
571
+ flags.push('transfer-hook-authority');
572
+ // A fee in force now, or a non-zero fee scheduled for a later epoch. A fee that was
573
+ // lowered to zero and is now in force doesn't count.
574
+ const scheduled = e.transferFee && e.transferFee.newer.epoch > e.transferFee.current.epoch;
575
+ if (e.transferFee &&
576
+ (e.transferFee.current.basisPoints > 0 || (scheduled && e.transferFee.newer.basisPoints > 0))) {
577
+ flags.push('transfer-fee');
578
+ }
579
+ if (e.transferFee?.authority)
580
+ flags.push('transfer-fee-authority');
581
+ if (e.permanentDelegate?.delegate)
582
+ flags.push('permanent-delegate');
583
+ if (e.nonTransferable)
584
+ flags.push('non-transferable');
585
+ if (e.defaultAccountState?.state === 'frozen')
586
+ flags.push('default-frozen');
587
+ if (e.pausable && (e.pausable.authority || e.pausable.paused))
588
+ flags.push('pausable');
589
+ if (e.pausable?.paused)
590
+ flags.push('paused');
591
+ if (e.mintCloseAuthority?.closeAuthority)
592
+ flags.push('closable-mint');
593
+ if (e.interestBearing)
594
+ flags.push('interest-bearing');
595
+ if (e.scaledUiAmount)
596
+ flags.push('scaled-ui-amount');
597
+ if (e.confidentialTransfer || e.confidentialMintBurn)
598
+ flags.push('confidential-transfers');
599
+ if (e.permissionedBurn)
600
+ flags.push('permissioned-burn');
601
+ if (mint.unknownExtensions.length > 0)
602
+ flags.push('unknown-extension');
603
+ return orderedFlags(flags);
604
+ }
605
+ function enabled(option, fetch) {
606
+ if (option === false) {
607
+ return null;
608
+ }
609
+ const base = option === true || option === undefined ? {} : option;
610
+ return { fetch, ...base };
611
+ }
612
+ /**
613
+ * A strategy's registration (registered_at, market_count, metadata_uri), its program
614
+ * facts, its metadata document and its verified-build status, with flags.
615
+ */
616
+ export async function inspectStrategy(rpc, programId, options = {}) {
617
+ const strategyAccount = await strategyPda(programId);
618
+ const metadataOptions = enabled(options.metadata, options.fetch);
619
+ const verifyOptions = enabled(options.verifiedBuild, options.fetch);
620
+ const offMainnet = options.cluster !== undefined && options.cluster !== 'mainnet';
621
+ const [raw, program, verifiedBuild] = await Promise.all([
622
+ getAccount(rpc, strategyAccount),
623
+ inspectProgram(rpc, programId, options),
624
+ !verifyOptions
625
+ ? Promise.resolve(null)
626
+ : offMainnet
627
+ ? Promise.resolve(noVerifiedBuild('not-applicable'))
628
+ : fetchVerifiedBuild(programId, verifyOptions),
629
+ ]);
630
+ const registration = raw && raw.owner === PIPELINE_PROGRAM_ADDRESS ? decodeStrategy(raw.data) : null;
631
+ let metadata;
632
+ const uri = registration?.metadataUri ?? '';
633
+ if (uri.trim() === '') {
634
+ metadata = { status: 'missing', uri: '' };
635
+ }
636
+ else if (!metadataOptions) {
637
+ metadata = { status: 'not-fetched', uri };
638
+ }
639
+ else {
640
+ const fetched = await fetchStrategyMetadata(uri, metadataOptions);
641
+ if (fetched.ok) {
642
+ metadata = { status: 'valid', uri, value: fetched.value, warnings: fetched.warnings };
643
+ }
644
+ else {
645
+ metadata = {
646
+ status: fetched.reason === 'invalid' || fetched.reason === 'not-json' ? 'invalid' : 'unreachable',
647
+ uri,
648
+ errors: fetched.errors,
649
+ };
650
+ }
651
+ }
652
+ const flags = [...program.flags];
653
+ if (!registration) {
654
+ flags.push('unregistered');
655
+ }
656
+ else if (metadata.status === 'missing') {
657
+ flags.push('metadata-missing');
658
+ }
659
+ if (metadata.status === 'unreachable')
660
+ flags.push('metadata-unreachable');
661
+ if (metadata.status === 'invalid')
662
+ flags.push('metadata-invalid');
663
+ if (metadata.status === 'valid' && metadata.value.conformance)
664
+ flags.push('conformance-report');
665
+ // Build flags need our own hash of the deployed code: OtterSec's record can be stale
666
+ // (the program upgraded since), so its hash must equal what is deployed now. Without
667
+ // a hash (`hashExecutable: false`) neither flag is set.
668
+ const answered = verifiedBuild && (verifiedBuild.status === 'verified' || verifiedBuild.status === 'unverified');
669
+ if (answered && program.deployed && program.executableSha256 !== null) {
670
+ const matches = verifiedBuild.onchainHash === program.executableSha256;
671
+ flags.push(verifiedBuild.verified && matches ? 'verified-build' : 'unverified-build');
672
+ }
673
+ return {
674
+ programId,
675
+ strategyAccount,
676
+ registration,
677
+ program,
678
+ metadata,
679
+ verifiedBuild,
680
+ flags: orderedFlags(flags),
681
+ };
682
+ }
683
+ /**
684
+ * A recorded market (mints, created_by, created_at), its strategy's inspection and each
685
+ * mint's inspection, with the union of their flags. `null` if `market` is not a router
686
+ * Market account.
687
+ */
688
+ export async function inspectMarket(rpc, market, options = {}) {
689
+ const raw = await getAccount(rpc, market);
690
+ const decoded = raw && raw.owner === PIPELINE_PROGRAM_ADDRESS ? decodeMarket(raw.data) : null;
691
+ if (!decoded) {
692
+ return null;
693
+ }
694
+ const mints = marketMints(decoded);
695
+ const [strategy, mintInspections] = await Promise.all([
696
+ options.strategy && options.strategy.programId === decoded.strategyProgram
697
+ ? Promise.resolve(options.strategy)
698
+ : inspectStrategy(rpc, decoded.strategyProgram, options),
699
+ Promise.all(mints.map((mint) => inspectMint(rpc, mint, options))),
700
+ ]);
701
+ const flags = [...strategy.flags];
702
+ for (const mint of mintInspections) {
703
+ if (mint) {
704
+ flags.push(...mint.flags);
705
+ }
706
+ else {
707
+ flags.push('mint-unreadable');
708
+ }
709
+ }
710
+ return {
711
+ address: market,
712
+ market: decoded,
713
+ mints,
714
+ createdBy: decoded.createdBy,
715
+ createdAt: decoded.createdAt,
716
+ strategy,
717
+ mintInspections,
718
+ flags: orderedFlags(flags),
719
+ };
720
+ }
721
+ //# sourceMappingURL=inspect.js.map