@pipeline-sol/sdk 0.0.0-stage → 0.1.1

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