@typesol/cli 0.28.0 → 0.29.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 (40) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +1 -1
  3. package/dist/compiler/analyze.d.ts +3 -1
  4. package/dist/compiler/analyze.js +21 -7
  5. package/dist/compiler/emit/alias.d.ts +48 -0
  6. package/dist/compiler/emit/alias.js +166 -0
  7. package/dist/compiler/emit/borsh.js +6 -3
  8. package/dist/compiler/emit/calls.js +21 -4
  9. package/dist/compiler/emit/cpi-core.d.ts +70 -0
  10. package/dist/compiler/emit/cpi-core.js +356 -0
  11. package/dist/compiler/emit/cpi.d.ts +3 -177
  12. package/dist/compiler/emit/cpi.js +13 -2721
  13. package/dist/compiler/emit/create.d.ts +39 -0
  14. package/dist/compiler/emit/create.js +548 -0
  15. package/dist/compiler/emit/function.d.ts +11 -2
  16. package/dist/compiler/emit/function.js +42 -7
  17. package/dist/compiler/emit/metaplex.d.ts +78 -0
  18. package/dist/compiler/emit/metaplex.js +1345 -0
  19. package/dist/compiler/emit/program.js +24 -4
  20. package/dist/compiler/emit/shared.d.ts +5 -1
  21. package/dist/compiler/emit/shared.js +11 -2
  22. package/dist/compiler/emit/statements.d.ts +0 -9
  23. package/dist/compiler/emit/statements.js +2 -53
  24. package/dist/compiler/emit/storage.d.ts +5 -20
  25. package/dist/compiler/emit/storage.js +40 -106
  26. package/dist/compiler/emit/token.d.ts +8 -0
  27. package/dist/compiler/emit/token.js +493 -0
  28. package/dist/compiler/model.d.ts +10 -2
  29. package/dist/compiler/model.js +7 -1
  30. package/dist/tools/portgen.js +3 -0
  31. package/docs/architecture.md +29 -1
  32. package/docs/audit.md +3 -2
  33. package/docs/case-study-multisig.md +31 -29
  34. package/docs/errors.md +3 -2
  35. package/docs/language.md +4 -3
  36. package/docs/migrate-from-anchor.md +3 -3
  37. package/docs/security-model.md +1 -1
  38. package/lib/typesol.d.ts +17 -6
  39. package/package.json +1 -1
  40. package/runtime/typesol_rt.h +85 -1
@@ -0,0 +1,1345 @@
1
+ import ts from "typescript";
2
+ import { isWritable, optionKey } from "../model.js";
3
+ import { U64, U8, BOOL, PUBKEY, STRING, cBytes } from "./shared.js";
4
+ import { TokenEmitter } from "./token.js";
5
+ /**
6
+ * Bubblegum instructions that replace a leaf: discriminator, accounts in order ([label, writable, signer, optional,
7
+ * either-signs]) and the leaf's shape. Optional accounts take `null` (the program id). The Merkle proof follows the
8
+ * leaf (and metadata) as remaining accounts.
9
+ */
10
+ const BUBBLEGUM_OPS = {
11
+ delegateV2: {
12
+ disc: [95, 87, 125, 140, 181, 131, 128, 227],
13
+ leaf: "delegate",
14
+ accounts: [
15
+ ["treeConfig", true, false],
16
+ ["payer", true, true],
17
+ ["leafOwner", false, true, true],
18
+ ["previousLeafDelegate", false, false, true],
19
+ ["newLeafDelegate", false, false],
20
+ ["merkleTree", true, false],
21
+ ["logWrapper", false, false],
22
+ ["compressionProgram", false, false],
23
+ ["systemProgram", false, false],
24
+ ],
25
+ },
26
+ ...Object.fromEntries([
27
+ ["freezeV2", [200, 151, 244, 102, 16, 195, 255, 3], false],
28
+ ["thawV2", [96, 133, 101, 93, 82, 220, 146, 191], false],
29
+ ["setNonTransferableV2", [181, 141, 206, 58, 242, 199, 152, 168], true],
30
+ ].map(([name, disc, needsCollection]) => [
31
+ name,
32
+ {
33
+ disc: disc,
34
+ leaf: "v2",
35
+ accounts: [
36
+ ["treeConfig", true, false],
37
+ ["payer", true, true],
38
+ ["authority", false, true, true],
39
+ ["leafOwner", false, false],
40
+ ["leafDelegate", false, false, name === "setNonTransferableV2"],
41
+ ["merkleTree", true, false],
42
+ ["coreCollection", false, false, !needsCollection],
43
+ ["logWrapper", false, false],
44
+ ["compressionProgram", false, false],
45
+ ["systemProgram", false, false],
46
+ ],
47
+ },
48
+ ])),
49
+ updateMetadataV2: {
50
+ disc: [43, 103, 89, 42, 121, 242, 62, 72],
51
+ leaf: "meta",
52
+ accounts: [
53
+ ["treeConfig", true, false],
54
+ ["payer", true, true],
55
+ ["authority", false, true, true],
56
+ ["leafOwner", false, false],
57
+ ["leafDelegate", false, false, true],
58
+ ["merkleTree", true, false],
59
+ ["coreCollection", false, false, true],
60
+ ["logWrapper", false, false],
61
+ ["compressionProgram", false, false],
62
+ ["systemProgram", false, false],
63
+ ],
64
+ },
65
+ ...Object.fromEntries([
66
+ ["verifyCreatorV2", [85, 138, 140, 42, 22, 241, 118, 102]],
67
+ ["unverifyCreatorV2", [174, 112, 29, 142, 230, 100, 239, 7]],
68
+ ].map(([name, disc]) => [
69
+ name,
70
+ {
71
+ disc: disc,
72
+ leaf: "meta",
73
+ accounts: [
74
+ ["treeConfig", true, false],
75
+ ["payer", true, true],
76
+ ["creator", false, true, true],
77
+ ["leafOwner", false, false],
78
+ ["leafDelegate", false, false, true],
79
+ ["merkleTree", true, false],
80
+ ["logWrapper", false, false],
81
+ ["compressionProgram", false, false],
82
+ ["systemProgram", false, false],
83
+ ],
84
+ },
85
+ ])),
86
+ setCollectionV2: {
87
+ disc: [229, 35, 61, 91, 15, 14, 99, 160],
88
+ leaf: "meta",
89
+ accounts: [
90
+ ["treeConfig", true, false],
91
+ ["payer", true, true],
92
+ ["authority", false, true, true],
93
+ ["newCollectionAuthority", false, true, true],
94
+ ["leafOwner", false, false],
95
+ ["leafDelegate", false, false, true],
96
+ ["merkleTree", true, false],
97
+ ["coreCollection", true, false, true],
98
+ ["newCoreCollection", true, false, true],
99
+ ["mplCoreCpiSigner", false, false, true],
100
+ ["logWrapper", false, false],
101
+ ["compressionProgram", false, false],
102
+ ["mplCoreProgram", false, false],
103
+ ["systemProgram", false, false],
104
+ ],
105
+ },
106
+ // V1 trees (SPL Account Compression, SPL Noop).
107
+ transfer: {
108
+ disc: [163, 52, 200, 231, 140, 3, 69, 186],
109
+ leaf: "v1",
110
+ accounts: [
111
+ ["treeConfig", false, false],
112
+ ["leafOwner", false, false, false, "owner"],
113
+ ["leafDelegate", false, false, false, "delegate"],
114
+ ["newLeafOwner", false, false],
115
+ ["merkleTree", true, false],
116
+ ["logWrapper", false, false],
117
+ ["compressionProgram", false, false],
118
+ ["systemProgram", false, false],
119
+ ],
120
+ },
121
+ burn: {
122
+ disc: [116, 110, 29, 56, 107, 219, 42, 93],
123
+ leaf: "v1",
124
+ accounts: [
125
+ ["treeConfig", false, false],
126
+ ["leafOwner", false, false, false, "owner"],
127
+ ["leafDelegate", false, false, false, "delegate"],
128
+ ["merkleTree", true, false],
129
+ ["logWrapper", false, false],
130
+ ["compressionProgram", false, false],
131
+ ["systemProgram", false, false],
132
+ ],
133
+ },
134
+ delegate: {
135
+ disc: [90, 147, 75, 178, 85, 88, 4, 137],
136
+ leaf: "v1",
137
+ accounts: [
138
+ ["treeConfig", false, false],
139
+ ["leafOwner", false, false, false, "owner"],
140
+ ["previousLeafDelegate", false, false],
141
+ ["newLeafDelegate", false, false],
142
+ ["merkleTree", true, false],
143
+ ["logWrapper", false, false],
144
+ ["compressionProgram", false, false],
145
+ ["systemProgram", false, false],
146
+ ],
147
+ },
148
+ };
149
+ /** Metaplex Core's Plugin / PluginType enums, in order (MasterEdition, VerifiedCreators and Autograph values are refused). */
150
+ const CORE_PLUGINS = [
151
+ "Royalties",
152
+ "FreezeDelegate",
153
+ "BurnDelegate",
154
+ "TransferDelegate",
155
+ "UpdateDelegate",
156
+ "PermanentFreezeDelegate",
157
+ "Attributes",
158
+ "PermanentTransferDelegate",
159
+ "PermanentBurnDelegate",
160
+ "Edition",
161
+ "MasterEdition",
162
+ "AddBlocker",
163
+ "ImmutableMetadata",
164
+ "VerifiedCreators",
165
+ "Autograph",
166
+ "BubblegumV2",
167
+ "FreezeExecute",
168
+ "PermanentFreezeExecute",
169
+ "Groups",
170
+ ];
171
+ const CORE_PLUGIN_FIELDS = {
172
+ Royalties: ["basisPoints", "creators", "ruleSet"],
173
+ MasterEdition: ["maxSupply", "name", "uri"],
174
+ VerifiedCreators: ["signatures"],
175
+ Autograph: ["signatures"],
176
+ FreezeExecute: ["frozen"],
177
+ PermanentFreezeExecute: ["frozen"],
178
+ FreezeDelegate: ["frozen"],
179
+ PermanentFreezeDelegate: ["frozen"],
180
+ UpdateDelegate: ["additionalDelegates"],
181
+ Attributes: ["attributes"],
182
+ Edition: ["number"],
183
+ };
184
+ /** Metaplex: Token Metadata, Core (plugins and external plugins) and Bubblegum. */
185
+ export class MetaplexEmitter extends TokenEmitter {
186
+ metadataOp(node, program, method) {
187
+ if (method === "createMasterEditionV3" || method === "verifyCollection")
188
+ return this.metadataCollectionOp(node, program, method);
189
+ if (method !== "createV3")
190
+ this.fail(node.expression, `the Token Metadata program supports createV3, createMasterEditionV3 and verifyCollection, not ${method}`);
191
+ const a = node.arguments;
192
+ const usage = "createV3(metadata, mint, mintAuthority, payer, updateAuthority, systemProgram, name, symbol, uri, sellerFeeBasisPoints, isMutable, { creators?, collection?, isCollection? }?, signerSeeds?)";
193
+ // An object literal after isMutable carries the optional creators / collection; signerSeeds stays last.
194
+ const extras = a[11] && ts.isObjectLiteralExpression(a[11]) ? a[11] : undefined;
195
+ const seedsArg = extras ? a[12] : a[11];
196
+ if (a.length < 11 || a.length > (extras ? 13 : 12))
197
+ this.fail(node, usage);
198
+ const [metadata, mint, mintAuth, payer, updateAuth, sys] = a.slice(0, 6).map((n, i) => this.accountParam(n, `account #${i + 1}`));
199
+ if (!isWritable(metadata.kind))
200
+ this.fail(a[0], "the metadata account must be Mut<AccountInfo>");
201
+ if (payer.kind.kind !== "signer" || !payer.kind.mut)
202
+ this.fail(a[3], "the payer must be a Mut<Signer>");
203
+ if (sys.kind.kind !== "system")
204
+ this.fail(a[5], "pass the SystemProgram parameter");
205
+ // Arguments in source order, as JS evaluates them: a later one that runs statements (a helper changing account
206
+ // text) must not change what an earlier one read.
207
+ const vals = [];
208
+ const inOrder = (n, t) => {
209
+ const mark = this.lines.length;
210
+ const v = this.expect(this.expr(n, t), t, n);
211
+ for (let j = 0; j < vals.length; j++)
212
+ vals[j] = this.settle(vals[j], mark);
213
+ vals.push(v);
214
+ return vals.length - 1;
215
+ };
216
+ const slots = [...a.slice(6, 9).map((n) => inOrder(n, STRING)), inOrder(a[9], { kind: "int", name: "u16" }), inOrder(a[10], BOOL)];
217
+ const settleAll = (mark) => {
218
+ for (let j = 0; j < vals.length; j++)
219
+ vals[j] = this.settle(vals[j], mark);
220
+ };
221
+ const extrasMark = this.lines.length;
222
+ let creators = "NULL";
223
+ let ncreators = "-1";
224
+ let collection = "NULL";
225
+ let sized = "false";
226
+ if (extras) {
227
+ for (const p of extras.properties) {
228
+ if (!ts.isPropertyAssignment(p) || !ts.isIdentifier(p.name))
229
+ this.fail(p, "use creators: [...], collection: key and isCollection: boolean");
230
+ if (p.name.text === "creators") {
231
+ if (!ts.isArrayLiteralExpression(p.initializer))
232
+ this.fail(p.initializer, "creators: [{ address, verified, share }, …] (an array literal)");
233
+ const list = p.initializer.elements;
234
+ if (list.length < 1 || list.length > 5)
235
+ this.fail(p.initializer, "Metaplex takes 1 to 5 creators");
236
+ const buf = this.tmp("creators");
237
+ this.line(`uint8_t ${buf}[${34 * list.length}];`);
238
+ let shares = 0n;
239
+ let constant = true;
240
+ list.forEach((el, i) => {
241
+ if (!ts.isObjectLiteralExpression(el))
242
+ this.fail(el, "a creator is { address, verified, share }");
243
+ const field = (k) => {
244
+ const q = el.properties.find((x) => ts.isPropertyAssignment(x) && ts.isIdentifier(x.name) && x.name.text === k);
245
+ const sh = el.properties.find((x) => ts.isShorthandPropertyAssignment(x) && x.name.text === k);
246
+ if (!q && !sh)
247
+ this.fail(el, `a creator needs ${k}`);
248
+ return q ? q.initializer : sh.name;
249
+ };
250
+ const at = 34 * i;
251
+ const key = this.expect(this.expr(field("address"), PUBKEY), PUBKEY, el);
252
+ this.line(`ts_memcpy(${buf} + ${at}, ${key.c}, 32);`);
253
+ const verified = this.expect(this.expr(field("verified"), BOOL), BOOL, el);
254
+ this.line(`${buf}[${at + 32}] = (${verified.c}) ? 1 : 0;`);
255
+ const shareNode = field("share");
256
+ if (ts.isBigIntLiteral(shareNode))
257
+ shares += BigInt(shareNode.text.slice(0, -1));
258
+ else
259
+ constant = false;
260
+ const share = this.expect(this.expr(shareNode, U8), U8, el);
261
+ this.line(`${buf}[${at + 33}] = (uint8_t)(${share.c});`);
262
+ });
263
+ if (constant && shares !== 100n)
264
+ this.fail(p.initializer, `creator shares add up to ${shares}; Metaplex requires 100`);
265
+ creators = buf;
266
+ ncreators = String(list.length);
267
+ }
268
+ else if (p.name.text === "collection") {
269
+ const key = this.expect(this.expr(p.initializer, PUBKEY), PUBKEY, p.initializer);
270
+ const t = this.tmp("coll");
271
+ this.line(`SolPubkey ${t} = *(${key.c});`);
272
+ collection = `&${t}`;
273
+ }
274
+ else if (p.name.text === "isCollection") {
275
+ const v = this.expect(this.expr(p.initializer, BOOL), BOOL, p.initializer);
276
+ const t = this.tmp("sized");
277
+ this.line(`bool ${t} = ${v.c};`);
278
+ sized = t;
279
+ }
280
+ else
281
+ this.fail(p.name, `createV3 extras are creators, collection and isCollection, not ${p.name.text}`);
282
+ }
283
+ }
284
+ const seeds = this.signerSeeds(seedsArg, mintAuth, a[2]);
285
+ settleAll(extrasMark);
286
+ const [name, symbol, uri, fee, mutable] = slots.map((i) => vals[i]);
287
+ this.line(`TS_TRY(ts_mpl_create_v3(params, a_${program.name}, a_${metadata.name}, a_${mint.name}, a_${mintAuth.name}, a_${payer.name}, a_${updateAuth.name}, a_${sys.name}, ${name.c}, ${symbol.c}, ${uri.c}, ${fee.c}, ${mutable.c}, ${creators}, ${ncreators}, ${collection}, ${sized}, ${seeds.name}, ${seeds.count}));`);
288
+ return undefined;
289
+ }
290
+ /** CreateMasterEditionV3 (17) and Verify (52) with VerificationArgs::CollectionV1. */
291
+ metadataCollectionOp(node, program, method) {
292
+ const a = node.arguments;
293
+ const p = `a_${program.name}`;
294
+ const seedsAt = (i) => (a[i] ? this.signingSeeds(a[i]) : { name: "NULL", count: 0 });
295
+ const acct = (i, what, w, s) => {
296
+ if (a[i].kind === ts.SyntaxKind.NullKeyword)
297
+ this.fail(a[i], `pass ${what}`);
298
+ return this.mplMeta(a[i], program, what, w, s);
299
+ };
300
+ if (method === "createMasterEditionV3") {
301
+ if (a.length !== 9 && a.length !== 10)
302
+ this.fail(node, "createMasterEditionV3(edition, mint, updateAuthority, mintAuthority, payer, metadata, tokenProgram, systemProgram, maxSupply | null, signerSeeds?)");
303
+ const metas = [
304
+ acct(0, "the edition", true, false),
305
+ acct(1, "the mint", true, false),
306
+ acct(2, "the update authority", false, true),
307
+ acct(3, "the mint authority", false, true),
308
+ acct(4, "the payer", true, true),
309
+ acct(5, "the metadata", true, false),
310
+ acct(6, "the token program", false, false),
311
+ acct(7, "the system program", false, false),
312
+ ];
313
+ // max_supply: Option<u64>; Some(0) makes a one of one, None allows unlimited prints.
314
+ const data = this.mplData(node, 16, a[8].kind === ts.SyntaxKind.NullKeyword ? [{ bytes: [17, 0] }] : [{ bytes: [17, 1] }, { value: a[8], type: { kind: "int", name: "u64" } }]);
315
+ this.cpi(p, metas, data.buf, data.len, seedsAt(9));
316
+ return undefined;
317
+ }
318
+ // Verify: authority, delegate record (absent: the program id), metadata, collection mint, collection metadata,
319
+ // collection master edition, system program, instructions sysvar.
320
+ if (a.length !== 7 && a.length !== 8)
321
+ this.fail(node, "verifyCollection(authority, metadata, collectionMint, collectionMetadata, collectionMasterEdition, systemProgram, instructionsSysvar, signerSeeds?)");
322
+ const metas = [
323
+ acct(0, "the collection authority", false, true),
324
+ [p, false, false],
325
+ acct(1, "the metadata", true, false),
326
+ acct(2, "the collection mint", false, false),
327
+ acct(3, "the collection metadata", true, false),
328
+ acct(4, "the collection master edition", false, false),
329
+ acct(5, "the system program", false, false),
330
+ acct(6, "the instructions sysvar", false, false),
331
+ ];
332
+ const data = this.mplData(node, 8, [{ bytes: [52, 1] }]);
333
+ this.cpi(p, metas, data.buf, data.len, seedsAt(7));
334
+ return undefined;
335
+ }
336
+ /**
337
+ * One account of a Metaplex CPI: an account parameter, or `null` for an optional account left out
338
+ * (Metaplex programs take their own id in its place).
339
+ */
340
+ mplMeta(n, program, what, writable, signer) {
341
+ if (n.kind === ts.SyntaxKind.NullKeyword)
342
+ return [`a_${program.name}`, false, false];
343
+ const acct = this.accountParam(n, what);
344
+ if (writable && !isWritable(acct.kind))
345
+ this.fail(n, `${what} must be writable (Mut<...>)`);
346
+ return [`a_${acct.name}`, writable, signer];
347
+ }
348
+ /** Borsh fields into a fresh buffer: raw bytes ("u8:N" style) or lowered values. */
349
+ mplData(at, max, fields) {
350
+ const { buf, len, put, finish } = this.byteBuffer("mpl", max, "TS_ERR_INSTRUCTION_DATA", "Metaplex instruction");
351
+ for (const f of fields) {
352
+ if ("bytes" in f) {
353
+ const name = this.tmp("bytes");
354
+ this.line(`static const uint8_t ${name}[${f.bytes.length}] = ${cBytes(f.bytes)};`);
355
+ put(name, String(f.bytes.length), f.bytes.length);
356
+ }
357
+ else if ("c" in f)
358
+ put(f.c, f.n);
359
+ else
360
+ this.serialize(this.expect(this.expr(f.value, f.type), f.type, f.value), f.value, put);
361
+ }
362
+ finish(at);
363
+ return { buf, len };
364
+ }
365
+ /**
366
+ * Borsh of one Metaplex Core plugin literal (`{ kind: "FreezeDelegate", frozen: true, authority?: … }`): the Plugin
367
+ * enum, then (`withAuthority`) the Option<PluginAuthority> that CreateV1's PluginAuthorityPair and AddPluginV1 take.
368
+ */
369
+ corePlugin(n, withAuthority) {
370
+ if (!ts.isObjectLiteralExpression(n))
371
+ this.fail(n, 'a Core plugin is an object literal: { kind: "FreezeDelegate", frozen: false }');
372
+ const props = new Map();
373
+ for (const q of n.properties) {
374
+ if (ts.isPropertyAssignment(q) && ts.isIdentifier(q.name))
375
+ props.set(q.name.text, q.initializer);
376
+ else if (ts.isShorthandPropertyAssignment(q))
377
+ props.set(q.name.text, q.name);
378
+ else
379
+ this.fail(q, "write plugin fields as name: value");
380
+ }
381
+ const kindNode = props.get("kind");
382
+ if (!kindNode || !ts.isStringLiteral(kindNode))
383
+ this.fail(n, 'a Core plugin needs kind: "Royalties" | "FreezeDelegate" | …');
384
+ const kind = kindNode.text;
385
+ const index = CORE_PLUGINS.indexOf(kind);
386
+ if (index < 0)
387
+ this.fail(kindNode, `Core plugins are ${CORE_PLUGINS.join(", ")}`);
388
+ if (kind === "Groups")
389
+ this.fail(kindNode, "Groups is kept by Core's group instructions (AddCollectionsToGroupV1 …), not set as a plugin");
390
+ const known = new Set(["kind", "authority", ...(CORE_PLUGIN_FIELDS[kind] ?? [])]);
391
+ for (const [k, v] of props)
392
+ if (!known.has(k))
393
+ this.fail(v, `${kind} has no field ${k}`);
394
+ const need = (k) => props.get(k) ?? this.fail(n, `${kind} needs ${k}`);
395
+ const list = (k, max) => {
396
+ const e = need(k);
397
+ if (!ts.isArrayLiteralExpression(e))
398
+ this.fail(e, `${k} is an array literal`);
399
+ if (e.elements.length > max)
400
+ this.fail(e, `at most ${max} entries in ${k}`);
401
+ return e.elements;
402
+ };
403
+ const u32 = (x) => [x & 0xff, (x >> 8) & 0xff, (x >> 16) & 0xff, x >>> 24];
404
+ const fields = [{ bytes: [index] }];
405
+ switch (kind) {
406
+ case "Royalties": {
407
+ const bps = need("basisPoints");
408
+ if (ts.isBigIntLiteral(bps) && BigInt(bps.text.slice(0, -1)) > 10000n)
409
+ this.fail(bps, "basisPoints is at most 10000 (100%)");
410
+ fields.push({ value: bps, type: { kind: "int", name: "u16" } });
411
+ const creators = list("creators", 5);
412
+ fields.push({ bytes: u32(creators.length) });
413
+ let sum = 0n;
414
+ let constant = true;
415
+ for (const c of creators) {
416
+ if (!ts.isObjectLiteralExpression(c))
417
+ this.fail(c, "a creator is { address, percentage }");
418
+ const get = (k) => {
419
+ const q = c.properties.find((x) => (ts.isPropertyAssignment(x) || ts.isShorthandPropertyAssignment(x)) && ts.isIdentifier(x.name) && x.name.text === k);
420
+ if (!q)
421
+ this.fail(c, `a creator needs ${k}`);
422
+ return ts.isPropertyAssignment(q) ? q.initializer : q.name;
423
+ };
424
+ const pct = get("percentage");
425
+ if (ts.isBigIntLiteral(pct))
426
+ sum += BigInt(pct.text.slice(0, -1));
427
+ else
428
+ constant = false;
429
+ fields.push({ value: get("address"), type: PUBKEY }, { value: pct, type: U8 });
430
+ }
431
+ if (constant && creators.length && sum !== 100n)
432
+ this.fail(need("creators"), `creator percentages add up to ${sum}; Core requires 100`);
433
+ // rule_set: None, or { programAllowList: [...] } / { programDenyList: [...] }
434
+ const rs = props.get("ruleSet");
435
+ if (!rs)
436
+ fields.push({ bytes: [0] });
437
+ else {
438
+ const pick = ts.isObjectLiteralExpression(rs) && rs.properties.length === 1 ? rs.properties[0] : undefined;
439
+ const which = pick && ts.isPropertyAssignment(pick) && ts.isIdentifier(pick.name) ? pick.name.text : undefined;
440
+ if (!pick ||
441
+ (which !== "programAllowList" && which !== "programDenyList") ||
442
+ !ts.isArrayLiteralExpression(pick.initializer))
443
+ this.fail(rs, "ruleSet is { programAllowList: [programs] } or { programDenyList: [programs] }");
444
+ const progs = pick.initializer.elements;
445
+ if (progs.length > 16)
446
+ this.fail(rs, "at most 16 programs in a rule set");
447
+ fields.push({ bytes: [which === "programAllowList" ? 1 : 2, ...u32(progs.length)] }, ...progs.map((k) => ({ value: k, type: PUBKEY })));
448
+ }
449
+ break;
450
+ }
451
+ case "MasterEdition": {
452
+ // Option<u32>, Option<String>, Option<String>: left out or null is None.
453
+ const opt = (k, t) => {
454
+ const v = props.get(k);
455
+ return !v || v.kind === ts.SyntaxKind.NullKeyword ? [{ bytes: [0] }] : [{ bytes: [1] }, { value: v, type: t }];
456
+ };
457
+ fields.push(...opt("maxSupply", { kind: "int", name: "u32" }), ...opt("name", STRING), ...opt("uri", STRING));
458
+ break;
459
+ }
460
+ case "VerifiedCreators":
461
+ case "Autograph": {
462
+ const sigs = list("signatures", 16);
463
+ fields.push({ bytes: u32(sigs.length) });
464
+ const second = kind === "VerifiedCreators" ? "verified" : "message";
465
+ for (const sg of sigs) {
466
+ if (!ts.isObjectLiteralExpression(sg))
467
+ this.fail(sg, `a signature is { address, ${second} }`);
468
+ const get = (k) => {
469
+ const q = sg.properties.find((x) => (ts.isPropertyAssignment(x) || ts.isShorthandPropertyAssignment(x)) && ts.isIdentifier(x.name) && x.name.text === k);
470
+ if (!q)
471
+ this.fail(sg, `a signature needs ${k}`);
472
+ return ts.isPropertyAssignment(q) ? q.initializer : q.name;
473
+ };
474
+ fields.push({ value: get("address"), type: PUBKEY }, { value: get(second), type: kind === "VerifiedCreators" ? BOOL : STRING });
475
+ }
476
+ break;
477
+ }
478
+ case "FreezeExecute":
479
+ case "PermanentFreezeExecute":
480
+ fields.push({ value: need("frozen"), type: BOOL });
481
+ break;
482
+ case "FreezeDelegate":
483
+ case "PermanentFreezeDelegate":
484
+ fields.push({ value: need("frozen"), type: BOOL });
485
+ break;
486
+ case "UpdateDelegate": {
487
+ const keys = props.has("additionalDelegates") ? list("additionalDelegates", 8) : [];
488
+ fields.push({ bytes: u32(keys.length) }, ...keys.map((k) => ({ value: k, type: PUBKEY })));
489
+ break;
490
+ }
491
+ case "Attributes": {
492
+ const attrs = list("attributes", 32);
493
+ fields.push({ bytes: u32(attrs.length) });
494
+ for (const at of attrs) {
495
+ if (!ts.isObjectLiteralExpression(at))
496
+ this.fail(at, "an attribute is { key, value }");
497
+ for (const k of ["key", "value"]) {
498
+ const q = at.properties.find((x) => (ts.isPropertyAssignment(x) || ts.isShorthandPropertyAssignment(x)) && ts.isIdentifier(x.name) && x.name.text === k);
499
+ if (!q)
500
+ this.fail(at, `an attribute needs ${k}`);
501
+ fields.push({ value: ts.isPropertyAssignment(q) ? q.initializer : q.name, type: STRING });
502
+ }
503
+ }
504
+ break;
505
+ }
506
+ case "Edition":
507
+ fields.push({ value: need("number"), type: { kind: "int", name: "u32" } });
508
+ break;
509
+ }
510
+ const auth = props.get("authority");
511
+ if (!withAuthority) {
512
+ if (auth)
513
+ this.fail(auth, "a plugin's authority is set when it is added; change it with Core's approve / revoke");
514
+ return fields;
515
+ }
516
+ if (!auth)
517
+ fields.push({ bytes: [0] }); // the plugin type's default authority
518
+ else if (ts.isStringLiteral(auth)) {
519
+ const i = ["none", "owner", "updateAuthority"].indexOf(auth.text);
520
+ if (i < 0)
521
+ this.fail(auth, 'authority is "none", "owner", "updateAuthority" or a Pubkey');
522
+ fields.push({ bytes: [1, i] });
523
+ }
524
+ else
525
+ fields.push({ bytes: [1, 3] }, { value: auth, type: PUBKEY });
526
+ return fields;
527
+ }
528
+ /** CreateV1 / CreateCollectionV1 plugins: Option<Vec<PluginAuthorityPair>>. */
529
+ corePluginList(n) {
530
+ if (!n)
531
+ return [{ bytes: [0] }];
532
+ const els = n.elements;
533
+ if (els.length > 16)
534
+ this.fail(n, "at most 16 plugins");
535
+ const kinds = els.map((e) => ts.isObjectLiteralExpression(e) ? e.properties.find((q) => q.name && ts.isIdentifier(q.name) && q.name.text === "kind") : undefined);
536
+ const seen = new Set();
537
+ kinds.forEach((k, i) => {
538
+ const lit = k && ts.isPropertyAssignment(k) && ts.isStringLiteral(k.initializer) ? k.initializer.text : undefined;
539
+ if (lit && seen.has(lit))
540
+ this.fail(els[i], `${lit} is listed twice; an asset has one plugin of each kind`);
541
+ if (lit)
542
+ seen.add(lit);
543
+ });
544
+ return [{ bytes: [1, els.length & 0xff, 0, 0, 0] }, ...els.flatMap((e) => this.corePlugin(e, true))];
545
+ }
546
+ /**
547
+ * Metaplex Core: assets and collections (with plugins), plugins and external plugin adapters added, updated, written
548
+ * and removed, transfer and burn. Each method is a row of CORE_OPS below: its accounts in order, its data.
549
+ */
550
+ coreOp(node, core, method) {
551
+ const a = node.arguments;
552
+ const p = `a_${core.name}`;
553
+ const op = this.coreOps()[method];
554
+ if (!op)
555
+ this.fail(node.expression, `Metaplex Core supports createAsset, createCollection, addPlugin, updatePlugin, removePlugin, addExternalPlugin, removeExternalPlugin, writeExternalPluginData (and the Collection forms), transferAsset and burnAsset, not ${method}`);
556
+ // An array literal of object literals right after the fixed arguments is the plugin list; the signer seeds follow.
557
+ const isPlugins = (n) => !!n && ts.isArrayLiteralExpression(n) && (n.elements.length === 0 || n.elements.every((e) => ts.isObjectLiteralExpression(e)));
558
+ const list = op.plugins && isPlugins(a[op.args]) ? a[op.args] : undefined;
559
+ const seedsAt = op.args + (list ? 1 : 0);
560
+ if (op.plugins ? a.length < op.args || a.length > seedsAt + 1 : a.length !== op.args && a.length !== op.args + 1)
561
+ this.fail(node, op.usage(method));
562
+ const metas = op.metas.map((m) => (m === "self" ? [p, false, false] : this.mplMeta(a[m[0]], core, m[1], m[2], m[3])));
563
+ const data = this.mplData(node, op.max, op.data(a, list));
564
+ this.cpi(p, metas, data.buf, data.len, a[seedsAt] ? this.signingSeeds(a[seedsAt]) : { name: "NULL", count: 0 });
565
+ return undefined;
566
+ }
567
+ /**
568
+ * Core instructions: `args` fixed arguments (then an optional plugin list when `plugins`, then optional signer
569
+ * seeds), accounts in order (`[argument, label, writable, signer]`, or "self": the Core program, Core's "none" for an
570
+ * optional account), at most `max` bytes of data.
571
+ */
572
+ coreOps() {
573
+ const str = (n) => ({ value: n, type: STRING });
574
+ const asset = [0, "the asset", true, false];
575
+ const assetPlugin = {
576
+ usage: (m) => `${m}(asset, collection | null, payer, authority | null, systemProgram, ${m === "removePlugin" ? "kind" : "plugin"}, signerSeeds?)`,
577
+ args: 6,
578
+ // Add/Remove/UpdatePluginV1: asset, collection, payer, authority, systemProgram, logWrapper.
579
+ metas: [
580
+ asset,
581
+ [1, "the collection", true, false],
582
+ [2, "the payer", true, true],
583
+ [3, "the authority", false, true],
584
+ [4, "the system program", false, false],
585
+ "self",
586
+ ],
587
+ max: 2048,
588
+ };
589
+ const collectionPlugin = {
590
+ usage: (m) => `${m}(collection, payer, authority | null, systemProgram, ${m === "removeCollectionPlugin" ? "kind" : "plugin"}, signerSeeds?)`,
591
+ args: 5,
592
+ // Add/Remove/UpdateCollectionPluginV1: collection, payer, authority, systemProgram, logWrapper.
593
+ metas: [
594
+ [0, "the collection", true, false],
595
+ [1, "the payer", true, true],
596
+ [2, "the authority", false, true],
597
+ [3, "the system program", false, false],
598
+ "self",
599
+ ],
600
+ max: 2048,
601
+ };
602
+ const assetPluginOp = (method, disc) => ({
603
+ ...assetPlugin,
604
+ data: (a) => [
605
+ { bytes: [disc] },
606
+ ...(method === "removePlugin" ? [this.corePluginType(a[5])] : this.corePlugin(a[5], method === "addPlugin")),
607
+ ],
608
+ });
609
+ const collectionPluginOp = (method, disc) => ({
610
+ ...collectionPlugin,
611
+ data: (a) => [
612
+ { bytes: [disc] },
613
+ ...(method === "removeCollectionPlugin" ? [this.corePluginType(a[4])] : this.corePlugin(a[4], method === "addCollectionPlugin")),
614
+ ],
615
+ });
616
+ // Add/RemoveExternalPluginAdapterV1: asset, collection, payer, authority, systemProgram, logWrapper; the write has a
617
+ // buffer account (left out: the data is in the instruction) before systemProgram. The Collection forms drop the asset.
618
+ const external = (method, disc, collection) => {
619
+ const write = method.startsWith("write");
620
+ const add = method.startsWith("add");
621
+ const n = (collection ? 5 : 6) + (write ? 1 : 0);
622
+ const at = collection ? 4 : 5;
623
+ const head = collection ? "collection, payer, authority | null, systemProgram" : "asset, collection | null, payer, authority | null, systemProgram";
624
+ const metas = collection
625
+ ? [
626
+ [0, "the collection", true, false],
627
+ [1, "the payer", true, true],
628
+ [2, "the authority", false, true],
629
+ ]
630
+ : [asset, [1, "the collection", true, false], [2, "the payer", true, true], [3, "the authority", false, true]];
631
+ if (write)
632
+ metas.push("self");
633
+ metas.push([collection ? 3 : 4, "the system program", false, false], "self");
634
+ return {
635
+ usage: (m) => `${m}(${head}, ${add ? "plugin" : write ? "key, data" : "key"}, signerSeeds?)`,
636
+ args: n,
637
+ metas,
638
+ max: 1024,
639
+ data: (a) => [
640
+ { bytes: [disc] },
641
+ ...(add
642
+ ? this.coreExternalPlugin(a[at])
643
+ : write
644
+ ? [...this.coreExternalKey(a[at]), ...this.coreExternalData(a[at + 1])]
645
+ : this.coreExternalKey(a[at])),
646
+ ],
647
+ };
648
+ };
649
+ return {
650
+ createAsset: {
651
+ usage: () => "createAsset(asset, collection | null, authority | null, payer, owner | null, systemProgram, name, uri, plugins?, signerSeeds?)",
652
+ args: 8,
653
+ plugins: true,
654
+ // CreateV1: asset, collection, authority, payer, owner, updateAuthority (the collection's, or the payer by
655
+ // default), systemProgram, logWrapper.
656
+ metas: [
657
+ [0, "the asset", true, true],
658
+ [1, "the collection", true, false],
659
+ [2, "the collection authority", false, true],
660
+ [3, "the payer", true, true],
661
+ [4, "the owner", false, false],
662
+ "self",
663
+ [5, "the system program", false, false],
664
+ "self",
665
+ ],
666
+ max: 2048,
667
+ data: (a, plugins) => [{ bytes: [0, 0] }, str(a[6]), str(a[7]), ...this.corePluginList(plugins)],
668
+ },
669
+ createCollection: {
670
+ usage: () => "createCollection(collection, updateAuthority | null, payer, systemProgram, name, uri, plugins?, signerSeeds?)",
671
+ args: 6,
672
+ plugins: true,
673
+ // CreateCollectionV1: collection, updateAuthority, payer, systemProgram.
674
+ metas: [
675
+ [0, "the collection", true, true],
676
+ [1, "the update authority", false, false],
677
+ [2, "the payer", true, true],
678
+ [3, "the system program", false, false],
679
+ ],
680
+ max: 2048,
681
+ data: (a, plugins) => [{ bytes: [1] }, str(a[4]), str(a[5]), ...this.corePluginList(plugins)],
682
+ },
683
+ addPlugin: assetPluginOp("addPlugin", 2),
684
+ removePlugin: assetPluginOp("removePlugin", 4),
685
+ updatePlugin: assetPluginOp("updatePlugin", 6),
686
+ addCollectionPlugin: collectionPluginOp("addCollectionPlugin", 3),
687
+ removeCollectionPlugin: collectionPluginOp("removeCollectionPlugin", 5),
688
+ updateCollectionPlugin: collectionPluginOp("updateCollectionPlugin", 7),
689
+ transferAsset: {
690
+ usage: () => "transferAsset(asset, collection | null, payer, authority | null, newOwner, signerSeeds?)",
691
+ args: 5,
692
+ // TransferV1: asset, collection, payer, authority, newOwner, systemProgram, logWrapper.
693
+ metas: [
694
+ asset,
695
+ [1, "the collection", false, false],
696
+ [2, "the payer", true, true],
697
+ [3, "the authority", false, true],
698
+ [4, "the new owner", false, false],
699
+ "self",
700
+ "self",
701
+ ],
702
+ max: 8,
703
+ data: () => [{ bytes: [14, 0] }],
704
+ },
705
+ burnAsset: {
706
+ usage: () => "burnAsset(asset, collection | null, payer, authority | null, signerSeeds?)",
707
+ args: 4,
708
+ // BurnV1: asset, collection, payer, authority, systemProgram, logWrapper.
709
+ metas: [asset, [1, "the collection", true, false], [2, "the payer", true, true], [3, "the authority", false, true], "self", "self"],
710
+ max: 8,
711
+ data: () => [{ bytes: [12, 0] }],
712
+ },
713
+ addExternalPlugin: external("addExternalPlugin", 22, false),
714
+ removeExternalPlugin: external("removeExternalPlugin", 24, false),
715
+ writeExternalPluginData: external("writeExternalPluginData", 28, false),
716
+ addCollectionExternalPlugin: external("addCollectionExternalPlugin", 23, true),
717
+ removeCollectionExternalPlugin: external("removeCollectionExternalPlugin", 25, true),
718
+ writeCollectionExternalPluginData: external("writeCollectionExternalPluginData", 29, true),
719
+ };
720
+ }
721
+ /** The fields of a Core object literal (`{ kind: "AppData", … }`) by name. */
722
+ coreProps(node, what) {
723
+ let n = node;
724
+ while (ts.isParenthesizedExpression(n) || ts.isAsExpression(n) || ts.isSatisfiesExpression(n))
725
+ n = n.expression;
726
+ if (!ts.isObjectLiteralExpression(n))
727
+ this.fail(n, `${what} is an object literal: { kind: "…", … }`);
728
+ const props = new Map();
729
+ for (const q of n.properties) {
730
+ if (ts.isPropertyAssignment(q) && ts.isIdentifier(q.name))
731
+ props.set(q.name.text, q.initializer);
732
+ else if (ts.isShorthandPropertyAssignment(q))
733
+ props.set(q.name.text, q.name);
734
+ else
735
+ this.fail(q, "write the fields as name: value");
736
+ }
737
+ return props;
738
+ }
739
+ /** PluginAuthority: "none" | "owner" | "updateAuthority" (literals), or an address. */
740
+ coreAuthority(n) {
741
+ if (ts.isStringLiteral(n)) {
742
+ const i = ["none", "owner", "updateAuthority"].indexOf(n.text);
743
+ if (i < 0)
744
+ this.fail(n, 'an authority is "none", "owner", "updateAuthority" or a Pubkey');
745
+ return [{ bytes: [i] }];
746
+ }
747
+ return [{ bytes: [3] }, { value: n, type: PUBKEY }];
748
+ }
749
+ coreOption(n, inner) {
750
+ return n ? [{ bytes: [1] }, ...inner(n)] : [{ bytes: [0] }];
751
+ }
752
+ coreSchema(n) {
753
+ const i = ts.isStringLiteral(n) ? ["binary", "json", "msgpack"].indexOf(n.text) : -1;
754
+ if (i < 0)
755
+ this.fail(n, 'schema is "binary", "json" or "msgpack"');
756
+ return [{ bytes: [i] }];
757
+ }
758
+ /** Vec<(HookableLifecycleEvent, ExternalCheckResult)>: `[{ event: "transfer", canReject: true }, …]`. */
759
+ coreChecks(n, at) {
760
+ if (!n || !ts.isArrayLiteralExpression(n))
761
+ this.fail(n ?? at, 'checks is a list: [{ event: "transfer", canApprove: true, canReject: true }]');
762
+ const out = [{ bytes: [n.elements.length & 0xff, 0, 0, 0] }];
763
+ for (const e of n.elements) {
764
+ const p = this.coreProps(e, "a lifecycle check");
765
+ const ev = p.get("event");
766
+ const i = ev && ts.isStringLiteral(ev) ? ["create", "transfer", "burn", "update", "execute"].indexOf(ev.text) : -1;
767
+ if (i < 0)
768
+ this.fail(ev ?? e, 'event is "create", "transfer", "burn", "update" or "execute"');
769
+ let flags = 0;
770
+ for (const [k, bit] of [
771
+ ["canListen", 1],
772
+ ["canApprove", 2],
773
+ ["canReject", 4],
774
+ ]) {
775
+ const v = p.get(k);
776
+ if (v && v.kind !== ts.SyntaxKind.TrueKeyword && v.kind !== ts.SyntaxKind.FalseKeyword)
777
+ this.fail(v, `${k} is true or false`);
778
+ if (v?.kind === ts.SyntaxKind.TrueKeyword)
779
+ flags |= bit;
780
+ }
781
+ for (const k of p.keys())
782
+ if (!["event", "canListen", "canApprove", "canReject"].includes(k))
783
+ this.fail(e, `a lifecycle check has event, canListen, canApprove and canReject, not ${k}`);
784
+ out.push({ bytes: [i, flags, 0, 0, 0] });
785
+ }
786
+ return out;
787
+ }
788
+ /** ExtraAccount: `{ kind: "address", address, isSigner?, isWritable? }` or a preconfigured one (`{ kind: "owner" }`, …). */
789
+ coreExtraAccount(n) {
790
+ const p = this.coreProps(n, "an extra account");
791
+ const kind = p.get("kind");
792
+ const kinds = ["program", "collection", "owner", "recipient", "asset", "customPda", "address"];
793
+ const i = kind && ts.isStringLiteral(kind) ? kinds.indexOf(kind.text) : -1;
794
+ if (i < 0 || i === 5)
795
+ this.fail(kind ?? n, 'an extra account is { kind: "address", address } or "program", "collection", "owner", "recipient", "asset"');
796
+ const flag = (k) => {
797
+ const v = p.get(k);
798
+ if (v && v.kind !== ts.SyntaxKind.TrueKeyword && v.kind !== ts.SyntaxKind.FalseKeyword)
799
+ this.fail(v, `${k} is true or false`);
800
+ return v?.kind === ts.SyntaxKind.TrueKeyword ? 1 : 0;
801
+ };
802
+ if (i === 6) {
803
+ const addr = p.get("address");
804
+ if (!addr)
805
+ this.fail(n, "an address extra account needs address");
806
+ return [{ bytes: [6] }, { value: addr, type: PUBKEY }, { bytes: [flag("isSigner"), flag("isWritable")] }];
807
+ }
808
+ return [{ bytes: [i, flag("isSigner"), flag("isWritable")] }];
809
+ }
810
+ /**
811
+ * ExternalPluginAdapterInitInfo from a literal: `{ kind: "AppData", dataAuthority, schema? }`, `{ kind: "Oracle",
812
+ * baseAddress, checks, resultsOffset?, baseAddressConfig? }`, `{ kind: "LifecycleHook", hookedProgram, checks,
813
+ * extraAccounts?, dataAuthority?, schema? }` and the Linked forms (collections); `authority?` is the plugin's own.
814
+ */
815
+ coreExternalPlugin(n) {
816
+ const p = this.coreProps(n, "a Core external plugin");
817
+ const kind = p.get("kind");
818
+ const kinds = ["LifecycleHook", "Oracle", "AppData", "LinkedLifecycleHook", "LinkedAppData"];
819
+ const i = kind && ts.isStringLiteral(kind) ? kinds.indexOf(kind.text) : -1;
820
+ if (i < 0)
821
+ this.fail(kind ?? n, `a Core external plugin is ${kinds.join(", ")}`);
822
+ const allowed = {
823
+ 0: ["hookedProgram", "checks", "extraAccounts", "dataAuthority", "schema"],
824
+ 1: ["baseAddress", "checks", "baseAddressConfig", "resultsOffset"],
825
+ 2: ["dataAuthority", "schema"],
826
+ 3: ["hookedProgram", "checks", "extraAccounts", "dataAuthority", "schema"],
827
+ 4: ["dataAuthority", "schema"],
828
+ };
829
+ for (const k of p.keys())
830
+ if (k !== "kind" && k !== "authority" && !allowed[i].includes(k))
831
+ this.fail(n, `${kinds[i]} takes ${allowed[i].join(", ")} and authority, not ${k}`);
832
+ const need = (k) => p.get(k) ?? this.fail(n, `${kinds[i]} needs ${k}`);
833
+ const auth = this.coreOption(p.get("authority"), (x) => this.coreAuthority(x));
834
+ const schema = this.coreOption(p.get("schema"), (x) => this.coreSchema(x));
835
+ if (i === 2 || i === 4)
836
+ return [{ bytes: [i] }, ...this.coreAuthority(need("dataAuthority")), ...auth, ...schema];
837
+ if (i === 1) {
838
+ const offset = p.get("resultsOffset");
839
+ const off = !offset
840
+ ? [{ bytes: [0] }]
841
+ : ts.isStringLiteral(offset) && (offset.text === "none" || offset.text === "anchor")
842
+ ? [{ bytes: [1, offset.text === "none" ? 0 : 1] }]
843
+ : [{ bytes: [1, 2] }, { value: offset, type: U64 }];
844
+ return [
845
+ { bytes: [1] },
846
+ { value: need("baseAddress"), type: PUBKEY },
847
+ ...auth,
848
+ ...this.coreChecks(need("checks"), n),
849
+ ...this.coreOption(p.get("baseAddressConfig"), (x) => this.coreExtraAccount(x)),
850
+ ...off,
851
+ ];
852
+ }
853
+ const extras = p.get("extraAccounts");
854
+ if (extras && !ts.isArrayLiteralExpression(extras))
855
+ this.fail(extras, "extraAccounts is a list of extra accounts");
856
+ return [
857
+ { bytes: [i] },
858
+ { value: need("hookedProgram"), type: PUBKEY },
859
+ ...auth,
860
+ ...this.coreChecks(need("checks"), n),
861
+ ...(extras ? [{ bytes: [1, extras.elements.length & 0xff, 0, 0, 0] }, ...extras.elements.flatMap((e) => this.coreExtraAccount(e))] : [{ bytes: [0] }]),
862
+ ...this.coreOption(p.get("dataAuthority"), (x) => this.coreAuthority(x)),
863
+ ...schema,
864
+ ];
865
+ }
866
+ /** ExternalPluginAdapterKey: `{ kind: "AppData", dataAuthority }`, `{ kind: "Oracle", address }`, `{ kind: "LifecycleHook", address }`, … */
867
+ coreExternalKey(n) {
868
+ const p = this.coreProps(n, "a Core external plugin key");
869
+ const kind = p.get("kind");
870
+ const kinds = ["LifecycleHook", "Oracle", "AppData", "LinkedLifecycleHook", "LinkedAppData"];
871
+ const i = kind && ts.isStringLiteral(kind) ? kinds.indexOf(kind.text) : -1;
872
+ if (i < 0)
873
+ this.fail(kind ?? n, `a Core external plugin key is ${kinds.join(", ")}`);
874
+ if (i === 2 || i === 4)
875
+ return [{ bytes: [i] }, ...this.coreAuthority(p.get("dataAuthority") ?? this.fail(n, `${kinds[i]}'s key is its dataAuthority`))];
876
+ return [
877
+ { bytes: [i] },
878
+ { value: p.get("address") ?? this.fail(n, `${kinds[i]}'s key is its address (the oracle's base address or the hooked program)`), type: PUBKEY },
879
+ ];
880
+ }
881
+ /** The data written: Option<Vec<u8>> from a string, a Vec<u8> argument, or null (clears it). */
882
+ coreExternalData(n) {
883
+ if (n.kind === ts.SyntaxKind.NullKeyword)
884
+ return [{ bytes: [0] }];
885
+ const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
886
+ if (l?.type.kind === "vecArg") {
887
+ if (l.type.elem.kind !== "int" || l.type.elem.name !== "u8")
888
+ this.fail(n, "data is a string, a Vec<u8> argument or null");
889
+ const t = this.tmp("dl");
890
+ this.line(`uint32_t ${t} = (uint32_t)${l.c}.len;`);
891
+ return [{ bytes: [1] }, { c: `&${t}`, n: "4" }, { c: `${l.c}.ptr`, n: `(uint64_t)${t}` }];
892
+ }
893
+ return [{ bytes: [1] }, { value: n, type: STRING }];
894
+ }
895
+ /** PluginType (u8) from a kind string literal: removePlugin(…, "FreezeDelegate"). */
896
+ corePluginType(n) {
897
+ if (!ts.isStringLiteral(n))
898
+ this.fail(n, 'name the plugin kind as a string literal: "FreezeDelegate"');
899
+ const i = CORE_PLUGINS.indexOf(n.text);
900
+ if (i < 0)
901
+ this.fail(n, `Core plugins are ${CORE_PLUGINS.join(", ")}`);
902
+ return { bytes: [i] };
903
+ }
904
+ /** Bubblegum (compressed NFTs on SPL account compression): createTree, mint (MintV1, no collection, no creators). */
905
+ bubblegumOp(node, bg, method) {
906
+ const a = node.arguments;
907
+ const p = `a_${bg.name}`;
908
+ const seedsAt = (i) => (a[i] ? this.signingSeeds(a[i]) : { name: "NULL", count: 0 });
909
+ const acct = (i, what, w, s) => this.mplMeta(a[i], bg, what, w, s);
910
+ switch (method) {
911
+ case "createTree": {
912
+ // CreateTreeConfig: treeConfig, merkleTree, payer, treeCreator, logWrapper, compressionProgram, systemProgram.
913
+ if (a.length !== 10 && a.length !== 11)
914
+ this.fail(node, "createTree(treeConfig, merkleTree, payer, treeCreator, logWrapper, compressionProgram, systemProgram, maxDepth, maxBufferSize, isPublic, signerSeeds?)");
915
+ const metas = [
916
+ acct(0, "the tree config", true, false),
917
+ acct(1, "the merkle tree", true, false),
918
+ acct(2, "the payer", true, true),
919
+ acct(3, "the tree creator", false, true),
920
+ acct(4, "the log wrapper", false, false),
921
+ acct(5, "the compression program", false, false),
922
+ acct(6, "the system program", false, false),
923
+ ];
924
+ const U32 = { kind: "int", name: "u32" };
925
+ const data = this.mplData(node, 32, [
926
+ { bytes: [165, 83, 136, 142, 89, 202, 47, 220] },
927
+ { value: a[7], type: U32 },
928
+ { value: a[8], type: U32 },
929
+ { bytes: [1] }, // public: Some(bool)
930
+ { value: a[9], type: BOOL },
931
+ ]);
932
+ this.cpi(p, metas, data.buf, data.len, seedsAt(10));
933
+ return undefined;
934
+ }
935
+ case "mint": {
936
+ // MintV1: treeConfig, leafOwner, leafDelegate, merkleTree, payer, treeCreatorOrDelegate, logWrapper,
937
+ // compressionProgram, systemProgram; MetadataArgs with no collection, uses or creators.
938
+ if (a.length !== 13 && a.length !== 14)
939
+ this.fail(node, "mint(treeConfig, leafOwner, leafDelegate, merkleTree, payer, treeDelegate, logWrapper, compressionProgram, systemProgram, name, symbol, uri, sellerFeeBasisPoints, signerSeeds?)");
940
+ const metas = [
941
+ acct(0, "the tree config", true, false),
942
+ acct(1, "the leaf owner", false, false),
943
+ acct(2, "the leaf delegate", false, false),
944
+ acct(3, "the merkle tree", true, false),
945
+ acct(4, "the payer", false, true),
946
+ acct(5, "the tree delegate", false, true),
947
+ acct(6, "the log wrapper", false, false),
948
+ acct(7, "the compression program", false, false),
949
+ acct(8, "the system program", false, false),
950
+ ];
951
+ const data = this.mplData(node, 1024, [
952
+ { bytes: [145, 98, 192, 118, 184, 147, 118, 104] },
953
+ { value: a[9], type: STRING },
954
+ { value: a[10], type: STRING },
955
+ { value: a[11], type: STRING },
956
+ { value: a[12], type: { kind: "int", name: "u16" } },
957
+ // primarySaleHappened false, isMutable true, editionNonce None, tokenStandard Some(NonFungible),
958
+ // collection None, uses None, tokenProgramVersion Original, creators [].
959
+ { bytes: [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0] },
960
+ ]);
961
+ this.cpi(p, metas, data.buf, data.len, seedsAt(13));
962
+ return undefined;
963
+ }
964
+ case "mintToCollection": {
965
+ // MintToCollectionV1: MintV1's accounts plus the collection authority (signing), its record PDA (or null),
966
+ // the collection mint, metadata (writable) and master edition, Bubblegum's signer PDA and Token Metadata;
967
+ // MetadataArgs with Some({ verified: false, key: collection mint }) (Bubblegum verifies it).
968
+ if (a.length !== 17 && a.length !== 18)
969
+ this.fail(node, "mintToCollection(treeConfig, leafOwner, leafDelegate, merkleTree, payer, treeDelegate, collectionAuthority, collectionAuthorityRecordPda | null, collectionMint, collectionMetadata, collectionEdition, bubblegumSigner, logWrapper, compressionProgram, tokenMetadataProgram, systemProgram, { name, symbol, uri, sellerFeeBasisPoints, creators?, isMutable?, editionNonce? }, signerSeeds?)");
970
+ const metas = [
971
+ acct(0, "the tree config", true, false),
972
+ acct(1, "the leaf owner", false, false),
973
+ acct(2, "the leaf delegate", false, false),
974
+ acct(3, "the merkle tree", true, false),
975
+ acct(4, "the payer", false, true),
976
+ acct(5, "the tree delegate", false, true),
977
+ acct(6, "the collection authority", false, true),
978
+ acct(7, "the collection authority record", false, false),
979
+ acct(8, "the collection mint", false, false),
980
+ acct(9, "the collection metadata", true, false),
981
+ acct(10, "the collection edition", false, false),
982
+ acct(11, "Bubblegum's signer", false, false),
983
+ acct(12, "the log wrapper", false, false),
984
+ acct(13, "the compression program", false, false),
985
+ acct(14, "Token Metadata", false, false),
986
+ acct(15, "the system program", false, false),
987
+ ];
988
+ const md = a[16];
989
+ if (!ts.isObjectLiteralExpression(md))
990
+ this.fail(md, "the metadata is { name, symbol, uri, sellerFeeBasisPoints, creators?, isMutable?, editionNonce? }");
991
+ const props = this.literalProps(md, ["name", "symbol", "uri", "sellerFeeBasisPoints", "creators", "isMutable", "editionNonce"], "the metadata");
992
+ const need = (k) => props.get(k) ?? this.fail(md, `the metadata needs ${k}`);
993
+ // `collectionMint.key`, read where the call is.
994
+ const key = ts.factory.createPropertyAccessExpression(a[8], "key");
995
+ ts.setTextRange(key, a[8]);
996
+ key.parent = node;
997
+ const nonce = props.get("editionNonce");
998
+ const data = this.mplData(node, 1024, [
999
+ { bytes: [153, 18, 178, 47, 197, 158, 86, 15] },
1000
+ { value: need("name"), type: STRING },
1001
+ { value: need("symbol"), type: STRING },
1002
+ { value: need("uri"), type: STRING },
1003
+ { value: need("sellerFeeBasisPoints"), type: { kind: "int", name: "u16" } },
1004
+ { bytes: [0] }, // primarySaleHappened
1005
+ props.get("isMutable") ? { value: props.get("isMutable"), type: BOOL } : { bytes: [1] },
1006
+ ...(nonce ? [{ bytes: [1] }, { value: nonce, type: U8 }] : [{ bytes: [0] }]),
1007
+ { bytes: [1, 0] }, // tokenStandard Some(NonFungible)
1008
+ { bytes: [1, 0] }, // collection Some({ verified: false, … })
1009
+ { value: key, type: PUBKEY },
1010
+ { bytes: [0, 0] }, // uses None, tokenProgramVersion Original
1011
+ ...this.bubblegumCreators(props.get("creators")),
1012
+ ]);
1013
+ this.cpi(p, metas, data.buf, data.len, seedsAt(17));
1014
+ return undefined;
1015
+ }
1016
+ }
1017
+ return this.bubblegumV2(node, bg, method);
1018
+ }
1019
+ /** Bubblegum V2 (trees on mpl-account-compression with mpl-noop; optional Metaplex Core collections). */
1020
+ bubblegumV2(node, bg, method) {
1021
+ const a = node.arguments;
1022
+ const p = `a_${bg.name}`;
1023
+ const acct = (i, what, w, s) => this.mplMeta(a[i], bg, what, w, s);
1024
+ const seedsAt = (i) => (a[i] ? this.signingSeeds(a[i]) : { name: "NULL", count: 0 });
1025
+ const U32 = { kind: "int", name: "u32" };
1026
+ const U64v = { kind: "int", name: "u64" };
1027
+ const HASH = { kind: "pubkey", hash: true };
1028
+ // The leaf an instruction replaces. "v2": { root, dataHash, creatorHash, assetDataHash?, flags?, nonce, index };
1029
+ // "delegate": the same with collectionHash? before assetDataHash; "meta": { root, assetDataHash?, flags?, nonce,
1030
+ // index } (the hashes come from the metadata passed); "v1": { root, dataHash, creatorHash, nonce, index }.
1031
+ const leafFields = (n, shape = "v2") => {
1032
+ const known = shape === "v1"
1033
+ ? ["root", "dataHash", "creatorHash", "nonce", "index"]
1034
+ : shape === "meta"
1035
+ ? ["root", "assetDataHash", "flags", "nonce", "index"]
1036
+ : ["root", "dataHash", "creatorHash", ...(shape === "delegate" ? ["collectionHash"] : []), "assetDataHash", "flags", "nonce", "index"];
1037
+ if (!ts.isObjectLiteralExpression(n))
1038
+ this.fail(n, `the leaf is { ${known.join(", ")} }`);
1039
+ const props = new Map();
1040
+ for (const q of n.properties) {
1041
+ if (ts.isPropertyAssignment(q) && ts.isIdentifier(q.name))
1042
+ props.set(q.name.text, q.initializer);
1043
+ else if (ts.isShorthandPropertyAssignment(q))
1044
+ props.set(q.name.text, q.name);
1045
+ else
1046
+ this.fail(q, "write leaf fields as name: value");
1047
+ }
1048
+ for (const [k, v] of props)
1049
+ if (!known.includes(k))
1050
+ this.fail(v, `the leaf has no field ${k}`);
1051
+ const need = (k) => props.get(k) ?? this.fail(n, `the leaf needs ${k}`);
1052
+ // Left out or null: None. A value that may be null at run time (`Hash | null`) goes as a Borsh Option.
1053
+ const opt = (k, t) => {
1054
+ const v = props.get(k);
1055
+ if (!v || v.kind === ts.SyntaxKind.NullKeyword)
1056
+ return [{ bytes: [0] }];
1057
+ this.model.options.set(optionKey(t), t);
1058
+ return [{ value: v, type: { kind: "option", inner: t } }];
1059
+ };
1060
+ const hashes = shape === "meta"
1061
+ ? []
1062
+ : [
1063
+ { value: need("dataHash"), type: HASH },
1064
+ { value: need("creatorHash"), type: HASH },
1065
+ ];
1066
+ const tail = [
1067
+ { value: need("nonce"), type: U64v },
1068
+ { value: need("index"), type: U32 },
1069
+ ];
1070
+ if (shape === "v1")
1071
+ return [{ value: need("root"), type: HASH }, ...hashes, ...tail];
1072
+ return [
1073
+ { value: need("root"), type: HASH },
1074
+ ...hashes,
1075
+ ...(shape === "delegate" ? opt("collectionHash", HASH) : []),
1076
+ ...opt("assetDataHash", HASH),
1077
+ ...opt("flags", U8),
1078
+ ...tail,
1079
+ ];
1080
+ };
1081
+ // MetadataArgsV2 from { name, symbol, uri, sellerFeeBasisPoints, primarySaleHappened?, isMutable?, creators?,
1082
+ // collection? } (a leaf's current metadata: the program hashes it to check the leaf).
1083
+ const metadataV2 = (md) => {
1084
+ if (!ts.isObjectLiteralExpression(md))
1085
+ this.fail(md, "the metadata is { name, symbol, uri, sellerFeeBasisPoints, primarySaleHappened?, isMutable?, creators?, collection? }");
1086
+ const props = this.literalProps(md, ["name", "symbol", "uri", "sellerFeeBasisPoints", "primarySaleHappened", "isMutable", "creators", "collection"], "the metadata");
1087
+ const need = (k) => props.get(k) ?? this.fail(md, `the metadata needs ${k}`);
1088
+ const fields = [
1089
+ { value: need("name"), type: STRING },
1090
+ { value: need("symbol"), type: STRING },
1091
+ { value: need("uri"), type: STRING },
1092
+ { value: need("sellerFeeBasisPoints"), type: { kind: "int", name: "u16" } },
1093
+ ];
1094
+ const flag = (k, dflt) => (props.get(k) ? { value: props.get(k), type: BOOL } : { bytes: [dflt] });
1095
+ fields.push(flag("primarySaleHappened", 0), flag("isMutable", 1), { bytes: [1, 0] }); // token_standard: Some(NonFungible)
1096
+ fields.push(...this.bubblegumCreators(props.get("creators")));
1097
+ const coll = props.get("collection");
1098
+ if (!coll || coll.kind === ts.SyntaxKind.NullKeyword)
1099
+ fields.push({ bytes: [0] });
1100
+ else {
1101
+ this.model.options.set("pubkey", PUBKEY);
1102
+ fields.push({ value: coll, type: { kind: "option", inner: PUBKEY } });
1103
+ }
1104
+ return fields;
1105
+ };
1106
+ const proofRange = (n) => {
1107
+ if (!this.ix)
1108
+ this.fail(n, "a Merkle proof comes from remainingAccounts(), so only instructions can pass one");
1109
+ return this.remainingRange(n) ?? this.fail(n, "pass the proof as remainingAccounts() or rest.slice(a, b)");
1110
+ };
1111
+ switch (method) {
1112
+ case "createTreeV2": {
1113
+ // CreateTreeConfigV2: treeConfig, merkleTree, payer, treeCreator, logWrapper, compressionProgram, systemProgram.
1114
+ if (a.length !== 10 && a.length !== 11)
1115
+ this.fail(node, "createTreeV2(treeConfig, merkleTree, payer, treeCreator | null, logWrapper, compressionProgram, systemProgram, maxDepth, maxBufferSize, isPublic, signerSeeds?)");
1116
+ const metas = [
1117
+ acct(0, "the tree config", true, false),
1118
+ acct(1, "the merkle tree", true, false),
1119
+ acct(2, "the payer", true, true),
1120
+ acct(3, "the tree creator", false, true),
1121
+ acct(4, "the log wrapper", false, false),
1122
+ acct(5, "the compression program", false, false),
1123
+ acct(6, "the system program", false, false),
1124
+ ];
1125
+ const data = this.mplData(node, 32, [
1126
+ { bytes: [55, 99, 95, 215, 142, 203, 227, 205] },
1127
+ { value: a[7], type: U32 },
1128
+ { value: a[8], type: U32 },
1129
+ { bytes: [1] },
1130
+ { value: a[9], type: BOOL },
1131
+ ]);
1132
+ this.cpi(p, metas, data.buf, data.len, seedsAt(10));
1133
+ return undefined;
1134
+ }
1135
+ case "mintV2": {
1136
+ // MintV2: treeConfig, payer, treeCreatorOrDelegate, collectionAuthority, leafOwner, leafDelegate, merkleTree,
1137
+ // coreCollection, mplCoreCpiSigner, logWrapper, compressionProgram, mplCoreProgram, systemProgram.
1138
+ const usage = "mintV2(treeConfig, payer, treeDelegate | null, leafOwner, leafDelegate | null, merkleTree, logWrapper, compressionProgram, mplCoreProgram, systemProgram, { name, symbol, uri, sellerFeeBasisPoints, creators?, isMutable? }, { collection, authority, cpiSigner }?, signerSeeds?)";
1139
+ const collection = a[11] && ts.isObjectLiteralExpression(a[11]) ? a[11] : undefined;
1140
+ if (a.length < 11 || a.length > (collection ? 13 : 12))
1141
+ this.fail(node, usage);
1142
+ const md = a[10];
1143
+ if (!ts.isObjectLiteralExpression(md))
1144
+ this.fail(md, "the metadata is { name, symbol, uri, sellerFeeBasisPoints, creators?, isMutable? }");
1145
+ const field = (o, k) => {
1146
+ const q = o.properties.find((x) => (ts.isPropertyAssignment(x) || ts.isShorthandPropertyAssignment(x)) && ts.isIdentifier(x.name) && x.name.text === k);
1147
+ return q ? (ts.isPropertyAssignment(q) ? q.initializer : q.name) : undefined;
1148
+ };
1149
+ for (const q of md.properties)
1150
+ if (!q.name || !ts.isIdentifier(q.name) || !["name", "symbol", "uri", "sellerFeeBasisPoints", "creators", "isMutable"].includes(q.name.text))
1151
+ this.fail(q, "the metadata takes name, symbol, uri, sellerFeeBasisPoints, creators and isMutable");
1152
+ const coll = collection
1153
+ ? ["collection", "authority", "cpiSigner"].map((k) => field(collection, k) ?? this.fail(collection, `the collection needs ${k}`))
1154
+ : undefined;
1155
+ if (collection)
1156
+ for (const q of collection.properties)
1157
+ if (!q.name || !ts.isIdentifier(q.name) || !["collection", "authority", "cpiSigner"].includes(q.name.text))
1158
+ this.fail(q, "the collection is { collection, authority, cpiSigner }");
1159
+ const metas = [
1160
+ acct(0, "the tree config", true, false),
1161
+ acct(1, "the payer", true, true),
1162
+ acct(2, "the tree delegate", false, true),
1163
+ coll ? this.mplMeta(coll[1], bg, "the collection authority", false, true) : [p, false, false],
1164
+ acct(3, "the leaf owner", false, false),
1165
+ acct(4, "the leaf delegate", false, false),
1166
+ acct(5, "the merkle tree", true, false),
1167
+ coll ? this.mplMeta(coll[0], bg, "the core collection", true, false) : [p, false, false],
1168
+ coll ? this.mplMeta(coll[2], bg, "the mpl-core CPI signer", false, false) : [p, false, false],
1169
+ acct(6, "the log wrapper", false, false),
1170
+ acct(7, "the compression program", false, false),
1171
+ acct(8, "the mpl-core program", false, false),
1172
+ acct(9, "the system program", false, false),
1173
+ ];
1174
+ const need = (k) => field(md, k) ?? this.fail(md, `the metadata needs ${k}`);
1175
+ const fields = [
1176
+ { bytes: [120, 121, 23, 146, 173, 110, 199, 205] },
1177
+ { value: need("name"), type: STRING },
1178
+ { value: need("symbol"), type: STRING },
1179
+ { value: need("uri"), type: STRING },
1180
+ { value: need("sellerFeeBasisPoints"), type: { kind: "int", name: "u16" } },
1181
+ { bytes: [0] }, // primary_sale_happened
1182
+ ];
1183
+ const mutable = field(md, "isMutable");
1184
+ fields.push(mutable ? { value: mutable, type: BOOL } : { bytes: [1] });
1185
+ fields.push({ bytes: [1, 0] }); // token_standard: Some(NonFungible)
1186
+ const creators = field(md, "creators");
1187
+ if (creators && !ts.isArrayLiteralExpression(creators))
1188
+ this.fail(creators, "creators: [{ address, verified, share }, …] (an array literal)");
1189
+ const list = creators ? creators.elements : [];
1190
+ if (list.length > 5)
1191
+ this.fail(creators, "Bubblegum takes at most 5 creators");
1192
+ fields.push({ bytes: [list.length, 0, 0, 0] });
1193
+ let shares = 0n;
1194
+ let constant = true;
1195
+ for (const el of list) {
1196
+ if (!ts.isObjectLiteralExpression(el))
1197
+ this.fail(el, "a creator is { address, verified, share }");
1198
+ const f = (k) => field(el, k) ?? this.fail(el, `a creator needs ${k}`);
1199
+ const share = f("share");
1200
+ if (ts.isBigIntLiteral(share))
1201
+ shares += BigInt(share.text.slice(0, -1));
1202
+ else
1203
+ constant = false;
1204
+ fields.push({ value: f("address"), type: PUBKEY }, { value: f("verified"), type: BOOL }, { value: share, type: U8 });
1205
+ }
1206
+ if (list.length && constant && shares !== 100n)
1207
+ this.fail(creators, `creator shares add up to ${shares}; Bubblegum requires 100`);
1208
+ // collection: Some(the core collection's key) when minting into one.
1209
+ if (coll)
1210
+ fields.push({ bytes: [1] }, { value: this.keyOf(coll[0]), type: PUBKEY });
1211
+ else
1212
+ fields.push({ bytes: [0] });
1213
+ fields.push({ bytes: [0, 0] }); // asset_data, asset_data_schema: None
1214
+ const data = this.mplData(node, 1024, fields);
1215
+ this.cpi(p, metas, data.buf, data.len, seedsAt(collection ? 12 : 11));
1216
+ return undefined;
1217
+ }
1218
+ case "transferV2": {
1219
+ // TransferV2: treeConfig, payer, authority, leafOwner, leafDelegate, newLeafOwner, merkleTree, coreCollection,
1220
+ // logWrapper, compressionProgram, systemProgram; the proof follows as remaining accounts.
1221
+ if (a.length !== 13 && a.length !== 14)
1222
+ this.fail(node, "transferV2(treeConfig, payer, authority | null, leafOwner, leafDelegate | null, newLeafOwner, merkleTree, coreCollection | null, logWrapper, compressionProgram, systemProgram, leaf, proof, signerSeeds?)");
1223
+ const metas = [
1224
+ acct(0, "the tree config", true, false),
1225
+ acct(1, "the payer", true, true),
1226
+ acct(2, "the authority", false, true),
1227
+ acct(3, "the leaf owner", false, false),
1228
+ acct(4, "the leaf delegate", false, false),
1229
+ acct(5, "the new leaf owner", false, false),
1230
+ acct(6, "the merkle tree", true, false),
1231
+ acct(7, "the core collection", false, false),
1232
+ acct(8, "the log wrapper", false, false),
1233
+ acct(9, "the compression program", false, false),
1234
+ acct(10, "the system program", false, false),
1235
+ ];
1236
+ const data = this.mplData(node, 160, [{ bytes: [119, 40, 6, 235, 234, 221, 248, 49] }, ...leafFields(a[11])]);
1237
+ this.cpi(p, metas, data.buf, data.len, seedsAt(13), proofRange(a[12]));
1238
+ return undefined;
1239
+ }
1240
+ case "burnV2": {
1241
+ // BurnV2: treeConfig, payer, authority, leafOwner, leafDelegate, merkleTree, coreCollection, mplCoreCpiSigner,
1242
+ // logWrapper, compressionProgram, mplCoreProgram, systemProgram; the proof follows as remaining accounts.
1243
+ if (a.length !== 14 && a.length !== 15)
1244
+ this.fail(node, "burnV2(treeConfig, payer, authority | null, leafOwner, leafDelegate | null, merkleTree, coreCollection | null, mplCoreCpiSigner | null, logWrapper, compressionProgram, mplCoreProgram, systemProgram, leaf, proof, signerSeeds?)");
1245
+ const metas = [
1246
+ acct(0, "the tree config", true, false),
1247
+ acct(1, "the payer", true, true),
1248
+ acct(2, "the authority", false, true),
1249
+ acct(3, "the leaf owner", false, false),
1250
+ acct(4, "the leaf delegate", false, false),
1251
+ acct(5, "the merkle tree", true, false),
1252
+ acct(6, "the core collection", true, false),
1253
+ acct(7, "the mpl-core CPI signer", false, false),
1254
+ acct(8, "the log wrapper", false, false),
1255
+ acct(9, "the compression program", false, false),
1256
+ acct(10, "the mpl-core program", false, false),
1257
+ acct(11, "the system program", false, false),
1258
+ ];
1259
+ const data = this.mplData(node, 160, [{ bytes: [115, 210, 34, 240, 232, 143, 183, 16] }, ...leafFields(a[12])]);
1260
+ this.cpi(p, metas, data.buf, data.len, seedsAt(14), proofRange(a[13]));
1261
+ return undefined;
1262
+ }
1263
+ }
1264
+ const op = BUBBLEGUM_OPS[method];
1265
+ if (op) {
1266
+ // accounts…, [leaf, metadata?, update?], proof, signerSeeds?
1267
+ const nAccounts = op.accounts.length;
1268
+ const extra = op.leaf === "meta" ? (method === "updateMetadataV2" ? 2 : 1) : 0;
1269
+ const proofAt = nAccounts + 1 + extra;
1270
+ if (a.length !== proofAt + 1 && a.length !== proofAt + 2)
1271
+ this.fail(node, `${method}(${op.accounts.map(([l, , , o]) => (o ? `${l} | null` : l)).join(", ")}, leaf${extra ? (extra === 2 ? ", currentMetadata, update" : ", metadata") : ""}, proof, signerSeeds?)`);
1272
+ const hasSeeds = !!a[proofAt + 1];
1273
+ const metas = op.accounts.map(([label, w, s, optional, either], i) => {
1274
+ if (!optional && a[i].kind === ts.SyntaxKind.NullKeyword)
1275
+ this.fail(a[i], `pass ${label}`);
1276
+ const m = this.mplMeta(a[i], bg, label, w, s);
1277
+ // V1 leaf owner / delegate: either may sign (a PDA owner signs with the seeds).
1278
+ if (either)
1279
+ return [
1280
+ m[0],
1281
+ w,
1282
+ either === "owner"
1283
+ ? `(${m[0]}->is_signer || ${hasSeeds})`
1284
+ : `(${m[0]}->is_signer || (${hasSeeds} && ${m[0]} == ${`a_${this.accountParam(a[i - 1], "the leaf owner").name}`}))`,
1285
+ ];
1286
+ return m;
1287
+ });
1288
+ const fields = [{ bytes: op.disc }, ...leafFields(a[nAccounts], op.leaf)];
1289
+ if (op.leaf === "meta")
1290
+ fields.push(...metadataV2(a[nAccounts + 1]));
1291
+ if (method === "updateMetadataV2")
1292
+ fields.push(...this.bubblegumUpdateArgs(a[nAccounts + 2]));
1293
+ const data = this.mplData(node, 2048, fields);
1294
+ this.cpi(p, metas, data.buf, data.len, seedsAt(proofAt + 1), proofRange(a[proofAt]));
1295
+ return undefined;
1296
+ }
1297
+ this.fail(node.expression, `Bubblegum supports createTree, mint, mintToCollection, createTreeV2, mintV2, transferV2, burnV2, ${Object.keys(BUBBLEGUM_OPS).join(", ")}, not ${method}`);
1298
+ }
1299
+ /** Vec<Creator> (address, verified, share) from a literal list; shares add up to 100 when literal. */
1300
+ bubblegumCreators(creators) {
1301
+ if (creators && !ts.isArrayLiteralExpression(creators))
1302
+ this.fail(creators, "creators: [{ address, verified, share }, …] (an array literal)");
1303
+ const list = creators ? creators.elements : [];
1304
+ if (list.length > 5)
1305
+ this.fail(creators, "Bubblegum takes at most 5 creators");
1306
+ const fields = [{ bytes: [list.length, 0, 0, 0] }];
1307
+ let shares = 0n;
1308
+ let constant = true;
1309
+ for (const el of list) {
1310
+ if (!ts.isObjectLiteralExpression(el))
1311
+ this.fail(el, "a creator is { address, verified, share }");
1312
+ const props = this.literalProps(el, ["address", "verified", "share"], "a creator");
1313
+ const f = (k) => props.get(k) ?? this.fail(el, `a creator needs ${k}`);
1314
+ const share = f("share");
1315
+ if (ts.isBigIntLiteral(share))
1316
+ shares += BigInt(share.text.slice(0, -1));
1317
+ else
1318
+ constant = false;
1319
+ fields.push({ value: f("address"), type: PUBKEY }, { value: f("verified"), type: BOOL }, { value: share, type: U8 });
1320
+ }
1321
+ if (list.length && constant && shares !== 100n)
1322
+ this.fail(creators, `creator shares add up to ${shares}; Bubblegum requires 100`);
1323
+ return fields;
1324
+ }
1325
+ /** UpdateArgs: every field optional (left out or null: unchanged). */
1326
+ bubblegumUpdateArgs(n) {
1327
+ if (!ts.isObjectLiteralExpression(n))
1328
+ this.fail(n, "the update is { name?, symbol?, uri?, creators?, sellerFeeBasisPoints?, primarySaleHappened?, isMutable? }");
1329
+ const props = this.literalProps(n, ["name", "symbol", "uri", "creators", "sellerFeeBasisPoints", "primarySaleHappened", "isMutable"], "the update");
1330
+ const opt = (k, t) => {
1331
+ const v = props.get(k);
1332
+ return !v || v.kind === ts.SyntaxKind.NullKeyword ? [{ bytes: [0] }] : [{ bytes: [1] }, { value: v, type: t }];
1333
+ };
1334
+ const creators = props.get("creators");
1335
+ return [
1336
+ ...opt("name", STRING),
1337
+ ...opt("symbol", STRING),
1338
+ ...opt("uri", STRING),
1339
+ ...(creators && creators.kind !== ts.SyntaxKind.NullKeyword ? [{ bytes: [1] }, ...this.bubblegumCreators(creators)] : [{ bytes: [0] }]),
1340
+ ...opt("sellerFeeBasisPoints", { kind: "int", name: "u16" }),
1341
+ ...opt("primarySaleHappened", BOOL),
1342
+ ...opt("isMutable", BOOL),
1343
+ ];
1344
+ }
1345
+ }