sememe 0.0.0-stage → 0.4.21

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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2667 -2
  3. package/bin/sememe.mjs +556 -0
  4. package/index.mjs +48 -0
  5. package/interface/ata-ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL.json +62 -0
  6. package/interface/native-11111111111111111111111111111111.json +226 -0
  7. package/interface/native-ComputeBudget111111111111111111111111111111.json +72 -0
  8. package/interface/raydium-675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8.json +352 -0
  9. package/interface/token-TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA.json +334 -0
  10. package/interface/token-TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb.json +535 -0
  11. package/interface/token-metadata.json +132 -0
  12. package/package.json +71 -4
  13. package/src/account-list.mjs +308 -0
  14. package/src/account-union.mjs +523 -0
  15. package/src/account.mjs +199 -0
  16. package/src/acquire.mjs +145 -0
  17. package/src/adopt.mjs +205 -0
  18. package/src/ata-interface.mjs +276 -0
  19. package/src/ata.mjs +223 -0
  20. package/src/base58.mjs +96 -0
  21. package/src/canonical.mjs +24 -0
  22. package/src/cli-surface.mjs +300 -0
  23. package/src/codec.mjs +1069 -0
  24. package/src/conformance.mjs +431 -0
  25. package/src/corpus/harvest-compute-budget-2026-10-31.json +19122 -0
  26. package/src/corpus/harvest-system-2026-10-31.json +26090 -0
  27. package/src/decode.mjs +286 -0
  28. package/src/dialect.mjs +145 -0
  29. package/src/discriminators.mjs +177 -0
  30. package/src/drift.mjs +172 -0
  31. package/src/gap.mjs +205 -0
  32. package/src/lighthouse.mjs +168 -0
  33. package/src/lock.mjs +440 -0
  34. package/src/native-audit.mjs +56 -0
  35. package/src/native-corpus.mjs +57 -0
  36. package/src/native-interface.mjs +252 -0
  37. package/src/native.mjs +324 -0
  38. package/src/peer.mjs +95 -0
  39. package/src/program-id.mjs +74 -0
  40. package/src/pull.mjs +117 -0
  41. package/src/rawle.mjs +450 -0
  42. package/src/raydium-interface.mjs +747 -0
  43. package/src/raydium.mjs +391 -0
  44. package/src/receipt-digest.mjs +84 -0
  45. package/src/receipt-name.mjs +128 -0
  46. package/src/receipt-order.mjs +56 -0
  47. package/src/shank.mjs +73 -0
  48. package/src/short-forms.mjs +209 -0
  49. package/src/store-read.mjs +250 -0
  50. package/src/store-write.mjs +46 -0
  51. package/src/token-interface.mjs +394 -0
  52. package/src/token-metadata-interface.mjs +371 -0
  53. package/src/token-metadata.mjs +317 -0
  54. package/src/token.mjs +443 -0
  55. package/src/union.mjs +428 -0
  56. package/vendor/anza-solana-sdk/8db406e2edfafa25939ec782b77b5b6f30de164d/LICENSE.txt +201 -0
  57. package/vendor/anza-solana-sdk/8db406e2edfafa25939ec782b77b5b6f30de164d/compute-budget-interface/src/lib.rs +93 -0
  58. package/vendor/anza-solana-sdk/8db406e2edfafa25939ec782b77b5b6f30de164d/system-interface/src/instruction.rs +1899 -0
  59. package/vendor/lighthouse/4c579479c98635e419b1b167f08be02a71604a71/LICENSE +21 -0
  60. package/vendor/lighthouse/4c579479c98635e419b1b167f08be02a71604a71/lighthouse.json +2769 -0
  61. package/vendor/raydium-amm/91739d8d9f5cf347e0ce14ebe4d2bb7069fb31b6/LICENSE +201 -0
  62. package/vendor/raydium-amm/91739d8d9f5cf347e0ce14ebe4d2bb7069fb31b6/program/src/instruction.rs +1189 -0
  63. package/vendor/raydium-amm/91739d8d9f5cf347e0ce14ebe4d2bb7069fb31b6/program/src/state.rs +1348 -0
  64. package/vendor/spl-associated-token-account/fbf5379e7398ac8b231c73ee8a9ff677b43dd0ec/LICENSE +201 -0
  65. package/vendor/spl-associated-token-account/fbf5379e7398ac8b231c73ee8a9ff677b43dd0ec/interface/src/instruction.rs +169 -0
  66. package/vendor/spl-associated-token-account/fbf5379e7398ac8b231c73ee8a9ff677b43dd0ec/interface/src/lib.rs +12 -0
  67. package/vendor/spl-associated-token-account/fbf5379e7398ac8b231c73ee8a9ff677b43dd0ec/program/src/processor.rs +308 -0
  68. package/vendor/spl-token/737788ff5bcc3f1f44cfb222f25483187650be76/LICENSE.txt +176 -0
  69. package/vendor/spl-token/737788ff5bcc3f1f44cfb222f25483187650be76/interface/src/instruction.rs +1963 -0
  70. package/vendor/spl-token-2022/5251dcc07ecbcb721d6c4f0231090defadf00311/LICENSE.txt +176 -0
  71. package/vendor/spl-token-2022/5251dcc07ecbcb721d6c4f0231090defadf00311/interface/src/instruction.rs +2868 -0
  72. package/vendor/spl-token-metadata-interface/7038969ec74a89f1afdb9bc97c112d4d26fead9a/LICENSE +201 -0
  73. package/vendor/spl-token-metadata-interface/7038969ec74a89f1afdb9bc97c112d4d26fead9a/interface/src/error.rs +58 -0
  74. package/vendor/spl-token-metadata-interface/7038969ec74a89f1afdb9bc97c112d4d26fead9a/interface/src/instruction.rs +596 -0
  75. package/vendor/spl-token-metadata-interface/7038969ec74a89f1afdb9bc97c112d4d26fead9a/interface/src/lib.rs +21 -0
  76. package/vendor/spl-token-metadata-interface/7038969ec74a89f1afdb9bc97c112d4d26fead9a/interface/src/state.rs +229 -0
package/src/union.mjs ADDED
@@ -0,0 +1,428 @@
1
+ // Union decode: one payload against TWO verified interface sources, with the
2
+ // disagreement made explicit and arbitrated by bytes, not by preference.
3
+ //
4
+ // Why this exists: the pump.fun measurement (research/traffic-coverage-2026-10-30.json)
5
+ // showed that a deployed program's own on-chain IDL account and its first-party
6
+ // published copy DISAGREE about real mainnet traffic — 996 payloads, same window:
7
+ // on-chain alone 669/996 decoded
8
+ // published alone 880/996 decoded
9
+ // union of both 914/996 decoded
10
+ // The union there was a hand-merged IDL inside a measurement tool. This module is
11
+ // the product form of that result: both sources stay intact, every decode names
12
+ // which source produced it, and the two sources must answer the same question:
13
+ //
14
+ // - Both decode to the SAME name and args -> 'agree'
15
+ // - Both decode, same name, different args -> 'layout_drift'; the winner is
16
+ // chosen by byte evidence: the source whose re-encode reproduces the WHOLE
17
+ // payload explains the bytes the other only prefixes (measured: the
18
+ // published `partial_fill` argument on `buy`-family instructions — real
19
+ // long-form payloads leave 1 unexplained byte under the on-chain layout).
20
+ // When both or neither explain fully, the primary wins and the drift is
21
+ // reported, not hidden.
22
+ // - One refuses, the other decodes -> 'fallback_secondary' — but ONLY
23
+ // if the surviving decode re-encodes to the actual bytes (full or
24
+ // described prefix). A second source that names bytes it cannot reproduce
25
+ // is refused, exactly like a first source would be.
26
+ // - Names differ on the same discriminator -> hard refusal. Two different
27
+ // names for the same bytes is an interface conflict, not a decode: guessing
28
+ // either one would launder it.
29
+ // - Both refuse -> refusal with BOTH named reasons.
30
+ //
31
+ // Nothing here mutates either source. Discriminator gaps are filled per source
32
+ // with Anchor's rule (src/discriminators.mjs) before decoding, so two legacy
33
+ // sources can be compared at all; stored discriminators are never touched.
34
+
35
+ import { decodeData, encodeInstructionData, encodeEventData, toJsonSafe } from './codec.mjs';
36
+ import { withDerivedDiscriminators, snakeCase, globalDiscriminator } from './discriminators.mjs';
37
+ import { diffArgsByNormalisedName } from './drift.mjs';
38
+
39
+ const MAX_DIFF_PATHS = 20;
40
+
41
+ /** Named refusal carrying the verdict, so callers can tally without parsing text. */
42
+ export class UnionRefusal extends Error {
43
+ constructor(verdict, message, details) {
44
+ super(message);
45
+ this.name = 'UnionRefusal';
46
+ this.verdict = verdict;
47
+ this.details = details ?? {};
48
+ }
49
+ }
50
+
51
+ const reasonOf = (error) => String(error?.message ?? error).slice(0, 200);
52
+
53
+ /**
54
+ * Decode + re-encode under one source's own layout; every fact stays per-source.
55
+ *
56
+ * `absentPolicy` is passed through to the decoder. With 'report' a source that
57
+ * declares one field more than the wire carries can still decode — and then
58
+ * the re-encode MUST omit exactly the fields the decode reported absent, or
59
+ * the bytes would not reproduce and the decode would look like a guess. The
60
+ * absent list therefore travels from decode to re-encode: byte-exactness is
61
+ * what makes an absent field honest instead of invented.
62
+ */
63
+ function probe(source, bytes, absentPolicy) {
64
+ try {
65
+ const decoded = decodeData(source.idl, bytes, { trailing: 'report', absent: absentPolicy });
66
+ const reencoded = decoded.kind === 'instruction'
67
+ ? encodeInstructionData(source.idl, decoded.instruction, decoded.args, { absent: decoded.absent })
68
+ : encodeEventData(source.idl, decoded.event, decoded.args, { tagged: decoded.tagged });
69
+ const described = bytes.subarray(0, decoded.consumed);
70
+ return {
71
+ ok: true,
72
+ decoded,
73
+ fullExact: reencoded.equals(bytes),
74
+ describedExact: reencoded.equals(described),
75
+ };
76
+ } catch (error) {
77
+ return { ok: false, reason: reasonOf(error) };
78
+ }
79
+ }
80
+
81
+ /** Prepare one caller-verified IDL: fill discriminator gaps per source, keep counts.
82
+ * The source's identity (`idlMeta`, `objectPath`) rides along so the winning
83
+ * side's provenance can be quoted in the result. */
84
+ function prepare(source) {
85
+ const { idl: filledIdl, filled, conflicts } = withDerivedDiscriminators(source.idl);
86
+ // The STORED discriminators, kept per instruction name: a rename is
87
+ // recognized by the bytes, not by a name similarity — see the rename check
88
+ // in unionDecode. Stored means any non-empty byte array the source
89
+ // published (HADRo stores 1-byte discriminators) — the same "stored is
90
+ // stored at any length" rule as src/discriminators.mjs; the old length===8
91
+ // gate silently dropped every short stored byte from this evidence map.
92
+ const stored = new Map();
93
+ for (const ix of source.idl?.instructions ?? []) {
94
+ if (ix && typeof ix.name === 'string' && Array.isArray(ix.discriminator) && ix.discriminator.length > 0) {
95
+ stored.set(ix.name, Buffer.from(ix.discriminator).toString('hex'));
96
+ }
97
+ }
98
+ return {
99
+ ...source,
100
+ idl: filledIdl,
101
+ storedDiscriminators: stored,
102
+ discriminatorDerivation: {
103
+ filledInstructions: filled.instructions,
104
+ filledEvents: filled.events,
105
+ conflicts: conflicts.length,
106
+ },
107
+ };
108
+ }
109
+
110
+ /** Field paths where two decoded arg trees disagree (bounded, stable order). */
111
+ /**
112
+ * Field paths where two decoded instruction or event trees disagree,
113
+ * compared by NORMALISED spelling (src/drift.mjs).
114
+ *
115
+ * `paths.paths` lists the REAL differences in data or shape;
116
+ * `paths.spellingOnly` lists the fields both copies declare under different
117
+ * names. Returns the existing `{ paths, truncated }` shape tests pin.
118
+ */
119
+ function diffPaths(primaryArgs, secondaryArgs) {
120
+ const diff = diffArgsByNormalisedName(primaryArgs, secondaryArgs, { max: MAX_DIFF_PATHS });
121
+ return {
122
+ paths: diff.paths,
123
+ truncated: diff.truncated,
124
+ differs: diff.differs,
125
+ spellingOnly: diff.spellingOnly,
126
+ };
127
+ }
128
+
129
+ function decodeFields(source, probeResult, bytes) {
130
+ const { decoded } = probeResult;
131
+ const described = bytes.subarray(0, decoded.consumed);
132
+ return {
133
+ kind: decoded.kind,
134
+ instruction: decoded.kind === 'instruction' ? decoded.instruction : undefined,
135
+ event: decoded.kind === 'event' ? decoded.event : undefined,
136
+ name: decoded.kind === 'instruction' ? decoded.instruction : decoded.event,
137
+ discriminator: decoded.discriminator,
138
+ tagged: decoded.tagged,
139
+ args: toJsonSafe(decoded.args),
140
+ // Declared fields this source's layout does not carry in these bytes.
141
+ // Non-empty means the wire is SHORTER than the interface says — the
142
+ // caller can see that instead of having to infer it from missing keys.
143
+ absent: decoded.absent ?? [],
144
+ bytes: bytes.length,
145
+ consumed: decoded.consumed,
146
+ trailing: decoded.trailing,
147
+ roundTripByteExact: probeResult.fullExact,
148
+ describedRoundTripByteExact: probeResult.describedExact,
149
+ describedBytes: described.length,
150
+ };
151
+ }
152
+
153
+ function resultEnvelope(program, fields, winnerSource, view) {
154
+ return {
155
+ program,
156
+ ...fields,
157
+ // Provenance of the decode: WHICH verified source produced the answer, and
158
+ // what the OTHER source said. `idl` describes the winning source only.
159
+ idl: winnerSource.idlMeta,
160
+ object: winnerSource.objectPath,
161
+ view,
162
+ };
163
+ }
164
+
165
+ /**
166
+ * Decode `bytes` against a primary and an optional secondary interface source.
167
+ *
168
+ * Both IDLs must already be store-verified by the caller (receipt re-hash etc.)
169
+ * — this module deliberately does not re-verify, it arbitrates. Sources are
170
+ * `{ label, idl, idlMeta, objectPath }`; `idlMeta` is quoted verbatim in the
171
+ * result's `idl` field (fingerprint/slot/source/receipt of the winning side).
172
+ *
173
+ * Returns the decoded result on 'agree' | 'layout_drift' | 'fallback_secondary'
174
+ * | 'single_source'; throws `UnionRefusal` for 'name_conflict', a secondary
175
+ * fallback without byte evidence, and total refusal.
176
+ */
177
+ export function unionDecode({ program, primary, secondary, bytes, absent, additional = [] }) {
178
+ // An adopted copy is a VERIFIED source like any other: it may stand alone
179
+ // when there is no on-chain pull to sit next to. The acquisition gap
180
+ // (a program with no pullable IDL account — measured for Jupiter Liquidity
181
+ // and Raydium AMM v4 in the traffic sample) produced stores that hold a
182
+ // published copy and nothing else; refusing those with "needs a primary
183
+ // source" reported "no interface" about a store that has one, and made the
184
+ // union flag disagree with the plain decode on the same bytes.
185
+ // What an adopted copy must NEVER do is DISPLACE an on-chain pull: that is
186
+ // still the primary whenever one exists.
187
+ const soleSource = !primary?.idl && secondary?.idl ? secondary : null;
188
+ if (!primary?.idl && !soleSource) throw new UnionRefusal('invalid_input', 'unionDecode needs a primary source');
189
+ // The payload bytes are normalized to a Buffer here, not merely CHECKED
190
+ // for being one. The union path compares the re-encoded bytes with the
191
+ // input (`reencoded.equals(bytes)`), and a plain Uint8Array has no
192
+ // `equals`; the old check refused such input outright, which made the
193
+ // base58 CLI path fail on every payload with "unionDecode needs the
194
+ // payload bytes as a Buffer" while the same bytes as hex decoded fine.
195
+ // A caller may hand over any byte array; the shape of the input must not
196
+ // decide whether it decodes.
197
+ if (!(bytes instanceof Uint8Array)) {
198
+ throw new UnionRefusal('invalid_input', 'unionDecode needs the payload bytes as a Buffer');
199
+ }
200
+ bytes = Buffer.isBuffer(bytes)
201
+ ? bytes
202
+ : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
203
+ // 'error' is the default and keeps the whole product strict. 'report' is the
204
+ // opt-in that lets a source decode a wire form SHORTER than its own layout
205
+ // declares — measured as chain-accepted on mainnet (research/
206
+ // short-form-wire-forms-2026-11-03.json).
207
+ const absentPolicy = absent ?? 'error';
208
+ if (absentPolicy !== 'report' && absentPolicy !== 'error') {
209
+ throw new UnionRefusal('invalid_input', `unknown absent policy ${JSON.stringify(absent)}`);
210
+ }
211
+ const prim = prepare(soleSource ?? primary);
212
+ const sec = secondary?.idl && secondary !== soleSource ? prepare(secondary) : null;
213
+ // Whether the sources that answered came from the chain at all. A source with
214
+ // no slot is an ADOPTED copy, and a store holding only adopted copies has no
215
+ // on-chain answer — the verdict must say so even when the pair is full.
216
+ const primAdopted = prim.idlMeta?.slot === null || prim.idlMeta?.slot === undefined;
217
+ const secAdopted = !sec || sec.idlMeta?.slot === null || sec.idlMeta?.slot === undefined;
218
+ const adoptedOnly = primAdopted && secAdopted;
219
+
220
+ const primProbe = probe(prim, bytes, absentPolicy);
221
+ const secProbe = sec ? probe(sec, bytes, absentPolicy) : null;
222
+
223
+ const sourceView = (source, probeResult) => probeResult === null
224
+ ? { label: source?.label ?? null, present: false }
225
+ : {
226
+ label: source.label,
227
+ present: true,
228
+ // The copy this view describes, named by content. A view that only
229
+ // carries a LABEL cannot be compared with the plain reader's answer:
230
+ // the label holds the origin the caller typed, the fingerprint holds
231
+ // the bytes. The disagreement this fixes was invisible without it.
232
+ fingerprint: source.idlMeta?.fingerprint ?? null,
233
+ receipt: source.idlMeta?.receipt ?? null,
234
+ decoded: probeResult.ok,
235
+ refusedReason: probeResult.ok ? undefined : probeResult.reason,
236
+ name: probeResult.ok ? probeResult.decoded.kind === 'instruction'
237
+ ? probeResult.decoded.instruction : probeResult.decoded.event : undefined,
238
+ roundTripByteExact: probeResult.ok ? probeResult.fullExact : undefined,
239
+ describedRoundTripByteExact: probeResult.ok ? probeResult.describedExact : undefined,
240
+ trailingBytes: probeResult.ok ? probeResult.decoded.trailing.count : undefined,
241
+ absentFields: probeResult.ok ? (probeResult.decoded.absent ?? []).length : undefined,
242
+ };
243
+
244
+ const view = {
245
+ primary: sourceView(prim, primProbe),
246
+ secondary: sourceView(sec, secProbe),
247
+ sourcesAgree: null,
248
+ // Every source that answered came from an adopted copy iff no real slot
249
+ // is behind either consulted source — set once, for every verdict, so the
250
+ // flag cannot disagree with the sources that were actually read.
251
+ adoptedOnly,
252
+ additionalSources: additional.map((a) => ({
253
+ label: a.label,
254
+ fingerprint: a.idlMeta?.fingerprint,
255
+ receipt: a.idlMeta?.receipt,
256
+ })),
257
+ };
258
+
259
+ // Single source: behave like a plain decode, but say so.
260
+ if (!sec) {
261
+ if (!primProbe.ok) {
262
+ throw new UnionRefusal('refused',
263
+ `decode refused by the only stored source (${prim.label}): ${primProbe.reason}`,
264
+ { view });
265
+ }
266
+ const fields = decodeFields(prim, primProbe, bytes);
267
+ view.verdict = 'single_source';
268
+ view.adoptedOnly = adoptedOnly;
269
+ view.arbitration = { winner: prim.label, basis: 'only_source', evidence: primProbe.fullExact ? 'full_roundtrip' : 'described_roundtrip' };
270
+ return resultEnvelope(program, fields, prim, view);
271
+ }
272
+
273
+ view.discriminatorDerivation = { primary: prim.discriminatorDerivation, secondary: sec.discriminatorDerivation };
274
+
275
+ // Both refuse: the payload is refused, with both named reasons visible.
276
+ if (!primProbe.ok && !secProbe.ok) {
277
+ throw new UnionRefusal('refused',
278
+ `both stored sources refuse this payload — ${prim.label}: ${primProbe.reason}; ${sec.label}: ${secProbe.reason}`,
279
+ { view });
280
+ }
281
+
282
+ // Primary refuses, secondary decodes: only byte evidence admits the fallback.
283
+ if (!primProbe.ok && secProbe.ok) {
284
+ if (!secProbe.fullExact && !secProbe.describedExact) {
285
+ throw new UnionRefusal('union_fallback_refused',
286
+ `${prim.label} refuses (${primProbe.reason}); ${sec.label} names `
287
+ + `"${secProbe.decoded.kind === 'instruction' ? secProbe.decoded.instruction : secProbe.decoded.event}" `
288
+ + `but cannot re-encode the bytes, so the fallback is refused`,
289
+ { view });
290
+ }
291
+ const fields = decodeFields(sec, secProbe, bytes);
292
+ view.verdict = 'fallback_secondary';
293
+ view.sourcesAgree = false;
294
+ view.arbitration = {
295
+ winner: sec.label,
296
+ basis: 'primary_refused',
297
+ evidence: secProbe.fullExact ? 'full_roundtrip' : 'described_roundtrip',
298
+ };
299
+ return resultEnvelope(program, fields, sec, view);
300
+ }
301
+
302
+ // Secondary refuses, primary decodes: plain primary decode, refusal recorded.
303
+ if (primProbe.ok && !secProbe.ok) {
304
+ const fields = decodeFields(prim, primProbe, bytes);
305
+ view.verdict = 'primary_only';
306
+ view.sourcesAgree = false;
307
+ view.arbitration = {
308
+ winner: prim.label,
309
+ basis: 'secondary_refused',
310
+ evidence: primProbe.fullExact ? 'full_roundtrip' : 'described_roundtrip',
311
+ };
312
+ return resultEnvelope(program, fields, prim, view);
313
+ }
314
+
315
+ // Both decode. Same discriminator matched by both sources (decodeData works
316
+ // on discriminators), so the NAMES must agree — two different names for the
317
+ // same bytes is an interface conflict, not a decode.
318
+ const primFields = decodeFields(prim, primProbe, bytes);
319
+ const secFields = decodeFields(sec, secProbe, bytes);
320
+ //
321
+ // Measured exception (2026-11-04, step-ingestooor sweep, 31 payloads across
322
+ // hubble/dca/farms/vaults/perps/marginfi/tuna/referrals): Anchor's own rule
323
+ // derives the INSTRUCTION discriminator from the snake-cased name
324
+ // (sha256("global:" + snake_case(name))[0..8]), so two sources that matched
325
+ // the same 8 bytes and differ only in naming CONVENTION (`closeDca` vs
326
+ // `close_dca`, `repayLoan` vs `repay_loan`) are describing ONE wire
327
+ // instruction — refusing it would refuse real, successfully executed
328
+ // traffic over a spelling difference. That case is DECODED, the convention
329
+ // difference recorded under `view.namingConvention`, the on-chain name kept
330
+ // as the answer. EVENTS stay strict: their discriminator hashes the raw
331
+ // name (no snake_case), so two event names that differ at all are two
332
+ // different claimed schemas for the same bytes.
333
+ if (primFields.name !== secFields.name || primFields.kind !== secFields.kind) {
334
+ const sameInstructionTwoConventions = primFields.kind === 'instruction'
335
+ && secFields.kind === 'instruction'
336
+ && snakeCase(primFields.name) === snakeCase(secFields.name);
337
+ const storedDisc = (source, name) => source.storedDiscriminators?.get(name) ?? null;
338
+ const ruleDisc = (name) => Buffer.from(globalDiscriminator(name)).toString('hex');
339
+ const renamedByPrimary = storedDisc(prim, primFields.name) === ruleDisc(secFields.name);
340
+ const renamedBySecondary = storedDisc(sec, secFields.name) === ruleDisc(primFields.name);
341
+ // The convention check comes FIRST: for `closeDca` vs `close_dca` Anchor's
342
+ // rule yields the same discriminator either way, so both the convention
343
+ // and the rename test would match — but it is one instruction under two
344
+ // spellings, not a rename, and the recorded `kind` must say so.
345
+ const sameInstructionRenamed = !sameInstructionTwoConventions
346
+ && primFields.kind === 'instruction'
347
+ && secFields.kind === 'instruction'
348
+ && (renamedByPrimary || renamedBySecondary);
349
+ if (!sameInstructionTwoConventions && !sameInstructionRenamed) {
350
+ throw new UnionRefusal('name_conflict',
351
+ `interface conflict on the same bytes: ${prim.label} says "${primFields.name}", `
352
+ + `${sec.label} says "${secFields.name}" — refusing instead of picking a winner`,
353
+ { view: { ...view, primary: { ...view.primary, name: primFields.name }, secondary: { ...view.secondary, name: secFields.name } } });
354
+ }
355
+ view.namingConvention = {
356
+ primary: primFields.name,
357
+ secondary: secFields.name,
358
+ kind: sameInstructionRenamed ? 'rename' : 'naming-convention',
359
+ rule: sameInstructionRenamed
360
+ ? "anchor: the primary's stored discriminator equals sha256('global:' + snake_case(secondary name))[0..8] — same wire instruction, renamed by the program; the on-chain name answers"
361
+ : "anchor: sha256('global:' + snake_case(name))[0..8] — same instruction, two naming conventions; the on-chain name answers",
362
+ };
363
+ }
364
+
365
+ // Arbitration by bytes, strongest evidence first:
366
+ // 1. A source that re-encodes the WHOLE payload explains every byte.
367
+ // 2. Otherwise, the source with FEWER unexplained trailing bytes explains
368
+ // strictly more of the same bytes (measured on pump.fun events: the
369
+ // on-chain TradeEvent copy declares 34 fields and leaves 16 bytes
370
+ // unexplained, the published copy declares the additional
371
+ // creator_fee_unclaimed: u64 and leaves 8; both still leave the known
372
+ // 8-byte tail, so the disagreement stays REPORTED under `drift`).
373
+ // When the evidence does not decide, the primary stands and the drift is
374
+ // reported — never hidden, never resolved by preference.
375
+ let winner = prim;
376
+ let basis = 'primary_by_default';
377
+ let evidence = primProbe.fullExact ? 'full_roundtrip' : (primProbe.describedExact ? 'described_roundtrip' : null);
378
+ const primTrailing = primProbe.decoded.trailing.count;
379
+ const secTrailing = secProbe.decoded.trailing.count;
380
+ if (secProbe.fullExact && !primProbe.fullExact) {
381
+ winner = sec;
382
+ basis = 'byte_evidence_full_roundtrip';
383
+ evidence = 'full_roundtrip';
384
+ } else if (!primProbe.fullExact && !secProbe.fullExact
385
+ && primProbe.describedExact && secProbe.describedExact
386
+ && secTrailing < primTrailing) {
387
+ winner = sec;
388
+ basis = 'byte_evidence_fewer_unexplained_bytes';
389
+ evidence = `trailing ${secTrailing} < ${primTrailing}`;
390
+ }
391
+
392
+ // The two copies AGREE about the data or they do not. A field that one
393
+ // copy spells `inAmount` and the other spells `in_amount` is the same
394
+ // field; the spelling is not a disagreement about the bytes. Before this
395
+ // rule the union compared the two argument trees with raw JSON equality,
396
+ // so a naming difference produced the verdict `layout_drift` with paths
397
+ // that listed only the differing spellings (measured 2026-11-09: ALL 643
398
+ // meteora-damm-v1 instruction rows were pure spelling differences —
399
+ // `inAmount` in one, `in_amount` in the other, both decoding to the same
400
+ // values). The report told the caller the two copies disagreed about the
401
+ // data about fields whose data was identical.
402
+ const diff = diffPaths(primFields.args, secFields.args);
403
+ const argsAgree = !diff.differs;
404
+ const fields = winner === prim ? primFields : secFields;
405
+ view.sourcesAgree = argsAgree;
406
+ view.arbitration = { winner: winner.label, basis, evidence };
407
+
408
+ if (!argsAgree) {
409
+ view.verdict = 'layout_drift';
410
+ view.drift = {
411
+ paths: diff,
412
+ primaryExplainsFully: primProbe.fullExact,
413
+ secondaryExplainsFully: secProbe.fullExact,
414
+ primaryTrailingBytes: primTrailing,
415
+ secondaryTrailingBytes: secTrailing,
416
+ note: 'both sources decoded the same bytes to different arguments; the winner was chosen by byte evidence where it decides, otherwise the primary stands and the drift is reported',
417
+ };
418
+ } else {
419
+ view.verdict = 'agree';
420
+ if (diff.spellingOnly.length > 0) {
421
+ view.naming = {
422
+ spellingOnly: diff.spellingOnly,
423
+ note: 'the two copies spell the same fields differently and decode them to the same values; the naming difference is reported, it is not a disagreement about the data',
424
+ };
425
+ }
426
+ }
427
+ return resultEnvelope(program, fields, winner, view);
428
+ }
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.